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
29,846
InitAlloc.cpp
supercollider_supercollider/lang/LangSource/InitAlloc.cpp
/* 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 "InitAlloc.h" #include "malloc_aligned.hpp" AllocPool* pyr_pool_compile = nullptr; AllocPool* pyr_pool_runtime = nullptr; #define AREASIZE 65536L static void* pyr_new_area(size_t size) { return nova::malloc_aligned(size); } static void pyr_free_area(void* ptr) { nova::free_aligned(ptr); } static void* pyr_new_area_from_runtime(size_t size) { void* ptr = pyr_pool_runtime->Alloc(size); MEMFAIL(ptr); return ptr; } static void pyr_free_area_from_runtime(void* ptr) { pyr_pool_runtime->Free(ptr); } SCLANG_DLLEXPORT_C bool pyr_init_mem_pools(int runtime_space, int runtime_grow) { pyr_pool_runtime = new AllocPool(pyr_new_area, pyr_free_area, runtime_space, runtime_grow); if (!pyr_pool_runtime) return false; pyr_pool_compile = new AllocPool(pyr_new_area_from_runtime, pyr_free_area_from_runtime, 0L, AREASIZE); if (!pyr_pool_compile) return false; // pyr_pool_runtime->DoCheckPool(); return true; }
1,847
C++
.cpp
39
43.179487
106
0.737723
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
29,847
GC.cpp
supercollider_supercollider/lang/LangSource/GC.cpp
/* 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 "GC.h" #include "PyrKernel.h" #include "PyrObjectProto.h" #include "PyrSymbol.h" #include "InitAlloc.h" #include <string.h> #include <stdexcept> #define PAUSETIMES 0 double pauseBeginTime = 0.; double totalPauseTime = 0.; double maxPauseTime = 0.; double minPauseTime = 1e9; int pauseCount = 0; int numPausesGreaterThanOneMillisecond = 0; int maxPauseStackScans = 0; int maxPauseFlips = 0; int maxPauseScans = 0; int maxPausePartialScans = 0; int maxPauseNumToScan = 0; int maxPauseSlotsScanned = 0; int checkStackScans = 0; int checkFlips = 0; int checkNumToScan = 0; int checkScans = 0; int checkPartialScans = 0; int checkSlotsScanned = 0; double elapsedTime(); inline void PyrGC::beginPause() { checkStackScans = mStackScans; checkFlips = mFlips; checkScans = mScans; checkNumToScan = mNumToScan; checkPartialScans = mNumPartialScans; checkSlotsScanned = mSlotsScanned; pauseBeginTime = elapsedTime(); } inline void PyrGC::endPause() { double pauseTime = elapsedTime() - pauseBeginTime; if (pauseTime > 0.001) numPausesGreaterThanOneMillisecond++; if (pauseTime > maxPauseTime) { maxPauseTime = pauseTime; maxPauseStackScans = mStackScans - checkStackScans; maxPauseFlips = mFlips - checkFlips; maxPauseScans = mScans - checkScans; maxPauseNumToScan = checkNumToScan; maxPausePartialScans = mNumPartialScans - checkPartialScans; maxPauseSlotsScanned = mSlotsScanned - checkSlotsScanned; } if (pauseTime < minPauseTime) minPauseTime = pauseTime; totalPauseTime += pauseTime; pauseCount++; } void PyrGC::reportPause() { post("pauses %d\n", pauseCount); post("total pause time %g\n", totalPauseTime); post("num pauses > 1 ms %d\n", numPausesGreaterThanOneMillisecond); post("avg pause time %g\n", totalPauseTime / pauseCount); post("min pause time %g\n", minPauseTime); post("max pause time %g\n", maxPauseTime); post("max pause scans %d\n", maxPauseScans); post("max pause partial obj scans %d\n", maxPausePartialScans); post("max pause num to scan %d\n", maxPauseNumToScan); post("max pause flips %d\n", maxPauseFlips); post("max pause stack scans %d\n", maxPauseStackScans); post("max pause slots scanned %d\n", maxPauseSlotsScanned); pauseBeginTime = 0.; totalPauseTime = 0.; maxPauseTime = 0.; minPauseTime = 1e9; pauseCount = 0; numPausesGreaterThanOneMillisecond = 0; } #if PAUSETIMES # define BEGINPAUSE beginPause(); # define ENDPAUSE endPause(); # define REPORTPAUSE reportPause(); #else # define BEGINPAUSE # define ENDPAUSE # define REPORTPAUSE #endif /* --- list segments: black gray white free sweep scan phase: clear list of new nonlocal reached objects. when a non local object is reached, mark it, and put it on the list if not retained. sweep phase: send any new retained objects to other system send any no longer reatined objects to the other system. send this list to enqueue finalization messages finalize: call finalize method, move from sweep area to free area list of nonlocal objects. list of nonlocal reached objects. */ void fatalerror(const char* str); void fatalerror(const char* str) { fputs(str, stderr); postfl(str); throw std::runtime_error(str); // exit(-1); } inline int ScanSize(PyrObjectHdr* obj) { return obj->obj_format <= obj_slot ? obj->size : 0; } HOT void PyrGC::ScanSlots(PyrSlot* inSlots, long inNumToScan) { if (inNumToScan == 0) return; unsigned char whiteColor = mWhiteColor; unsigned char greyColor = mGreyColor; mSlotsScanned += inNumToScan; int foundGreyObjects = 0; PyrObjectHdr* grey = &mGrey; PyrObjectHdr* greyNext = grey->next; PyrSlot* slot = inSlots; PyrSlot* endslot = inSlots + inNumToScan; do { if (IsObj(slot)) { PyrObject* obj = slotRawObject(slot); if (obj->gc_color == whiteColor) { /* used to be ToGrey2(obj), but rearranged for slightly better performance * * move obj from white to grey */ PyrObjectHdr* objPrev = obj->prev; PyrObjectHdr* objNext = obj->next; /* link in grey set */ greyNext->prev = obj; grey->next = obj; obj->prev = grey; obj->next = greyNext; greyNext = obj; // remove from old set objNext->prev = objPrev; objPrev->next = objNext; obj->gc_color = greyColor; foundGreyObjects++; } } ++slot; } while (slot != endslot); mNumGrey += foundGreyObjects; } void GCSet::Init(int inGCSet) { mBlack.classptr = nullptr; mBlack.obj_sizeclass = inGCSet; mBlack.size = 0; mBlack.gc_color = obj_gcmarker; mWhite.classptr = nullptr; mWhite.obj_sizeclass = inGCSet; mWhite.size = 0; mWhite.gc_color = obj_gcmarker; mFree = &mBlack; mBlack.next = &mWhite; mWhite.next = &mBlack; mBlack.prev = &mWhite; mWhite.prev = &mBlack; } void GCSet::MajorFlip() { // move all white items to beginning of free list mFree = mWhite.next; if (!PyrGC::IsMarker(mBlack.next)) { // move all black items to white list mWhite.next = mBlack.next; mFree->prev = mWhite.prev; mBlack.next->prev = &mWhite; mWhite.prev->next = mFree; // black list empty mBlack.next = &mWhite; mWhite.prev = &mBlack; } } void GCSet::MinorFlip() { // move all white items to beginning of free list mFree = mWhite.next; } PyrProcess* newPyrProcess(VMGlobals* g, PyrClass* procclassobj); PyrGC::PyrGC(VMGlobals* g, AllocPool* inPool, PyrClass* mainProcessClass, long poolSize) { mVMGlobals = g; mPool = inPool; // mCurSet = 0; mNumToScan = 0; mFlips = 0; mCollects = 0; mAllocTotal = 0; mNumAllocs = 0; mScans = 0; mStackScans = 0; mNumPartialScans = 0; mSlotsScanned = 0; mGreyColor = 3 << 2; mBlackColor = 2 << 2; mWhiteColor = 1 << 2; mFreeColor = 0; mRunning = false; mCanSweep = false; mPartialScanObj = nullptr; mPartialScanSlot = 0; mUncollectedAllocations = 0; mGrey.classptr = nullptr; mGrey.obj_sizeclass = 0; mGrey.size = 0; mGrey.gc_color = obj_gcmarker; mGrey.prev = &mGrey; mGrey.next = &mGrey; mNumGrey = 0; mNewPool.Init(mPool, poolSize, poolSize, 9000); // initialize treadmills for (int i = 0; i < kNumGCSets; ++i) { mSets[i].Init(i); } g->process = nullptr; // initPyrThread checks to see if process has been started mProcess = newPyrProcess(g, mainProcessClass); mStack = slotRawObject(&slotRawThread(&mProcess->mainThread)->stack); ToBlack(mStack); SetNil(&slotRawThread(&mProcess->mainThread)->stack); mNumGrey = 0; ToGrey2(mProcess); g->sp = mStack->slots - 1; g->process = mProcess; mRunning = true; SanityCheck(); // assert(SanityCheck()); } PyrObject* PyrGC::NewPermanent(size_t inNumBytes, long inFlags, long inFormat) { // obtain size info int32 alignedSize = (inNumBytes + kAlignMask) & ~kAlignMask; // 16 byte align int32 numSlots = alignedSize / sizeof(PyrSlot); numSlots = numSlots < 1 ? 1 : numSlots; int32 sizeclass = LOG2CEIL(numSlots); sizeclass = sc_min(sizeclass, kNumGCSizeClasses - 1); int32 allocSize = sizeof(PyrObjectHdr) + (sizeof(PyrSlot) << sizeclass); // allocate permanent objects PyrObject* obj = (PyrObject*)pyr_pool_runtime->Alloc(allocSize); MEMFAIL(obj); obj->gc_color = obj_permanent; obj->next = obj->prev = nullptr; obj->obj_sizeclass = sizeclass; obj->obj_format = inFormat; obj->obj_flags = inFlags; obj->size = 0; obj->classptr = class_object; return obj; } void PyrGC::BecomePermanent(PyrObject* inObject) { if (IsGrey(inObject)) mNumGrey--; DLRemove(inObject); inObject->gc_color = obj_permanent; inObject->obj_flags |= obj_immutable; inObject->next = inObject->prev = inObject; } void PyrGC::BecomeImmutable(PyrObject* inObject) { inObject->obj_flags |= obj_immutable; } void DumpBackTrace(VMGlobals* g); HOT PyrObject* PyrGC::New(size_t inNumBytes, long inFlags, long inFormat, bool inRunCollection) { PyrObject* obj = nullptr; if (inFlags & obj_permanent) { return NewPermanent(inNumBytes, inFlags, inFormat); } #ifdef GC_SANITYCHECK SanityCheck(); #endif // obtain size info int32 alignedSize = (inNumBytes + kAlignMask) & ~kAlignMask; // 16 byte align int32 numSlots = alignedSize / sizeof(PyrSlot); numSlots = numSlots < 1 ? 1 : numSlots; int32 sizeclass = LOG2CEIL(numSlots); sizeclass = sc_min(sizeclass, kNumGCSizeClasses - 1); int32 credit = 1L << sizeclass; mAllocTotal += credit; mNumAllocs++; mNumToScan += credit; obj = Allocate(inNumBytes, sizeclass, inRunCollection); obj->obj_format = inFormat; obj->obj_flags = inFlags & 255; obj->size = 0; obj->classptr = class_object; obj->gc_color = mWhiteColor; #ifdef GC_SANITYCHECK SanityCheck(); #endif return obj; } HOT PyrObject* PyrGC::NewFrame(size_t inNumBytes, long inFlags, long inFormat, bool inAccount) { PyrObject* obj = nullptr; #ifdef GC_SANITYCHECK SanityCheck(); #endif // obtain size info int32 alignedSize = (inNumBytes + kAlignMask) & ~kAlignMask; // 16 byte align int32 numSlots = alignedSize / sizeof(PyrSlot); numSlots = numSlots < 1 ? 1 : numSlots; int32 sizeclass = LOG2CEIL(numSlots); sizeclass = sc_min(sizeclass, kNumGCSizeClasses - 1); int32 credit = 1L << sizeclass; mAllocTotal += credit; mNumAllocs++; mNumToScan += credit; obj = Allocate(inNumBytes, sizeclass, inAccount); obj->obj_format = inFormat; obj->obj_flags = inFlags; obj->size = 0; obj->classptr = class_frame; obj->gc_color = mWhiteColor; #ifdef GC_SANITYCHECK SanityCheck(); #endif return obj; } PyrObject* PyrGC::NewFinalizer(ObjFuncPtr finalizeFunc, PyrObject* inObject, bool inRunCollection) { PyrObject* obj = nullptr; #ifdef GC_SANITYCHECK SanityCheck(); #endif // obtain size info int32 sizeclass = 1; int32 credit = 1L << sizeclass; mNumToScan += credit; mAllocTotal += credit; mNumAllocs++; if (inRunCollection && mNumToScan >= kScanThreshold) { Collect(); } GCSet* gcs = mSets + kFinalizerSet; obj = (PyrObject*)gcs->mFree; if (!IsMarker(obj)) { // from free list gcs->mFree = obj->next; } else { if (sizeclass > kMaxPoolSet) { SweepBigObjects(); int32 allocSize = sizeof(PyrObjectHdr) + (sizeof(PyrSlot) << sizeclass); obj = (PyrObject*)mPool->Alloc(allocSize); } else { int32 allocSize = sizeof(PyrObjectHdr) + (sizeof(PyrSlot) << sizeclass); obj = (PyrObject*)mNewPool.Alloc(allocSize); } if (!obj) { post("Finalizer alloc failed.\n"); MEMFAILED; } DLInsertAfter(&gcs->mWhite, obj); } obj->obj_sizeclass = sizeclass; obj->obj_format = obj_slot; obj->obj_flags = 0; obj->size = 2; obj->classptr = class_finalizer; obj->gc_color = mWhiteColor; SetPtr(obj->slots + 0, (void*)finalizeFunc); SetObject(obj->slots + 1, inObject); #ifdef GC_SANITYCHECK SanityCheck(); #endif return obj; } void PyrGC::SweepBigObjects() { if (!mCanSweep) return; for (int i = kMaxPoolSet + 1; i < kNumGCSizeClasses; ++i) { GCSet* gcs = mSets + i; PyrObjectHdr* obj = gcs->mFree; if (!IsMarker(obj)) { // unlink chain of free objects gcs->mFree = obj->prev->next = &gcs->mBlack; gcs->mBlack.prev = obj->prev; do { PyrObjectHdr* nextobj = obj->next; void* ptr = (void*)obj; mPool->Free(ptr); obj = nextobj; } while (!IsMarker(obj)); } } mCanSweep = false; } void PyrGC::CompletePartialScan(PyrObject* obj) { if (mPartialScanObj == obj) { int32 remain = obj->size - mPartialScanSlot; ScanSlots(mPartialScanObj->slots + mPartialScanSlot, remain); } } HOT void PyrGC::DoPartialScan(int32 inObjSize) { int32 remain = inObjSize - mPartialScanSlot; mNumPartialScans++; if (remain <= 0) { mPartialScanObj = nullptr; mNumToScan -= 4; if (mNumToScan < 0) mNumToScan = 0; return; } int32 numtoscan = sc_min(remain, mNumToScan); ScanSlots(mPartialScanObj->slots + mPartialScanSlot, numtoscan); if (numtoscan == remain) { mPartialScanObj = nullptr; mNumToScan -= numtoscan + 4; } else { mPartialScanSlot += numtoscan; mNumToScan -= numtoscan; } if (mNumToScan < 0) mNumToScan = 0; // post("partial %5d xx %4d %2d %s\n", mScans, mNumToScan, mNumGrey); // post("partial %5d %2d %4d %2d %s\n", mScans, i, mNumToScan, mNumGrey, slotRawSymbol(&obj->classptr->name)->name); } HOT bool PyrGC::ScanOneObj() { // Find a set that has a grey object PyrObject* obj; obj = (PyrObject*)mGrey.next; if (IsMarker(obj)) { if (mNumGrey) fatalerror("grey count error\n"); return false; } /*if (!IsGrey(obj)) { postfl("Object on grey list not grey %d %d\n", obj->gc_color, mGreyColor); fatalerror("C1"); }*/ mScans++; // post("-> scan %d %d %d\n", mNumGrey, IsGrey(obj), mNumToScan); // Found a grey object // move obj from grey to black ToBlack(obj); int32 size = ScanSize(obj); // post("<- scan %d %d %d %d\n", mNumGrey, IsGrey(obj), mNumToScan, size); if (size > mNumToScan + 32) { mPartialScanObj = obj; mPartialScanSlot = 0; DoPartialScan(size); } else if (size > 0) { ScanSlots(obj->slots, size); mNumToScan -= 1L << obj->obj_sizeclass; if (mNumToScan < 0) mNumToScan = 0; } else { mNumToScan -= 1L << obj->obj_sizeclass; if (mNumToScan < 0) mNumToScan = 0; } return true; } void PyrGC::ScanStack() { // scan the stack PyrObject* obj = mStack; VMGlobals* g = mVMGlobals; PyrSlot* slot = obj->slots; int32 size = obj->size = g->sp - slot + 1; ScanSlots(slot, size); } void PyrGC::ScanFrames() { VMGlobals* g = mVMGlobals; PyrFrame* frame = g->frame; while (frame) { #if 1 // this is more incremental if (IsWhite(frame)) { ToGrey2(frame); } #else // this is more efficient if (!IsBlack(frame)) { ToBlack(frame); int32 size = ScanSize(frame); PyrSlot* slots = ((PyrObject*)frame)->slots; ScanSlots(slots, size); } #endif frame = slotRawFrame(&frame->caller); } } void PyrGC::Flip() { #ifdef GC_SANITYCHECK SanityCheck(); #endif ScanFinalizers(); GCSet* gcs = mSets; if ((mFlips & 3) == 0) { // major flip for (int i = 0; i < kNumGCSets; ++i, ++gcs) { gcs->MajorFlip(); } // advance colors mBlackColor += 4; mWhiteColor += 4; mGreyColor += 4; mFreeColor += 4; } else { // minor flip for (int i = 0; i < kNumGCSets; ++i, ++gcs) { gcs->MinorFlip(); } } // move root to grey area mNumGrey = 0; ToGrey2(mProcess); ToBlack(mStack); // reset counts mNumToScan = 0; mCanSweep = true; mFlips++; // post("flips %d collects %d nalloc %d alloc %d grey %d\n", mFlips, mCollects, mNumAllocs, mAllocTotal, // mNumGrey); #ifdef GC_SANITYCHECK SanityCheck(); #endif } void PyrGC::FullCollection() { Collect(100000000); // collect space SweepBigObjects(); } void PyrGC::Collect(int32 inNumToScan) { mNumToScan = sc_max(mNumToScan, inNumToScan); Collect(); // collect space } HOT void PyrGC::Collect() { BEGINPAUSE bool stackScanned = false; mCollects++; #ifdef GC_SANITYCHECK SanityCheck(); #endif if (mNumToScan > 0) { // post("->Collect ns %d ng %d s %d\n", mNumToScan, mNumGrey, mScans); // DumpInfo(); mNumToScan += mNumToScan >> 3; // post("->Collect2 ns %d ng %d s %d\n", mNumToScan, mNumGrey, mScans); // mCurSet = 0; while (mNumToScan > 0) { while (mNumToScan > 0 && (mNumGrey > 0 || mPartialScanObj)) { if (mPartialScanObj) { DoPartialScan(ScanSize(mPartialScanObj)); } else { if (!ScanOneObj()) break; } } if (mNumGrey == 0 && mPartialScanObj == nullptr) { if (!stackScanned) { stackScanned = true; mStackScans++; ScanStack(); ScanFrames(); } if (mNumGrey == 0 && mPartialScanObj == nullptr && stackScanned) { Flip(); break; } } } // post("<-Collect ns %d ng %d s %d\n", mNumToScan, mNumGrey, mScans); // DumpInfo(); // post("size9:\n"); // TraceAnyPathToObjsOfSize(9); // post("greys:\n"); // TraceAnyPathToAllGrey(); } // post("mNumToScan %d\n", mNumToScan); mUncollectedAllocations = 0; #ifdef GC_SANITYCHECK SanityCheck(); #endif ENDPAUSE } void PyrGC::Finalize(PyrObject* finalizer) { if (!IsPtr(finalizer->slots + 0)) return; if (!IsObj(finalizer->slots + 1)) return; ObjFuncPtr func = (ObjFuncPtr)slotRawPtr(&finalizer->slots[0]); PyrObject* obj = slotRawObject(&finalizer->slots[1]); // post("FINALIZE %s %p\n", slotRawSymbol(&obj->classptr->name)->name, obj); (func)(mVMGlobals, obj); SetNil(obj->slots + 0); SetNil(obj->slots + 1); } void PyrGC::ScanFinalizers() { GCSet* gcs = &mSets[kFinalizerSet]; PyrObjectHdr* obj = gcs->mWhite.next; PyrObjectHdr* firstFreeObj = gcs->mFree; while (obj != firstFreeObj) { Finalize((PyrObject*)obj); obj = obj->next; } } void PyrGC::RunAllFinalizers() { GCSet* gcs = &mSets[kFinalizerSet]; PyrObjectHdr* obj = gcs->mBlack.next; while (!IsMarker(obj)) { Finalize((PyrObject*)obj); obj = obj->next; } obj = gcs->mWhite.next; PyrObjectHdr* firstFreeObj = gcs->mFree; while (obj != firstFreeObj) { Finalize((PyrObject*)obj); obj = obj->next; } obj = mGrey.next; while (!IsMarker(obj)) { if (obj->classptr == class_finalizer) Finalize((PyrObject*)obj); obj = obj->next; } } bool PyrGC::SanityCheck2() { int numgrey = 0; PyrObjectHdr* grey = mGrey.next; while (!IsMarker(grey)) { numgrey++; if (!IsGrey(grey)) { postfl("sc Object on grey list not grey %d %d %d\n", grey->gc_color, mGreyColor, numgrey); return false; } grey = grey->next; } // postfl("sc %d %d\n", mNumGrey, numgrey); return mNumGrey == numgrey; } bool PyrGC::SanityCheck() { if (!mRunning) return true; // postfl("PyrGC::SanityCheck\n"); bool res = LinkSanity() && ListSanity() // && SanityMarkObj((PyrObject*)mProcess,NULL,0) && SanityMarkObj(mStack,NULL,0) // && SanityClearObj((PyrObject*)mProcess,0) && SanityClearObj(mStack,0) && SanityCheck2(); // if (!res) DumpInfo(); // if (!res) Debugger(); return res; } bool PyrGC::ListSanity() { bool found; if (StackDepth() < 0) { fprintf(stderr, "stack underflow %d\n", (int)StackDepth()); return false; } // postfl("PyrGC::ListSanity\n"); for (int i = 0; i < kNumGCSets; ++i) { PyrObjectHdr* obj; GCSet* set = mSets + i; // check black marker obj = &set->mBlack; if (!IsMarker(obj)) { // debugf("set %d black marker color wrong %d %p\n", i, obj->gc_color, obj); fprintf(stderr, "set %d black marker color wrong %d %p\n", i, obj->gc_color, obj); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); return false; } // check white marker obj = &set->mWhite; if (!IsMarker(obj)) { // debugf("set %d white marker color wrong %d %p\n", i, obj->gc_color, obj); fprintf(stderr, "set %d white marker color wrong %d %p\n", i, obj->gc_color, obj); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); return false; } // check free pointer between white and black marker if (set->mFree != &set->mBlack) { obj = set->mWhite.next; found = false; while (!IsMarker(obj)) { if (obj == set->mFree) { found = true; break; } obj = obj->next; } if (!found) { // debugf("set %d free pointer not between white and black\n", i); fprintf(stderr, "set %d free pointer not between white and black\n", i); fprintf(stderr, "set->mFree %p\n", set->mFree); fprintf(stderr, "set->mWhite %p\n", &set->mWhite); fprintf(stderr, "set->mBlack %p\n", &set->mBlack); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)set->mFree); fprintf(stderr, "black %d white %d grey %d\n", mBlackColor, mWhiteColor, mGreyColor); obj = &set->mWhite; int count = 0; do { if (obj == set->mFree) fprintf(stderr, "%4d %p %3d %d FREE\n", count, obj, obj->gc_color, obj->obj_sizeclass); else if (obj == &set->mWhite) fprintf(stderr, "%4d %p %3d %d WHITE\n", count, obj, obj->gc_color, obj->obj_sizeclass); else if (obj == &set->mBlack) fprintf(stderr, "%4d %p %3d %d BLACK\n", count, obj, obj->gc_color, obj->obj_sizeclass); else fprintf(stderr, "%4d %p %3d %d\n", count, obj, obj->gc_color, obj->obj_sizeclass); obj = obj->next; count++; } while (obj != &set->mWhite); return false; } } // scan black list obj = set->mBlack.next; while (!IsMarker(obj)) { if (obj->gc_color != mBlackColor) { // debugf("set %d black list obj color wrong %d (%d, %d, %d) %p\n", // i, obj->gc_color, mBlackColor, mGreyColor, mWhiteColor, obj); fprintf(stderr, "set %d black list obj color wrong %d (%d, %d, %d) %p\n", i, obj->gc_color, mBlackColor, mGreyColor, mWhiteColor, obj); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); return false; } if (GetGCSet(obj) != set) { // debugf("set %d black obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); fprintf(stderr, "set %d black obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); setPostFile(stderr); dumpBadObject((PyrObject*)obj); return false; } if (obj->next->prev != obj) { fprintf(stderr, "set %d black obj->next->prev != obj\n", i); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); } // scan for refs to white. if (!BlackToWhiteCheck((PyrObject*)obj)) return false; obj = obj->next; } // scan white list obj = set->mWhite.next; while (obj != set->mFree) { if (obj->gc_color != mWhiteColor) { // debugf("set %d white list obj color wrong %d (%d, %d, %d) %p\n", // i, obj->gc_color, mBlackColor, mGreyColor, mWhiteColor, obj); // debugf("hmmm free %p black %p\n", set->mFree, set->black); fprintf(stderr, "set %d white list obj color wrong %d (%d, %d, %d) %p\n", i, obj->gc_color, mBlackColor, mGreyColor, mWhiteColor, obj); fprintf(stderr, "hmmm free %p black %p\n", set->mFree, &set->mBlack); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); return false; } if (GetGCSet(obj) != set) { // debugf("set %d white obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); fprintf(stderr, "set %d white obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); return false; } if (obj->next->prev != obj) { fprintf(stderr, "set %d white obj->next->prev != obj\n", i); setPostFile(stderr); DumpBackTrace(mVMGlobals); dumpBadObject((PyrObject*)obj); } obj = obj->next; } // mark all free list items free obj = set->mFree; while (!IsMarker(obj)) { /*if (obj->gc_color == mGreyColor) { //debugf("grey obj on free list\n"); fprintf(stderr, "grey obj on free list\n"); return false; }*/ // post("FREE\n"); // dumpObject((PyrObject*)(PyrObject*)obj); obj->gc_color = mFreeColor; if (GetGCSet(obj) != set) { // debugf("set %d free obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); fprintf(stderr, "set %d free obj gcset wrong %d %p\n", i, obj->obj_sizeclass, obj); // dumpObject((PyrObject*)obj); return false; } if (obj->next->prev != obj) { fprintf(stderr, "set %d free obj->next->prev != obj\n", i); // dumpObject((PyrObject*)obj); } obj = obj->next; } } int numgrey = 0; PyrObjectHdr* grey = mGrey.next; while (!IsMarker(grey)) { numgrey++; if (!IsGrey(grey)) { fprintf(stderr, "sc Object on grey list not grey %d %d %d\n", grey->gc_color, mGreyColor, numgrey); fprintf(stderr, "%p <- %p -> %p grey %p process %p\n", mGrey.prev, &mGrey, mGrey.next, grey, mProcess); return false; } grey = grey->next; } if (numgrey != mNumGrey) { fprintf(stderr, "grey count off %d %d\n", numgrey, mNumGrey); DumpInfo(); fprintf(stderr, "."); return false; } return true; } bool PyrGC::LinkSanity() { // postfl("PyrGC::LinkSanity\n"); for (int i = 0; i < kNumGCSets; ++i) { GCSet* set = mSets + i; // scan entire loop PyrObjectHdr* obj = &set->mBlack; do { if (obj->next->prev != obj) { fprintf(stderr, "set %d black obj->next->prev != obj\n", i); // dumpObject((PyrObject*)obj); return false; } if (obj->prev->next != obj) { fprintf(stderr, "set %d black obj->prev->next != obj\n", i); // dumpObject((PyrObject*)obj); return false; } obj = obj->next; } while (obj != &set->mBlack); } return true; } #define DUMPINSANITY 1 bool PyrGC::BlackToWhiteCheck(PyrObject* objA) { if (objA->obj_format > obj_slot) return true; // scan it int size = objA->size; if (size > 0) { PyrSlot* slot = objA->slots; for (int j = size; j--; ++slot) { PyrObject* objB = nullptr; if (IsObj(slot) && slotRawObject(slot)) { objB = slotRawObject(slot); } if (objB && (uintptr_t)objB < 100) { fprintf(stderr, "weird obj ptr\n"); return false; } if (objB) { if (objA == mStack) continue; if (objA->gc_color == mBlackColor && objA != mPartialScanObj) { if (objB->gc_color == mWhiteColor) { if (objA->classptr == class_frame) { // jmc: black stack frames pointing to white nodes can be ignore PyrFrame* frameA = (PyrFrame*)objA; PyrMethod* meth = slotRawMethod(&frameA->method); PyrMethodRaw* methraw = METHRAW(meth); if (methraw->needsHeapContext) continue; } #if DUMPINSANITY fprintf(stderr, "black frame to white ref %p %p\n", objA, objB); dumpBadObject(objA); dumpBadObject(objB); fprintf(stderr, "\n"); #endif return false; } } } } } return true; } bool PyrGC::SanityMarkObj(PyrObject* objA, PyrObject* fromObj, int level) { if (objA->IsPermanent()) return true; if (objA->IsMarked()) return true; if (objA->size > MAXINDEXSIZE(objA)) { fprintf(stderr, "obj indexed size larger than max: %d > %ld\n", objA->size, MAXINDEXSIZE(objA)); // dumpObject((PyrObject*)objA); return false; } objA->SetMark(); // mark it if (!BlackToWhiteCheck(objA)) return false; if (objA->obj_format <= obj_slot) { // scan it int size = objA->size; if (size > 0) { PyrSlot* slot = objA->slots; for (int j = size; j--; ++slot) { PyrObject* objB = nullptr; int tag = GetTag(slot); if (tag == tagObj && slotRawObject(slot)) objB = slotRawObject(slot); if (objB) { /* if (level > 40) { fprintf(stderr, "40 levels deep!\n"); dumpBadObject(objA); dumpBadObject(objB); return false; } */ bool err = SanityMarkObj(objB, objA, level + 1); if (!err) return false; } } } } return true; } bool PyrGC::SanityClearObj(PyrObject* objA, int level) { if (!(objA->IsMarked())) return true; if (objA->IsPermanent()) return true; objA->ClearMark(); // unmark it if (objA->obj_format <= obj_slot) { // scan it int size = objA->size; if (size > 0) { PyrSlot* slot = objA->slots; for (int j = size; j--; ++slot) { PyrObject* objB = nullptr; if (IsObj(slot) && slotRawObject(slot)) { objB = slotRawObject(slot); } if (objB) { /*if (level > 40) { fprintf(stderr, "40 levels deep!\n"); dumpBadObject(objA); //dumpObject((PyrObject*)objB); //newPyrFrame return errFailed; }*/ bool err = SanityClearObj(objB, level + 1); if (!err) return false; } } } } return true; } void PyrGC::DumpInfo() { int i; PyrObjectHdr* obj; int numblack, numwhite, numfree, settotal, setsiztotal; int totblack, totgrey, totwhite, totfree, totref, total, siztotal; REPORTPAUSE post("flips %d collects %d nalloc %d alloc %d grey %d\n", mFlips, mCollects, mNumAllocs, mAllocTotal, mNumGrey); totblack = 0; totgrey = 0; totwhite = 0; totfree = 0; totref = 0; total = 0; siztotal = 0; for (i = 0; i < kNumGCSizeClasses; ++i) { GCSet* set = mSets + i; // scan black list numblack = 0; obj = set->mBlack.next; while (!IsMarker(obj)) { numblack++; obj = obj->next; } // scan white list numwhite = 0; obj = set->mWhite.next; while (obj != set->mFree) { numwhite++; obj = obj->next; } // scan free list numfree = 0; obj = set->mFree; while (!IsMarker(obj)) { numfree++; obj = obj->next; } settotal = numblack + numwhite + numfree; setsiztotal = settotal << (i + 3); siztotal += setsiztotal; totblack += numblack; totwhite += numwhite; totfree += numfree; total += settotal; if (settotal) { post("%2d bwf t sz: %6d %6d %6d %6d %8d\n", i, numblack, numwhite, numfree, settotal, setsiztotal); } } post("tot bwf t sz: %6d %6d %6d %6d %8d\n", totblack, totwhite, totfree, total, siztotal); } void PyrGC::DumpGrey() { // scan grey list PyrObjectHdr* obj = mGrey.next; while (!IsMarker(obj)) { post("grey %s %d %d\n", slotRawSymbol(&obj->classptr->name)->name, obj->obj_sizeclass, obj->size); obj = obj->next; } } void PyrGC::DumpSet(int i) { GCSet* set = mSets + i; // scan black list PyrObjectHdr* obj = set->mBlack.next; while (!IsMarker(obj)) { post("black %s %d %d\n", slotRawSymbol(&obj->classptr->name)->name, obj->obj_sizeclass, obj->size); obj = obj->next; } // scan white list obj = set->mWhite.next; while (obj != set->mFree) { post("white %s %d %d\n", slotRawSymbol(&obj->classptr->name)->name, obj->obj_sizeclass, obj->size); obj = obj->next; } // scan free list obj = set->mFree; while (!IsMarker(obj)) { post("free %s %d %d\n", slotRawSymbol(&obj->classptr->name)->name, obj->obj_sizeclass, obj->size); obj = obj->next; } } void PyrGC::ClearMarks() { for (int i = 0; i < kNumGCSets; ++i) { GCSet* set = mSets + i; // scan black list PyrObjectHdr* obj = set->mBlack.next; while (!IsMarker(obj)) { obj->ClearMark(); // unmark it obj = obj->next; } // scan grey list obj = mGrey.next; while (!IsMarker(obj)) { obj->ClearMark(); // unmark it obj = obj->next; } // scan white list obj = set->mWhite.next; while (obj != set->mFree) { obj->ClearMark(); // unmark it obj = obj->next; } // scan free list obj = set->mFree; while (!IsMarker(obj)) { obj->ClearMark(); // unmark it obj = obj->next; } } } void PyrGC::throwMemfailed(size_t inNumBytes) { post("alloc failed. size = %d\n", inNumBytes); MEMFAILED; }
36,952
C++
.cpp
1,073
25.883504
120
0.562108
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
29,848
SC_TerminalClient.cpp
supercollider_supercollider/lang/LangSource/SC_TerminalClient.cpp
/* Commandline interpreter interface. Copyright (c) 2003-2006 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 */ #include "SC_TerminalClient.h" #ifdef SC_QT # include "../../QtCollider/LanguageClient.h" #endif #include <boost/bind/bind.hpp> #ifdef _WIN32 # define __GNU_LIBRARY__ # include "getopt.h" # include "SC_Win32Utils.h" # include <io.h> # include <windows.h> # include <ioapiset.h> # include <iostream> // for cerr #endif #ifdef __APPLE__ # include "../../common/SC_Apple.hpp" #endif #ifdef HAVE_READLINE # include <readline/readline.h> # include <readline/history.h> # include <signal.h> #endif #include "GC.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrLexer.h" #include "PyrSlot.h" #include "VMGlobals.h" #include "SC_Filesystem.hpp" #include "SC_LanguageConfig.hpp" #include "SC_Version.hpp" #include <filesystem> using namespace boost::placeholders; static FILE* gPostDest = stdout; #ifdef _WIN32 static UINT gOldCodePage; // for remembering the old codepage when we switch to UTF-8 #endif SC_TerminalClient::SC_TerminalClient(const char* name): SC_LanguageClient(name), mReturnCode(0), mUseReadline(false), mWork(mIoService), mTimer(mIoService), #ifndef _WIN32 mStdIn(mInputService, STDIN_FILENO) #else mStdIn(mInputService, GetStdHandle(STD_INPUT_HANDLE)) #endif { } SC_TerminalClient::~SC_TerminalClient() {} void SC_TerminalClient::postText(const char* str, size_t len) { fwrite(str, sizeof(char), len, gPostDest); } void SC_TerminalClient::postFlush(const char* str, size_t len) { fwrite(str, sizeof(char), len, gPostDest); fflush(gPostDest); } void SC_TerminalClient::postError(const char* str, size_t len) { fprintf(gPostDest, "ERROR: "); fwrite(str, sizeof(char), len, gPostDest); } void SC_TerminalClient::flush() { fflush(gPostDest); } void SC_TerminalClient::printUsage() { Options opt; const size_t bufSize = 128; char memGrowBuf[bufSize]; char memSpaceBuf[bufSize]; snprintMemArg(memGrowBuf, bufSize, opt.mMemGrow); snprintMemArg(memSpaceBuf, bufSize, opt.mMemSpace); fprintf(stdout, "Usage:\n %s [options] [file..] [-]\n\n", getName()); fprintf( stdout, "Options:\n" " -v Print supercollider version and exit\n" " -d <path> Set runtime directory\n" " -D Enter daemon mode (no input)\n" " -g <memory-growth>[km] Set heap growth (default %s)\n" " -h Display this message and exit\n" " -l <path> Set library configuration file\n" " -m <memory-space>[km] Set initial heap size (default %s)\n" " -r Call Main.run on startup\n" " -s Call Main.stop on shutdown\n" " -u <network-port-number> Set UDP listening port (default %d)\n" " -i <ide-name> Specify IDE name (for enabling IDE-specific class code, default \"%s\")\n" " -a Standalone mode (exclude SCClassLibrary and user and system Extensions " "folders from search path)\n", memGrowBuf, memSpaceBuf, opt.mPort, SC_Filesystem::instance().getIdeName().c_str()); } bool SC_TerminalClient::parseOptions(int& argc, char**& argv, Options& opt) { const char* optstr = ":d:Dg:hl:m:rsu:i:av"; int c; // inhibit error reporting opterr = 0; while ((c = getopt(argc, argv, optstr)) != -1) { switch (c) { case 'd': opt.mRuntimeDir = optarg; break; case 'D': opt.mDaemon = true; break; case 'g': if (!parseMemArg(optarg, &opt.mMemGrow)) { optopt = c; goto optArgInvalid; } break; case 'h': goto help; case 'l': opt.mLibraryConfigFile = optarg; break; case 'm': if (!parseMemArg(optarg, &opt.mMemSpace)) { optopt = c; goto optArgInvalid; } break; case 'r': opt.mCallRun = true; break; case 'v': fprintf(stdout, "sclang %s (%s)\n", SC_VersionString().c_str(), SC_BuildString().c_str()); quit(0); return false; break; case 's': opt.mCallStop = true; break; case 'u': if (!parsePortArg(optarg, &opt.mPort)) { optopt = c; goto optArgInvalid; } break; case '?': goto optInvalid; break; case ':': goto optArgExpected; break; case 'i': SC_Filesystem::instance().setIdeName(optarg); break; case 'a': opt.mStandalone = true; break; default: ::post("%s: unknown error (getopt)\n", getName()); quit(255); return false; } } argv += optind; argc -= optind; return true; help: printUsage(); quit(0); return false; optInvalid: ::post("%s: invalid option -%c\n", getName(), optopt); quit(1); return false; optArgExpected: ::post("%s: missing argument for option -%c\n", getName(), optopt); quit(1); return false; optArgInvalid: ::post("%s: invalid argument for option -%c -- %s\n", getName(), optopt, optarg); quit(1); return false; } int SC_TerminalClient::run(int argc, char** argv) { Options& opt = mOptions; if (!parseOptions(argc, argv, opt)) { return mReturnCode; } // finish argv processing const char* codeFile = nullptr; if (argc > 0) { codeFile = argv[0]; opt.mDaemon = true; argv++; argc--; } opt.mArgc = argc; opt.mArgv = argv; // read library configuration file if (opt.mLibraryConfigFile) SC_LanguageConfig::setConfigPath(opt.mLibraryConfigFile); SC_LanguageConfig::readLibraryConfig(opt.mStandalone); // initialize runtime initRuntime(opt); // Create config directory so that it can be used by Quarks, etc. See #2919. if (!opt.mStandalone && !opt.mLibraryConfigFile) std::filesystem::create_directories(SC_Filesystem::instance().getDirectory(SC_Filesystem::DirName::UserConfig)); // startup library compileLibrary(opt.mStandalone); // enter main loop if (codeFile) executeFile(codeFile); if (opt.mCallRun) runMain(); if (opt.mDaemon) { daemonLoop(); } else { initInput(); startInput(); commandLoop(); endInput(); cleanupInput(); } if (opt.mCallStop) stopMain(); // shutdown library shutdownLibrary(); flush(); shutdownRuntime(); return mReturnCode; } void SC_TerminalClient::recompileLibrary() { SC_LanguageClient::recompileLibrary(mOptions.mStandalone); } void SC_TerminalClient::quit(int code) { mReturnCode = code; } static PyrSymbol* resolveMethodSymbol(bool silent) { if (silent) return s_interpretCmdLine; else return s_interpretPrintCmdLine; } void SC_TerminalClient::interpretCmdLine(const char* cmdLine, bool silent) { setCmdLine(cmdLine); runLibrary(resolveMethodSymbol(silent)); flush(); } void SC_TerminalClient::interpretCmdLine(const char* cmdLine, size_t size, bool silent) { setCmdLine(cmdLine, size); runLibrary(resolveMethodSymbol(silent)); flush(); } // Note: called only if the input thread does not perform an asynchronous read operation void SC_TerminalClient::interpretInput() { char* data = mInputBuf.getData(); int c = mInputBuf.getSize(); int i = 0; while (i < c) { switch (data[i]) { case kInterpretCmdLine: interpretCmdLine(data, i, true); break; case kInterpretPrintCmdLine: interpretCmdLine(data, i, false); break; case kRecompileLibrary: recompileLibrary(); break; default: ++i; continue; } data += i + 1; c -= i + 1; i = 0; } mInputBuf.reset(); if (mUseReadline) mReadlineSem.post(); else startInputRead(); } void SC_TerminalClient::onLibraryStartup() { SC_LanguageClient::onLibraryStartup(); int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_Argv", &SC_TerminalClient::prArgv, 1, 0); definePrimitive(base, index++, "_Exit", &SC_TerminalClient::prExit, 1, 0); definePrimitive(base, index++, "_AppClock_SchedNotify", &SC_TerminalClient::prScheduleChanged, 1, 0); definePrimitive(base, index++, "_Recompile", &SC_TerminalClient::prRecompile, 1, 0); } void SC_TerminalClient::sendSignal(Signal sig) { switch (sig) { case sig_input: mIoService.post(boost::bind(&SC_TerminalClient::interpretInput, this)); break; case sig_recompile: mIoService.post(boost::bind(&SC_TerminalClient::recompileLibrary, this)); break; case sig_sched: mIoService.post(boost::bind(&SC_TerminalClient::tick, this, boost::system::error_code())); break; case sig_stop: mIoService.post(boost::bind(&SC_TerminalClient::stopMain, this)); break; } } void SC_TerminalClient::onQuit(int exitCode) { postfl("main: quit request %i\n", exitCode); quit(exitCode); stop(); } extern void ElapsedTimeToChrono(double elapsed, std::chrono::system_clock::time_point& out_time_point); /** * \brief Repeatedly calls the main AppClock loop. * * This method does the following: * * - Wraps \c tickLocked (locking \c gLangMutex before and after), which in * turn calls \c runLibrary. * - Schedules to call itself again using a \c boost::asio::basic_waitable_timer * (\c mTimer). * * Since it calls itself, a single call to \c tick will cause the method to * keep calling itself autonomously. * * If \c tick is called again externally while a timer is running, any * previously scheduled \c tick call is canceled. This forces a premature \c * tick, which will schedule itself again, and so on. * * The timed calls to \c tick are used for events scheduled on the AppClock. * The interruption feature is used when sclang receives unanticipated events * such as inbound OSC messages. */ void SC_TerminalClient::tick(const boost::system::error_code& error) { /* Even if the timeout is canceled, this callback will always fire (see docs for boost::asio::basic_waitable_timer). Distinguishing between a canceled and successful callback is done by inspecting the error. If it turns out this method was called because of a cancelled timer, we need to bail out and let the tick call that interrupted us take over. If we aren't the result of a canceled timer call, we're either the result of a scheduled timer expiry, or we *are* the interruption and we need to cancel any scheduled tick calls. Calling mTimer.cancel() if the error is a success error code handles both cases. Previously, instead of this if/else block, this was just a call to mTimer.cancel(). This was causing this method to rapidly call itself excessively, hogging the CPU. See discussion at #2144. */ if (error == boost::system::errc::success) { mTimer.cancel(); } else { return; } double secs; lock(); bool haveNext = tickLocked(&secs); unlock(); flush(); std::chrono::system_clock::time_point nextAbsTime; ElapsedTimeToChrono(secs, nextAbsTime); if (haveNext) { mTimer.expires_at(nextAbsTime); mTimer.async_wait(boost::bind(&SC_TerminalClient::tick, this, _1)); } } void SC_TerminalClient::commandLoop() { mIoService.run(); } void SC_TerminalClient::daemonLoop() { commandLoop(); } #ifdef HAVE_READLINE static void sc_rl_cleanlf(void) { rl_reset_line_state(); rl_crlf(); rl_redisplay(); } static void sc_rl_signalhandler(int sig) { // ensure ctrl-C clears line rather than quitting (ctrl-D will quit nicely) rl_replace_line("", 0); sc_rl_cleanlf(); # ifdef _WIN32 // need to re-instate the handler on windows signal(SIGINT, &sc_rl_signalhandler); # endif } static int sc_rl_mainstop(int i1, int i2) { static_cast<SC_TerminalClient*>(SC_LanguageClient::instance())->sendSignal(SC_TerminalClient::sig_stop); sc_rl_cleanlf(); // We also push a newline so that there's some UI feedback return 0; } /* // Completion from sclang dictionary TODO char ** sc_rl_completion (const char *text, int start, int end); char ** sc_rl_completion (const char *text, int start, int end){ char **matches = (char **)NULL; printf("sc_rl_completion(%s, %i, %i)\n", text, start, end); return matches; } */ int SC_TerminalClient::readlineRecompile(int i1, int i2) { static_cast<SC_TerminalClient*>(SC_LanguageClient::instance())->sendSignal(sig_recompile); sc_rl_cleanlf(); return 0; } void SC_TerminalClient::readlineCmdLine(char* cmdLine) { SC_TerminalClient* client = static_cast<SC_TerminalClient*>(instance()); if (cmdLine == nullptr) { postfl("\nExiting sclang (ctrl-D)\n"); client->onQuit(0); return; } if (*cmdLine != 0) { // If line wasn't empty, store it so that uparrow retrieves it add_history(cmdLine); int len = strlen(cmdLine); client->mInputBuf.append(cmdLine, len); client->mInputBuf.append(kInterpretPrintCmdLine); client->sendSignal(sig_input); client->mReadlineSem.wait(); } } void SC_TerminalClient::readlineInit() { // Setup readline rl_readline_name = "sclang"; rl_basic_word_break_characters = " \t\n\"\\'`@><=;|&{}()."; // rl_attempted_completion_function = sc_rl_completion; rl_bind_key(CTRL('t'), &sc_rl_mainstop); rl_bind_key(CTRL('x'), &readlineRecompile); rl_callback_handler_install("sc3> ", &readlineCmdLine); // Set our handler for SIGINT that will clear the line instead of terminating. // NOTE: We prevent readline from setting its own signal handlers, // to not override ours. rl_catch_signals = 0; # ifndef _WIN32 struct sigaction sact; memset(&sact, 0, sizeof(struct sigaction)); sact.sa_handler = &sc_rl_signalhandler; sigaction(SIGINT, &sact, nullptr); # else signal(SIGINT, &sc_rl_signalhandler); # endif } #endif // HAVE_READLINE void SC_TerminalClient::startInputRead() { #ifndef _WIN32 if (mUseReadline) mStdIn.async_read_some(boost::asio::null_buffers(), boost::bind(&SC_TerminalClient::onInputRead, this, _1, _2)); else mStdIn.async_read_some(boost::asio::buffer(inputBuffer), boost::bind(&SC_TerminalClient::onInputRead, this, _1, _2)); #else mStdIn.async_wait([&](const boost::system::error_code& error) { if (error) onInputRead(error, 0); else { if (!mUseReadline || WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)) { DWORD bytes_transferred; ::ReadFile(GetStdHandle(STD_INPUT_HANDLE), inputBuffer.data(), inputBuffer.size(), &bytes_transferred, nullptr); onInputRead(error, bytes_transferred); } else { onInputRead(error, 0); } } }); #endif } void SC_TerminalClient::onInputRead(const boost::system::error_code& error, std::size_t bytes_transferred) { if (error == boost::asio::error::operation_aborted) { postfl("SCLang Input: Quit requested\n"); return; } if (error == boost::asio::error::eof) { postfl("SCLang Input: EOF. Will quit.\n"); onQuit(0); return; } if (error) { postfl("SCLang Input: %s.\n", error.message().c_str()); onQuit(1); return; } if (!error) { #if HAVE_READLINE if (mUseReadline) { rl_callback_read_char(); startInputRead(); return; } #endif pushCmdLine(inputBuffer.data(), bytes_transferred); } } void SC_TerminalClient::inputThreadFn() { #if HAVE_READLINE if (mUseReadline) readlineInit(); #endif #ifdef _WIN32 if (!mUseReadline) { // make sure there's nothing on stdin before we launch the service // this fixes #4214 DWORD bytesRead = 0; auto success = ReadFile(GetStdHandle(STD_INPUT_HANDLE), inputBuffer.data(), inputBuffer.size(), &bytesRead, NULL); if (success) { pushCmdLine(inputBuffer.data(), bytesRead); } } #endif startInputRead(); boost::asio::io_service::work work(mInputService); mInputService.run(); } void SC_TerminalClient::pushCmdLine(const char* newData, size_t size) { bool signal = false; while (size--) { char c = *newData++; switch (c) { case kRecompileLibrary: case kInterpretCmdLine: case kInterpretPrintCmdLine: mInputBuf.append(mInputThrdBuf.getData(), mInputThrdBuf.getSize()); mInputBuf.append(c); signal = true; mInputThrdBuf.reset(); break; default: mInputThrdBuf.append(c); } } if (signal) sendSignal(sig_input); else startInputRead(); } void SC_TerminalClient::initInput() { #ifdef HAVE_READLINE if (!SC_Filesystem::instance().usingIde()) { // Other clients (emacs, vim, ...) won't want to interact through rl mUseReadline = true; return; } #endif } void SC_TerminalClient::startInput() { SC_Thread thread(std::bind(&SC_TerminalClient::inputThreadFn, this)); mInputThread = std::move(thread); } void SC_TerminalClient::endInput() { mInputService.stop(); mStdIn.cancel(); #ifdef _WIN32 // Note this breaks Windows XP compatibility, since this function is only defined in Vista and later ::CancelIoEx(GetStdHandle(STD_INPUT_HANDLE), nullptr); #endif postfl("main: waiting for input thread to join...\n"); mInputThread.join(); postfl("main: quitting...\n"); } void SC_TerminalClient::cleanupInput() { #ifdef HAVE_READLINE if (mUseReadline) rl_callback_handler_remove(); #endif } int SC_TerminalClient::prArgv(struct VMGlobals* g, int) { int argc = ((SC_TerminalClient*)SC_TerminalClient::instance())->options().mArgc; char** argv = ((SC_TerminalClient*)SC_TerminalClient::instance())->options().mArgv; PyrSlot* argvSlot = g->sp; PyrObject* argvObj = newPyrArray(g->gc, argc * sizeof(PyrObject), 0, true); SetObject(argvSlot, argvObj); // this is okay here as we don't use the receiver for (int i = 0; i < argc; i++) { PyrString* str = newPyrString(g->gc, argv[i], 0, true); SetObject(argvObj->slots + i, str); argvObj->size++; g->gc->GCWriteNew(argvObj, (PyrObject*)str); // we know str is white so we can use GCWriteNew } return errNone; } int SC_TerminalClient::prExit(struct VMGlobals* g, int) { int code; int err = slotIntVal(g->sp, &code); if (err) return err; ((SC_TerminalClient*)SC_LanguageClient::instance())->onQuit(code); return errNone; } int SC_TerminalClient::prScheduleChanged(struct VMGlobals* g, int numArgsPushed) { static_cast<SC_TerminalClient*>(instance())->sendSignal(sig_sched); return errNone; } int SC_TerminalClient::prRecompile(struct VMGlobals*, int) { static_cast<SC_TerminalClient*>(instance())->sendSignal(sig_recompile); return errNone; } SCLANG_DLLEXPORT SC_LanguageClient* createLanguageClient(const char* name) { if (SC_LanguageClient::instance()) return nullptr; #ifdef __APPLE__ SC::Apple::disableAppNap(); #endif #ifdef _WIN32 // set codepage to UTF-8 gOldCodePage = GetConsoleOutputCP(); if (!SetConsoleOutputCP(65001)) std::cerr << "WARNING: could not set codepage to UTF-8" << std::endl; #endif #ifdef SC_QT return new QtCollider::LangClient(name); #else return new SC_TerminalClient(name); #endif } SCLANG_DLLEXPORT void destroyLanguageClient(class SC_LanguageClient* languageClient) { #ifdef _WIN32 // reset codepage from UTF-8 SetConsoleOutputCP(gOldCodePage); #endif delete languageClient; }
21,649
C++
.cpp
626
28.688498
120
0.639278
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
29,849
dumpByteCodes.cpp
supercollider_supercollider/lang/LangSource/dumpByteCodes.cpp
/* 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 "PyrKernel.h" #include "PyrParseNode.h" #include "PyrSymbol.h" #include "SCBase.h" void numBlockTemps(PyrBlock* block, long level, long* numArgNames, long* numVarNames); void numBlockTemps(PyrBlock* block, long level, long* numArgNames, long* numVarNames) { long i; for (i = 0; i < level; ++i) { block = slotRawBlock(&block->contextDef); } *numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; *numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; } unsigned char* dumpOneByteCode(PyrBlock* theBlock, PyrClass* theClass, unsigned char* ip); unsigned char* dumpOneByteCode(PyrBlock* theBlock, PyrClass* theClass, unsigned char* ip) { PyrClass* classobj; PyrBlock* block; PyrSlot* slot; PyrSymbol* selector; char str[256]; long op1, op2, op3, op4, op5; long i, n, ival, jmplen; long numArgNames, numVarNames, numTemps; unsigned char* ipbeg; if (theClass == nullptr) { block = theBlock; theClass = nullptr; while (block) { // dumpObject((PyrObject*)block); // post("block->classptr %d class_method %d %d\n", // block->classptr, class_method, isKindOf((PyrObject*)block, class_method)); // if (block->classptr == class_method) { if (isKindOf((PyrObject*)block, class_method)) { theClass = slotRawClass(&((PyrMethod*)block)->ownerclass); break; } block = slotRawBlock(&block->contextDef); } if (theClass == nullptr) { theClass = s_interpreter->u.classobj; // error("dumpByteCodes: no Class found.\n"); // return NULL; } } ipbeg = slotRawInt8Array(&theBlock->code)->b; n = ip - ipbeg; op1 = *ip++; post("%3d %02X", n, op1); switch (op1) { case 0: // push class op2 = *ip++; // get literal index post(" %02X PushClassX '%s'\n", op2, slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2])->name); break; case 1: // Extended, PushInstVar op2 = *ip++; // get inst var index post(" %02X PushInstVarX '%s'\n", op2, slotRawSymbolArray(&theClass->instVarNames)->symbols[op2]->name); break; case 2: // Extended, PushTempVar op2 = *ip++; // get temp var level block = theBlock; for (i = op2; i--; block = slotRawBlock(&block->contextDef)) { /* noop */ } numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; op3 = *ip++; // get temp var index if (op3 < numArgNames) { post(" %02X %02X PushTempVarX '%s'\n", op2, op3, slotRawSymbolArray(&block->argNames)->symbols[op3]->name); } else { post(" %02X %02X PushTempVarX '%s'\n", op2, op3, slotRawSymbolArray(&block->varNames)->symbols[op3 - numArgNames]->name); } break; case 3: // Extended, PushTempZeroVar block = theBlock; numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; op2 = *ip++; // get temp var index if (op2 < numArgNames) { post(" %02X PushTempZeroVarX '%s'\n", op2, slotRawSymbolArray(&theBlock->argNames)->symbols[op2]->name); } else { post(" %02X PushTempZeroVarX '%s'\n", op2, slotRawSymbolArray(&theBlock->varNames)->symbols[op2 - numArgNames]->name); } break; case 4: // Extended, PushLiteral op2 = *ip++; // get literal index // push a block if it is one slot = slotRawObject(&theBlock->selectors)->slots + op2; slotString(slot, str); post(" %02X PushLiteralX %s\n", op2, str); break; case 5: // Extended, PushClassVar op2 = *ip++; // get class var literal index op3 = *ip++; // get class var index post(" %02X %02X PushClassVarX\n", op2, op3); break; case 6: // Extended, PushSpecialValue == push a special class op2 = *ip++; // get class name index classobj = gSpecialClasses[op2]->u.classobj; post(" %02X PushSpecialClass '%s'\n", op2, slotRawSymbol(&classobj->name)->name); break; case 7: // Extended, StoreInstVar op2 = *ip++; // get inst var index post(" %02X StoreInstVarX '%s'\n", op2, slotRawSymbolArray(&theClass->instVarNames)->symbols[op2]->name); break; case 8: // Extended, StoreTempVar op2 = *ip++; // get temp var level block = theBlock; for (i = op2; i--; block = slotRawBlock(&block->contextDef)) { /* noop */ } numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; op3 = *ip++; // get temp var index if (op3 < numArgNames) { post(" %02X %02X StoreTempVarX '%s'\n", op2, op3, slotRawSymbolArray(&block->argNames)->symbols[op3]->name); } else { post(" %02X %02X StoreTempVarX '%s'\n", op2, op3, slotRawSymbolArray(&block->varNames)->symbols[op3 - numArgNames]->name); } break; case 9: // Extended, StoreClassVar op2 = *ip++; // get class var literal index op3 = *ip++; // get class var index post(" %02X %02X StoreClassVarX\n", op2, op3); break; case 10: // Extended, SendMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op4]); post(" %02X %02X %02X SendMsgX '%s'\n", op2, op3, op4, selector->name); break; case 11: // Extended, SuperMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op4]); post(" %02X %02X %02X SuperMsgX '%s'\n", op2, op3, op4, selector->name); break; case 12: // Extended, SendSpecialMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index post(" %02X %02X %02X SendSpecialMsgX '%s'\n", op2, op3, op4, gSpecialSelectors[op4]->name); break; case 13: // Extended, SendSpecialUnaryArithMsg op2 = *ip++; // get selector index post(" %02X SendSpecialUnaryArithMsgX '%s'\n", op2, gSpecialUnarySelectors[op2]->name); break; case 14: // Extended, SendSpecialBinaryArithMsg op2 = *ip++; // get selector index post(" %02X SendSpecialBinaryArithMsgX '%s'\n", op2, gSpecialBinarySelectors[op2]->name); break; case 15: // Extended, SpecialOpcode (none yet) op2 = *ip++; // get extended special opcode switch (op2) { case opgProcess: // push thisProcess post(" %02X opgProcess\n", op2); break; case opgThread: // push thisThread post(" %02X opgThread\n", op2); break; case opgMethod: // push thisMethod post(" %02X opgMethod\n", op2); break; case opgFunctionDef: // push thisBlock post(" %02X opgFunctionDef\n", op2); break; case opgFunction: // push thisClosure post(" %02X opgFunction\n", op2); break; } break; // PushInstVar, 0..15 case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: post(" PushInstVar '%s'\n", slotRawSymbolArray(&theClass->instVarNames)->symbols[op1 & 15]->name); break; case 32: op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpIfTrue %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 33: case 34: case 35: case 36: case 37: case 38: case 39: op2 = op1 & 15; // get temp var level block = theBlock; for (i = op2; i--; block = slotRawBlock(&block->contextDef)) { /* noop */ } numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; op3 = *ip++; // get temp var index if (op3 >= 0 && op3 < numArgNames) { post(" %02X PushTempVar '%s'\n", op3, slotRawSymbolArray(&block->argNames)->symbols[op3]->name); } else if (op3 >= 0) { post(" %02X PushTempVar '%s'\n", op3, slotRawSymbolArray(&block->varNames)->symbols[op3 - numArgNames]->name); } break; case 40: op5 = *ip++; ival = op5; slot = slotRawObject(&theBlock->constants)->slots + ival; slotString(slot, str); post(" %02X PushConstant %s\n", op5, str); break; case 41: op4 = *ip++; op5 = *ip++; ival = (op4 << 8) | op5; slot = slotRawObject(&theBlock->constants)->slots + ival; slotString(slot, str); post(" %02X %02X PushConstant %s\n", op4, op5, str); break; case 42: op3 = *ip++; op4 = *ip++; op5 = *ip++; ival = (op3 << 16) | (op4 << 8) | op5; slot = slotRawObject(&theBlock->constants)->slots + ival; slotString(slot, str); post(" %02X %02X %02X PushConstant %s\n", op3, op4, op5, str); break; case 43: op2 = *ip++; op3 = *ip++; op4 = *ip++; op5 = *ip++; ival = (op2 << 24) | (op3 << 16) | (op4 << 8) | op5; slot = slotRawObject(&theBlock->constants)->slots + ival; slotString(slot, str); post(" %02X %02X %02X %02X PushConstant %s\n", op2, op3, op4, op5, str); break; case 44: op5 = *ip++; ival = (int32)(op5 << 24) >> 24; post(" %02X PushInt %d\n", op5, ival); break; case 45: op4 = *ip++; op5 = *ip++; ival = (int32)((op4 << 24) | (op5 << 16)) >> 16; post(" %02X %02X PushInt %d\n", op4, op5, ival); break; case 46: op3 = *ip++; op4 = *ip++; op5 = *ip++; ival = (int32)((op3 << 24) | (op4 << 16) | (op5 << 8)) >> 8; post(" %02X %02X %02X PushInt %d\n", op3, op4, op5, ival); break; case 47: op2 = *ip++; op3 = *ip++; op4 = *ip++; op5 = *ip++; ival = (int32)((op2 << 24) | (op3 << 16) | (op4 << 8) | op5); post(" %02X %02X %02X %02X PushInt %d\n", op2, op3, op4, op5, ival); break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: op2 = op1 & 15; // get temp var index block = theBlock; numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; if (op2 < numArgNames) { post(" PushTempZeroVar '%s'\n", slotRawSymbolArray(&theBlock->argNames)->symbols[op2]->name); } else { post(" PushTempZeroVar '%s'\n", slotRawSymbolArray(&theBlock->varNames)->symbols[op2 - numArgNames]->name); } break; case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: op2 = op1 & 15; // get temp var level slot = slotRawObject(&theBlock->constants)->slots + op2; slotString(slot, str); post(" PushLiteral %s\n", str); break; // PushClassVar case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: op3 = *ip++; // get class var index post(" %02X PushClassVar\n", op3); break; // PushSpecialValue case 96: post(" PushSpecialValue this\n"); break; case 97: post(" PushOneAndSubtract\n"); break; case 98: post(" PushSpecialValue -1\n"); break; case 99: post(" PushSpecialValue 0\n"); break; case 100: post(" PushSpecialValue 1\n"); break; case 101: post(" PushSpecialValue 2\n"); break; case 102: post(" PushSpecialValue 0.5\n"); break; case 103: post(" PushSpecialValue -1.0\n"); break; case 104: post(" PushSpecialValue 0.0\n"); break; case 105: post(" PushSpecialValue 1.0\n"); break; case 106: post(" PushSpecialValue 2.0\n"); break; case 107: post(" PushOneAndAdd\n"); break; case 108: post(" PushSpecialValue true\n"); break; case 109: post(" PushSpecialValue false\n"); break; case 110: post(" PushSpecialValue nil\n"); break; case 111: post(" PushSpecialValue 'end'\n"); break; // StoreInstVar, 0..15 case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: post(" StoreInstVar '%s'\n", slotRawSymbolArray(&theClass->instVarNames)->symbols[op1 & 15]->name); break; // StoreTempVar case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: op2 = op1 & 15; // get temp var level block = theBlock; for (i = op2; i--; block = slotRawBlock(&block->contextDef)) { /* noop */ } numArgNames = slotRawSymbolArray(&block->argNames) ? slotRawSymbolArray(&block->argNames)->size : 0; numVarNames = slotRawSymbolArray(&block->varNames) ? slotRawSymbolArray(&block->varNames)->size : 0; numTemps = numArgNames + numVarNames; op3 = *ip++; // get temp var index if (op3 < numArgNames) { post(" %02X StoreTempVar '%s'\n", op3, slotRawSymbolArray(&block->argNames)->symbols[op3]->name); } else { post(" %02X StoreTempVar '%s'\n", op3, slotRawSymbolArray(&block->varNames)->symbols[op3 - numArgNames]->name); } break; case 136: op2 = *ip++; // get inst var index op3 = *ip++; // get selector index selector = gSpecialSelectors[op3]; post(" %02X %02X PushInstVarAndSendSpecialMsg '%s' '%s'\n", op2, op3, slotRawSymbolArray(&theClass->instVarNames)->symbols[op2]->name, selector->name); break; case 137: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); post(" %02X PushAllArgs+SendMsg '%s'\n", op2, selector->name); break; case 138: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); post(" %02X PushAllButFirstArg+SendMsg '%s'\n", op2, selector->name); break; case 139: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; post(" %02X PushAllArgs+SendSpecialMsg '%s'\n", op2, selector->name); break; case 140: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; post(" %02X PushAllButFirstArg+SendSpecialMsg '%s'\n", op2, selector->name); break; case 141: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); post(" %02X PushAllButFirstTwoArgs+SendMsg '%s'\n", op2, selector->name); break; case 142: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; post(" %02X PushAllButFirstTwoArgs+SendSpecialMsg '%s'\n", op2, selector->name); break; case 143: op2 = *ip++; // get loop opcode if (op2 < 23 || op2 > 27) { post(" %02X ControlOpcode\n", op2); break; } else { op3 = *ip++; // jump op4 = *ip++; // jump jmplen = ((op3 & 0xFF) << 8) | (op4 & 0xFF); post(" %02X %02X %02X ControlOpcode %d (%d)\n", op2, op3, op4, jmplen, n + jmplen + 3); break; } break; // StoreClassVar case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: op2 = op1 & 15; op3 = *ip++; // get class var index post(" %02X StoreClassVar\n", op3); break; // SendMsg case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); post(" %02X SendMsg '%s'\n", op2, selector->name); break; // TailCallReturnFromFunction case 176: post(" TailCallReturnFromFunction\n"); break; // SuperMsg case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); post(" %02X SuperMsg '%s'\n", op2, selector->name); break; // SendSpecialMsg case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; post(" %02X SendSpecialMsg '%s'\n", op2, selector->name); break; // SendSpecialUnaryArithMsg case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: op2 = op1 & 15; selector = gSpecialUnarySelectors[op2]; post(" SendSpecialUnaryArithMsg '%s'\n", selector->name); break; // SendSpecialBinaryArithMsg case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: op2 = op1 & 15; selector = gSpecialBinarySelectors[op2]; post(" SendSpecialBinaryArithMsg '%s'\n", selector->name); break; // SpecialOpcodes case 240: post(" Drop\n"); break; case 241: post(" Dup\n"); break; // Dup case 242: post(" BlockReturn\n"); break; // BlockReturn case 243: post(" Return\n"); break; // Return case 244: post(" ReturnSelf\n"); break; // ReturnSelf case 245: post(" ReturnTrue\n"); break; // ReturnTrue case 246: post(" ReturnFalse\n"); break; // ReturnFalse case 247: post(" ReturnNil\n"); break; // ReturnNil case 248: // JumpIfFalse op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpIfFalse %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 249: // JumpIfFalsePushNil op2 = *ip++; op3 = *ip++; jmplen = ((op2 & 0xFF) << 8) | (op3 & 0xFF); post(" %02X %02X JumpIfFalsePushNil %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 250: // JumpIfFalsePushFalse op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpIfFalsePushFalse %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 251: // JumpIfTruePushTrue op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpIfTruePushTrue %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 252: // JumpFwd op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpFwd %d (%d)\n", op2, op3, jmplen, n + jmplen + 3); break; case 253: // JumpBak op2 = *ip++; op3 = *ip++; jmplen = (op2 << 8) | op3; post(" %02X %02X JumpBak %d (%d)\n", op2, op3, jmplen, n - jmplen + 1); break; case 254: op2 = *ip++; post(" %02X SpecialBinaryOpWithAdverb\n", op2); break; case 255: post(" TailCallReturnFromMethod\n"); break; } return ip; } bool detectSendSelector(PyrBlock* theBlock, PyrClass* theClass, unsigned char** ipp, PyrSymbol* testSelector); bool detectSendSelector(PyrBlock* theBlock, PyrClass* theClass, unsigned char** ipp, PyrSymbol* testSelector) { PyrBlock* block; PyrSymbol* selector = nullptr; long op1, op2, op3, op4, op5, op6; unsigned char* ip = *ipp; if (theClass == nullptr) { block = theBlock; theClass = nullptr; while (block) { if (isKindOf((PyrObject*)block, class_method)) { theClass = slotRawClass(&((PyrMethod*)block)->ownerclass); break; } block = slotRawBlock(&block->contextDef); } if (theClass == nullptr) { theClass = s_interpreter->u.classobj; } } op1 = *ip++; switch (op1) { case 0: // push class op2 = *ip++; // get literal index break; case 1: // Extended, PushInstVar op2 = *ip++; // get inst var index break; case 2: // Extended, PushTempVar op2 = *ip++; // get temp var level op3 = *ip++; // get temp var index break; case 3: // Extended, PushTempZeroVar op2 = *ip++; // get temp var level break; case 4: // Extended, PushLiteral op2 = *ip++; // get literal index break; case 5: // Extended, PushClassVar op2 = *ip++; // get class var literal index op3 = *ip++; // get class var index break; case 6: // Extended, PushSpecialValue == push a special class op2 = *ip++; // get class name index break; case 7: // Extended, StoreInstVar op2 = *ip++; // get inst var index break; case 8: // Extended, StoreTempVar op2 = *ip++; // get temp var level op3 = *ip++; // get class var index break; case 9: // Extended, StoreClassVar op2 = *ip++; // get class var literal index op3 = *ip++; // get class var index break; case 10: // Extended, SendMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op4]); break; case 11: // Extended, SuperMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op4]); break; case 12: // Extended, SendSpecialMsg op2 = *ip++; // get num args op3 = *ip++; // get num key args op4 = *ip++; // get selector index selector = gSpecialSelectors[op4]; break; case 13: // Extended, SendSpecialUnaryArithMsg op2 = *ip++; // get selector index selector = gSpecialUnarySelectors[op2]; break; case 14: // Extended, SendSpecialBinaryArithMsg op2 = *ip++; // get selector index selector = gSpecialBinarySelectors[op2]; break; case 15: // Extended, SpecialOpcode (none yet) op2 = *ip++; // get extended special opcode break; // PushInstVar, 0..15 case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: break; case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: op2 = op1 & 15; // get temp var level op3 = *ip++; // get num key args break; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: break; case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: break; // PushClassVar case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: op2 = op1 & 15; op3 = *ip++; // get class var index break; // PushSpecialValue case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: break; // StoreInstVar, 0..15 case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: break; // StoreTempVar case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: op2 = op1 & 15; // get temp var level op3 = *ip++; // get class var index break; case 136: op2 = *ip++; // get inst var index op3 = *ip++; // get selector index selector = gSpecialSelectors[op3]; break; case 137: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); break; case 138: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); break; case 139: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; break; case 140: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; break; case 141: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); break; case 142: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; break; case 143: op2 = *ip++; // get selector index break; // StoreClassVar case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: op2 = op1 & 15; op3 = *ip++; // get class var index break; // SendMsg case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); break; // SuperMsg case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: op2 = *ip++; // get selector index selector = slotRawSymbol(&slotRawObject(&theBlock->selectors)->slots[op2]); break; // SendSpecialMsg case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: op2 = *ip++; // get selector index selector = gSpecialSelectors[op2]; break; // SendSpecialUnaryArithMsg case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: op2 = op1 & 15; selector = gSpecialUnarySelectors[op2]; break; // SendSpecialBinaryArithMsg case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: op2 = op1 & 15; selector = gSpecialBinarySelectors[op2]; break; // SpecialOpcodes case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: break; case 248: // JumpIfFalse case 249: // JumpIfFalsePushNil case 250: // JumpIfFalsePushFalse case 251: // JumpIfTruePushTrue case 252: // JumpFwd case 253: // JumpBak op2 = *ip++; op3 = *ip++; break; case 254: // PushPosInt case 255: // PushNegInt op2 = *ip++; if (op2 & 0x80) { op3 = *ip++; if (op3 & 0x80) { op4 = *ip++; if (op4 & 0x80) { op5 = *ip++; if (op5 & 0x80) { op6 = *ip++; } } } } break; } *ipp = ip; return testSelector == selector; } void dumpByteCodes(PyrBlock* theBlock); void dumpByteCodes(PyrBlock* theBlock) { PyrClass* theClass; PyrBlock* block; long size; unsigned char *ip, *ipbeg, *ipend; if (slotRawInt8Array(&theBlock->code) == nullptr) { post("Code empty.\n"); return; } block = theBlock; theClass = nullptr; while (block) { if (isKindOf((PyrObject*)block, class_method)) { theClass = slotRawClass(&((PyrMethod*)block)->ownerclass); break; } block = slotRawBlock(&block->contextDef); } if (theClass == nullptr) { theClass = s_interpreter->u.classobj; } ip = ipbeg = slotRawInt8Array(&theBlock->code)->b; size = slotRawInt8Array(&theBlock->code)->size; ipend = ip + size; post("BYTECODES: (%d)\n", size); while (ip < ipend) { ip = dumpOneByteCode(theBlock, theClass, ip); } } bool detectSendSelectorIn(PyrBlock* theBlock, PyrSymbol* testSelector); bool detectSendSelectorIn(PyrBlock* theBlock, PyrSymbol* testSelector) { PyrClass* theClass; PyrBlock* block; PyrSymbol* selector; long size; unsigned char *ip, *ipbeg, *ipend; if (slotRawInt8Array(&theBlock->code) == nullptr) { PyrMethodRaw* methraw = METHRAW(theBlock); switch (methraw->methType) { case methRedirect: case methRedirectSuper: case methForwardInstVar: case methForwardClassVar: selector = slotRawSymbol(&theBlock->selectors); return selector == testSelector; default: return false; } } block = theBlock; theClass = nullptr; while (block) { if (isKindOf((PyrObject*)block, class_method)) { theClass = slotRawClass(&((PyrMethod*)block)->ownerclass); break; } block = slotRawBlock(&block->contextDef); } if (theClass == nullptr) { theClass = s_interpreter->u.classobj; } ip = ipbeg = slotRawInt8Array(&theBlock->code)->b; size = slotRawInt8Array(&theBlock->code)->size; ipend = ip + size; bool res = false; while (ip < ipend) { if ((res = detectSendSelector(theBlock, theClass, &ip, testSelector))) break; } return res; } const char* byteCodeString(int code); const char* byteCodeString(int code) { switch (code) { case 0: return "PushClassX"; case 1: return "PushInstVarX"; case 2: return "PushTempVarX"; case 3: return "PushTempZeroVarX"; case 4: return "PushLiteralX"; case 5: return "PushClassVarX"; case 6: return "PushSpecialClass"; case 7: return "StoreInstVarX"; case 8: return "StoreTempVarX"; case 9: return "StoreClassVarX"; case 10: return "SendMsgX"; case 11: return "SuperMsgX"; case 12: return "SendSpecialMsgX"; case 13: return "SendSpecialUnaryArithMsgX"; case 14: return "SendSpecialBinaryArithMsgX"; case 15: return "PushGlobal"; case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: return "PushInstVar"; case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: return "PushTempVar"; case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: return "PushTempZeroVar"; case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: return "PushLiteral"; case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: return "PushClassVar"; case 96: return "PushSpecialValue this"; case 97: return "PushOneAndSubtract"; case 98: return "PushSpecialValue -1"; case 99: return "PushSpecialValue 0"; case 100: return "PushSpecialValue 1"; case 101: return "PushSpecialValue 2"; case 102: return "PushSpecialValue 0.5"; case 103: return "PushSpecialValue -1.0"; case 104: return "PushSpecialValue 0.0"; case 105: return "PushSpecialValue 1.0"; case 106: return "PushSpecialValue 2.0"; case 107: return "PushOneAndAdd"; case 108: return "PushSpecialValue true"; case 109: return "PushSpecialValue false"; case 110: return "PushSpecialValue nil"; case 111: return "PushSpecialValue 'end'"; case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: return "StoreInstVar"; case 128: case 129: case 130: case 131: return "StoreTempVar"; case 132: return "PushInstVarAndSendNext"; case 133: return "PushInstVarAndSendPrNext"; case 134: return "PushInstVarAndSendDemandThisNode"; case 135: return "PushInstVarAndSendSpecialMsg"; case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143: return "UndefinedOpcode"; case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: return "StoreClassVar"; case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: return "SendMsg"; case 176: return "TailCallReturnFromFunction"; case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: return "SuperMsg"; case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: return "SendSpecialMsg"; case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: return "SendSpecialUnaryArithMsg"; case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: return "SendSpecialBinaryArithMsg"; // SpecialOpcodes case 240: return "Drop"; case 241: return "Dup"; // Dup case 242: return "BlockReturn"; // BlockReturn case 243: return "Return"; // Return case 244: return "ReturnSelf"; // ReturnSelf case 245: return "ReturnTrue"; // ReturnTrue case 246: return "ReturnFalse"; // ReturnFalse case 247: return "ReturnNil"; // ReturnNil case 248: return "JumpIfFalse"; // JumpIfFalse case 249: return "JumpIfFalsePushNil"; // JumpIfFalsePushNil case 250: return "JumpIfFalsePushFalse"; // JumpIfFalsePushFalse case 251: return "JumpIfTruePushTrue"; // JumpIfTruePushTrue case 252: return "JumpFwd"; // JumpFwd case 253: return "JumpBak"; // JumpBak case 254: return "PushPosInt"; // PushPosInt case 255: return "TailCallReturnFromMethod"; // TailCallReturnFromMethod } return "unknown opcode"; }
41,099
C++
.cpp
1,527
20.041257
120
0.558235
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
29,850
PyrLexer.cpp
supercollider_supercollider/lang/LangSource/PyrLexer.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com Copyright (c) 2017 Brian Heim (boost::filesystem additions) 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 <stdlib.h> #include <string.h> #include <float.h> #include <math.h> #include <new> #include <stdlib.h> #include <ctype.h> #include <cerrno> #include <limits> #include <set> #ifdef _WIN32 # include <direct.h> #else # include <sys/param.h> #endif #include <filesystem> #include <fstream> #include "PyrParseNode.h" #include "Bison/lang11d_tab.h" #include "SCBase.h" #include "PyrObject.h" #include "PyrObjectProto.h" #include "PyrLexer.h" #include "PyrSched.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "GC.h" #include "SimpleStack.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "InitAlloc.h" #include "PredefinedSymbols.h" #ifdef _WIN32 #else # include "dirent.h" #endif #include <string.h> #include "SC_LanguageConfig.hpp" #include "SC_Filesystem.hpp" // getDirectory, resolveIfAlias, isStandalone #include "SC_Codecvt.hpp" // path_to_utf8_str #include "SC_TextUtils.hpp" int yyparse(); int processaccidental1(char* s); int processaccidental2(char* s); extern bool gFullyFunctional; double compileStartTime; int gNumCompiledFiles; /* thisProcess.interpreter.executeFile("Macintosh HD:score").size.postln; */ namespace fs = std::filesystem; using DirName = SC_Filesystem::DirName; PyrSymbol* gCompilingFileSym = nullptr; VMGlobals* gCompilingVMGlobals = nullptr; static fs::path gCompileDir; //#define DEBUGLEX 1 bool gDebugLexer = false; bool gShowWarnings = false; LongStack brackets; LongStack closedFuncCharNo; LongStack generatorStack; int lastClosedFuncCharNo = 0; const char* binopchars = "!@%&*-+=|<>?/"; char yytext[MAXYYLEN]; fs::path currfilename; std::string printingCurrfilename; // for error reporting int yylen; int lexCmdLine = 0; bool compilingCmdLine = false; bool compilingCmdLineErrorWindow = false; intptr_t zzval; int lineno, charno, linepos; int* linestarts; int maxlinestarts; char* text; int textlen; int textpos; int errLineOffset, errCharPosOffset; int parseFailed = 0; bool compiledOK = false; std::set<fs::path> compiledDirectories; /* so the text editor's dumb paren matching will work */ #define OPENPAREN '(' #define OPENCURLY '{' #define OPENSQUAR '[' #define CLOSSQUAR ']' #define CLOSCURLY '}' #define CLOSPAREN ')' int sc_strtoi(const char* str, int n, int base) { int z = 0; for (int i = 0; i < n; ++i) { int c = *str++; if (!c) break; if (c >= '0' && c <= '0' + sc_min(10, base) - 1) z = z * base + c - '0'; else if (c >= 'a' && c <= 'a' + sc_min(36, base) - 11) z = z * base + c - 'a' + 10; else if (c >= 'A' && c <= 'A' + sc_min(36, base) - 11) z = z * base + c - 'A' + 10; } return z; } double sc_strtof(const char* str, int n, int base) { double z = 0.; int decptpos = 0; for (int i = 0; i < n; ++i) { int c = *str++; if (!c) break; if (c >= '0' && c <= '0' + sc_min(10, base) - 1) z = z * base + c - '0'; else if (c >= 'a' && c <= 'a' + sc_min(36, base) - 11) z = z * base + c - 'a' + 10; else if (c >= 'A' && c <= 'A' + sc_min(36, base) - 11) z = z * base + c - 'A' + 10; else if (c == '.') decptpos = i; } // calculation previously included decimal point in count of columns (was n-decptpos); there are 1 less than n // characters which are columns in the number contribution z = z / pow((double)base, n - 1 - decptpos); return z; } bool startLexer(PyrSymbol* fileSym, const fs::path& p, int startPos, int endPos, int lineOffset); bool startLexer(PyrSymbol* fileSym, const fs::path& p, int startPos, int endPos, int lineOffset) { const char* filename = fileSym->name; textlen = -1; if (!fileSym->u.source) { try { std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); file.open(p, std::ios_base::binary); size_t sz = fs::file_size(p); text = (char*)pyr_pool_compile->Alloc((sz + 1) * sizeof(char)); MEMFAIL(text); file.read(text, sz); text[sz] = '\0'; fileSym->u.source = text; rtf2txt(text); } catch (const std::exception& ex) { error("Could not read %s: %s.\n", SC_Codecvt::path_to_utf8_str(p).c_str(), ex.what()); return false; } } else text = fileSym->u.source; if ((startPos >= 0) && (endPos > 0)) { textlen = endPos - startPos; text += startPos; } else if (textlen == -1) textlen = strlen(text); if (lineOffset > 0) errLineOffset = lineOffset; else errLineOffset = 0; if (startPos > 0) errCharPosOffset = startPos; else errCharPosOffset = 0; initLongStack(&brackets); initLongStack(&closedFuncCharNo); initLongStack(&generatorStack); lastClosedFuncCharNo = 0; textpos = 0; linepos = 0; lineno = 1; charno = 0; yylen = 0; zzval = 0; parseFailed = 0; lexCmdLine = 0; currfilename = fs::path(filename); printingCurrfilename = "file '" + SC_Codecvt::path_to_utf8_str(currfilename) + "'"; maxlinestarts = 1000; linestarts = (int*)pyr_pool_compile->Alloc(maxlinestarts * sizeof(int*)); MEMFAIL(linestarts); linestarts[0] = 0; linestarts[1] = 0; return true; } void startLexerCmdLine(char* textbuf, int textbuflen) { // pyrmalloc: // lifetime: kill after compile. (this one gets killed anyway) text = (char*)pyr_pool_compile->Alloc((textbuflen + 2) * sizeof(char)); MEMFAIL(text); memcpy(text, textbuf, textbuflen); text[textbuflen] = ' '; text[textbuflen + 1] = 0; textlen = textbuflen + 1; rtf2txt(text); initLongStack(&brackets); initLongStack(&closedFuncCharNo); initLongStack(&generatorStack); lastClosedFuncCharNo = 0; textpos = 0; linepos = 0; lineno = 1; charno = 0; yylen = 0; zzval = 0; parseFailed = 0; lexCmdLine = 1; currfilename = fs::path("interpreted text"); printingCurrfilename = currfilename.string(); maxlinestarts = 1000; linestarts = (int*)pyr_pool_compile->Alloc(maxlinestarts * sizeof(int*)); MEMFAIL(linestarts); linestarts[0] = 0; linestarts[1] = 0; errLineOffset = 0; errCharPosOffset = 0; } void finiLexer() { pyr_pool_compile->Free(linestarts); freeLongStack(&brackets); freeLongStack(&closedFuncCharNo); freeLongStack(&generatorStack); } void initLexer() { // strcpy(binopchars, "!@%&*-+=|:<>?/"); } int input() { int c; if (textpos >= textlen) { c = 0; } else { c = text[textpos++]; charno++; } if (c == '\n' || c == '\r') { lineno++; linepos = textpos; if (linestarts) { if (lineno >= maxlinestarts) { maxlinestarts += maxlinestarts; linestarts = (int*)pyr_pool_compile->Realloc(linestarts, maxlinestarts * sizeof(int*)); } linestarts[lineno] = linepos; } charno = 0; } if (c != 0 && yylen < MAXYYLEN - 2) yytext[yylen++] = c; // if (gDebugLexer) postfl("input '%c' %d\n",c,c); return c; } int input0() { int c; if (textpos >= textlen) { c = 0; textpos++; // so unput will work properly } else { c = text[textpos++]; charno++; } if (c == '\n' || c == '\r') { lineno++; linepos = textpos; if (linestarts) { if (lineno >= maxlinestarts) { maxlinestarts += maxlinestarts; linestarts = (int*)pyr_pool_compile->Realloc(linestarts, maxlinestarts * sizeof(int*)); } linestarts[lineno] = linepos; } charno = 0; } // if (gDebugLexer) postfl("input0 '%c' %d\n",c,c); return c; } void unput(int c) { if (textpos > 0) textpos--; if (c) { if (yylen) --yylen; if (charno) --charno; if (c == '\n' || c == '\r') { --lineno; } } } void unput0(int c) { if (textpos > 0) textpos--; if (charno) --charno; if (c == '\n' || c == '\r') { --lineno; } } int yylex() { int r, c, c2; intptr_t d; int radix; yylen = 0; // finite state machine to parse input stream into tokens if (lexCmdLine == 1) { lexCmdLine = 2; r = INTERPRET; goto leave; } start: c = input(); if (c == 0) { r = 0; goto leave; } else if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f') { yylen = 0; goto start; } else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') goto ident; else if (c == '/') { c = input(); if (c == '/') goto comment1; else if (c == '*') goto comment2; else { unput(c); goto binop; } } else if (c >= '0' && c <= '9') goto digits_1; else if (c == OPENPAREN || c == OPENSQUAR || c == OPENCURLY) { pushls(&brackets, (intptr_t)c); if (c == OPENCURLY) { pushls(&closedFuncCharNo, (intptr_t)(linestarts[lineno] + charno - 1)); } r = c; goto leave; } else if (c == CLOSSQUAR) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != (intptr_t)OPENSQUAR) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error2; } } else { fatal(); post("unmatched '%c'\n", c); goto error2; } r = c; goto leave; } else if (c == CLOSPAREN) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != OPENPAREN) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error2; } } else { fatal(); post("unmatched '%c'\n", c); goto error2; } r = c; goto leave; } else if (c == CLOSCURLY) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != OPENCURLY) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error2; } lastClosedFuncCharNo = popls(&closedFuncCharNo); } else { fatal(); post("unmatched '%c'\n", c); goto error2; } r = c; goto leave; } else if (c == '^') { r = c; goto leave; } else if (c == '~') { r = c; goto leave; } else if (c == ';') { r = c; goto leave; } else if (c == ':') { r = c; goto leave; } else if (c == '`') { r = c; goto leave; } else if (c == '\\') goto symbol1; else if (c == '\'') goto symbol3; else if (c == '"') goto string1; else if (c == '.') { if ((c = input()) == '.') { if ((c = input()) == '.') { r = ELLIPSIS; goto leave; } else { r = DOTDOT; unput(c); goto leave; } } else { unput(c); r = '.'; goto leave; } } else if (c == '#') { if ((c = input()) == OPENCURLY) { pushls(&brackets, (intptr_t)OPENCURLY); pushls(&closedFuncCharNo, (intptr_t)(linestarts[lineno] + charno - 2)); r = BEGINCLOSEDFUNC; } else { unput(c); r = '#'; } goto leave; } else if (c == '$') { c = input(); if (c == '\\') { c = input(); switch (c) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'f': c = '\f'; break; case 'v': c = '\v'; break; } } r = processchar(c); goto leave; } else if (c == ',') { r = c; goto leave; } else if (c == '=') { c = input(); if (strchr(binopchars, c)) goto binop; else { unput(c); r = '='; goto leave; } } else if (strchr(binopchars, c)) goto binop; else if (!(isprint(c) || isspace(c) || c == 0)) { yylen = 0; goto start; } else goto error1; ident: c = input(); if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || (c >= '0' && c <= '9')) goto ident; else if (c == ':') { yytext[yylen] = 0; r = processkeywordbinop(yytext); goto leave; } else { unput(c); yytext[yylen] = 0; r = processident(yytext); goto leave; } symbol1: c = input(); if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') goto symbol2; else if (c >= '0' && c <= '9') goto symbol4; else { unput(c); yytext[yylen] = 0; r = processsymbol(yytext); goto leave; } symbol2: c = input(); if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || (c >= '0' && c <= '9')) goto symbol2; else { unput(c); yytext[yylen] = 0; r = processsymbol(yytext); goto leave; } symbol4: c = input(); if (c >= '0' && c <= '9') goto symbol4; else { unput(c); yytext[yylen] = 0; r = processsymbol(yytext); goto leave; } binop: c = input(); if (c == 0) goto binop2; if (strchr(binopchars, c)) goto binop; else { binop2: unput(c); yytext[yylen] = 0; r = processbinop(yytext); goto leave; } radix_digits_1: c = input(); if (c >= '0' && c <= '0' + sc_min(10, radix) - 1) goto radix_digits_1; if (c >= 'a' && c <= 'a' + sc_min(36, radix) - 11) goto radix_digits_1; if (c >= 'A' && c <= 'A' + sc_min(36, radix) - 11) goto radix_digits_1; if (c == '.') { goto radix_digits_2; } unput(c); yytext[yylen] = 0; r = processintradix(yytext, yylen, radix); goto leave; radix_digits_2: c = input(); if (c >= '0' && c <= '0' + sc_min(10, radix) - 1) goto radix_digits_2; if (c >= 'A' && c <= 'A' + sc_min(36, radix) - 11) goto radix_digits_2; // do not allow lower case after decimal point. unput(c); yytext[yylen] = 0; r = processfloatradix(yytext, yylen, radix); goto leave; hexdigits: c = input(); if (c >= '0' && c <= '9') goto hexdigits; if (c >= 'a' && c <= 'f') goto hexdigits; if (c >= 'A' && c <= 'F') goto hexdigits; unput(c); yytext[yylen] = 0; r = processhex(yytext); goto leave; digits_1: /* number started with digits */ c = input(); if (c >= '0' && c <= '9') goto digits_1; else if (c == 'r') { radix = sc_strtoi(yytext, yylen - 1, 10); yylen = 0; goto radix_digits_1; } else if (c == 'e' || c == 'E') goto expon_1; else if (c == '.') { c2 = input(); if (c2 >= '0' && c2 <= '9') goto digits_2; else { unput(c2); unput(c); yytext[yylen] = 0; r = processint(yytext); goto leave; } } else if (c == 'b' || c == 's') { d = input(); if (d >= '0' && d <= '9') goto accidental1; if (d == c) goto accidental2; goto accidental3; accidental1: d = input(); if (d >= '0' && d <= '9') goto accidental1; unput(d); yytext[yylen] = 0; r = processaccidental1(yytext); goto leave; accidental2: d = input(); if (d == c) goto accidental2; accidental3: unput(d); yytext[yylen] = 0; r = processaccidental2(yytext); goto leave; } else if (c == 'x') { yylen = 0; goto hexdigits; } else { unput(c); yytext[yylen] = 0; r = processint(yytext); goto leave; } digits_2: c = input(); if (c >= '0' && c <= '9') goto digits_2; else if (c == 'e' || c == 'E') goto expon_1; // else if (c == 'π' || c == '∏') { // --yylen; // yytext[yylen] = 0; // r = processfloat(yytext, 1); // goto leave; // } else { unput(c); yytext[yylen] = 0; r = processfloat(yytext, 0); goto leave; } expon_1: /* e has been seen, need digits */ c = input(); if (c >= '0' && c <= '9') goto expon_3; else if (c == '+' || c == '-') goto expon_2; else goto error1; expon_2: /* + or - seen but still need digits */ c = input(); if (c >= '0' && c <= '9') goto expon_3; else goto error1; expon_3: c = input(); if (c >= '0' && c <= '9') goto expon_3; // else if (c == 'π' || c == '∏') { // --yylen; // yytext[yylen] = 0; // r = processfloat(yytext, 1); // goto leave; // } else { unput(c); yytext[yylen] = 0; r = processfloat(yytext, 0); goto leave; } symbol3 : { int startline, endchar; startline = lineno; endchar = '\''; /*do { c = input(); } while (c != endchar && c != 0);*/ for (; yylen < MAXYYLEN;) { c = input(); if (c == '\n' || c == '\r') { post("Symbol open at end of line on line %d of %s\n", startline + errLineOffset, printingCurrfilename.c_str()); yylen = 0; r = 0; goto leave; } if (c == '\\') { yylen--; c = input(); } else if (c == endchar) break; if (c == 0) break; } if (c == 0) { post("Open ended symbol started on line %d of %s\n", startline + errLineOffset, printingCurrfilename.c_str()); yylen = 0; r = 0; goto leave; } yytext[yylen] = 0; yytext[yylen - 1] = 0; r = processsymbol(yytext); goto leave; } string1 : { int startline, endchar; startline = lineno; endchar = '"'; for (; yylen < MAXYYLEN;) { c = input(); if (c == '\\') { yylen--; c = input(); switch (c) { case 'n': yytext[yylen - 1] = '\n'; break; case 'r': yytext[yylen - 1] = '\r'; break; case 't': yytext[yylen - 1] = '\t'; break; case 'f': yytext[yylen - 1] = '\f'; break; case 'v': yytext[yylen - 1] = '\v'; break; } } else if (c == '\r') c = '\n'; else if (c == endchar) break; if (c == 0) break; } if (c == 0) { post("Open ended string started on line %d of %s\n", startline + errLineOffset, printingCurrfilename.c_str()); yylen = 0; r = 0; goto leave; } yylen--; do { c = input0(); } while (c && isspace(c)); if (c == '"') goto string1; else if (c) unput0(c); yytext[yylen] = 0; r = processstring(yytext); goto leave; } comment1: /* comment -- to end of line */ do { c = input0(); } while (c != '\n' && c != '\r' && c != 0); yylen = 0; if (c == 0) { r = 0; goto leave; } else goto start; comment2 : { int startline, clevel, prevc; startline = lineno; prevc = 0; clevel = 1; do { c = input0(); if (c == '/' && prevc == '*') { if (--clevel <= 0) break; else prevc = c, c = input0(); // eat both characters } else if (c == '*' && prevc == '/') { clevel++; prevc = c, c = input0(); // eat both characters } prevc = c; } while (c != 0); yylen = 0; if (c == 0) { post("Open ended comment started on line %d of %s\n", startline + errLineOffset, printingCurrfilename.c_str()); r = 0; goto leave; } goto start; } error1: yytext[yylen] = 0; post("illegal input string '%s' \n in %s line %d char %d\n", yytext, printingCurrfilename.c_str(), lineno + errLineOffset, charno); post("code %d\n", c); // postfl(" '%c' '%s'\n", c, binopchars); // postfl("%d\n", strchr(binopchars, c)); error2: post(" in %s line %d char %d\n", printingCurrfilename.c_str(), lineno + errLineOffset, charno); r = BADTOKEN; goto leave; leave: yytext[yylen] = 0; #if DEBUGLEX if (gDebugLexer) postfl("yylex: %d '%s'\n", r, yytext); #endif // if (lexCmdLine>0) postfl("yylex: %d '%s'\n",r,yytext); return r; } int processbinop(char* token) { PyrSymbol* sym; PyrSlot slot; PyrSlotNode* node; #if DEBUGLEX if (gDebugLexer) postfl("processbinop: '%s'\n", token); #endif sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; if (strcmp(token, "<-") == 0) return LEFTARROW; if (strcmp(token, "<>") == 0) return READWRITEVAR; if (strcmp(token, "|") == 0) return '|'; if (strcmp(token, "<") == 0) return '<'; if (strcmp(token, ">") == 0) return '>'; if (strcmp(token, "-") == 0) return '-'; if (strcmp(token, "*") == 0) return '*'; if (strcmp(token, "+") == 0) return '+'; return BINOP; } int processkeywordbinop(char* token) { PyrSymbol* sym; PyrSlot slot; PyrSlotNode* node; // post("'%s' file '%s'\n", token, currfilename); #if DEBUGLEX if (gDebugLexer) postfl("processkeywordbinop: '%s'\n", token); #endif token[strlen(token) - 1] = 0; // strip off colon sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return KEYBINOP; } int processident(char* token) { char c; PyrSymbol* sym; PyrSlot slot; PyrParseNode* node; c = token[0]; zzval = (intptr_t)-1; #if DEBUGLEX if (gDebugLexer) postfl("word: '%s'\n", token); #endif /* strcpy(uptoken, token); for (str = uptoken; *str; ++str) { if (*str >= 'a' && *str <= 'z') *str += 'A' - 'a'; }*/ if (token[0] == '_') { if (token[1] == 0) { node = newPyrCurryArgNode(); zzval = (intptr_t)node; return CURRYARG; } else { sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return PRIMITIVENAME; } } if (token[0] >= 'A' && token[0] <= 'Z') { sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; #if DEBUGLEX if (gDebugLexer) postfl("CLASSNAME: '%s'\n", token); #endif return CLASSNAME; } if (strcmp("var", token) == 0) return VAR; if (strcmp("arg", token) == 0) return ARG; if (strcmp("classvar", token) == 0) return CLASSVAR; if (strcmp("const", token) == 0) return SC_CONST; if (strcmp("while", token) == 0) { sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return WHILE; } if (strcmp("pi", token) == 0) { SetFloat(&slot, pi); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return PIE; } if (strcmp("true", token) == 0) { SetTrue(&slot); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return TRUEOBJ; } if (strcmp("false", token) == 0) { SetFalse(&slot); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return FALSEOBJ; } if (strcmp("nil", token) == 0) { SetNil(&slot); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return NILOBJ; } if (strcmp("inf", token) == 0) { SetFloat(&slot, std::numeric_limits<double>::infinity()); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return SC_FLOAT; } sym = getsym(token); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return NAME; } int processhex(char* s) { PyrSlot slot; PyrSlotNode* node; char* c; int val; #if DEBUGLEX if (gDebugLexer) postfl("processhex: '%s'\n", s); #endif c = s; val = 0; while (*c) { if (*c >= '0' && *c <= '9') val = val * 16 + *c - '0'; else if (*c >= 'a' && *c <= 'z') val = val * 16 + *c - 'a' + 10; else if (*c >= 'A' && *c <= 'Z') val = val * 16 + *c - 'A' + 10; c++; } SetInt(&slot, val); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return INTEGER; } int processintradix(char* s, int n, int radix) { PyrSlot slot; PyrSlotNode* node; #if DEBUGLEX if (gDebugLexer) postfl("processintradix: '%s'\n", s); #endif SetInt(&slot, sc_strtoi(s, n, radix)); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return INTEGER; } int processfloatradix(char* s, int n, int radix) { PyrSlot slot; PyrSlotNode* node; #if DEBUGLEX if (gDebugLexer) postfl("processfloatradix: '%s'\n", s); #endif SetFloat(&slot, sc_strtof(s, n, radix)); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return SC_FLOAT; } int processint(char* s) { PyrSlot slot; PyrSlotNode* node; #if DEBUGLEX if (gDebugLexer) postfl("processint: '%s'\n", s); #endif SetInt(&slot, atoi(s)); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return INTEGER; } int processchar(int c) { PyrSlot slot; PyrSlotNode* node; #if DEBUGLEX if (gDebugLexer) postfl("processhex: '%c'\n", c); #endif SetChar(&slot, c); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return ASCII; } int processfloat(char* s, int sawpi) { PyrSlot slot; PyrSlotNode* node; double z; #if DEBUGLEX if (gDebugLexer) postfl("processfloat: '%s'\n", s); #endif if (sawpi) { z = atof(s) * pi; SetFloat(&slot, z); } else { SetFloat(&slot, atof(s)); } node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return SC_FLOAT; } int processaccidental1(char* s) { PyrSlot slot; PyrSlotNode* node; char* c; double degree = 0.; double cents = 0.; double centsdiv = 1000.; #if 0 printf("processaccidental1: '%s'\n",s); #endif c = s; while (*c) { if (*c >= '0' && *c <= '9') degree = degree * 10. + *c - '0'; else break; c++; } if (*c == 'b') centsdiv = -1000.; else if (*c == 's') centsdiv = 1000.; c++; while (*c) { if (*c >= '0' && *c <= '9') { cents = cents * 10. + *c - '0'; } else break; c++; } if (cents > 499.) cents = 499.; SetFloat(&slot, degree + cents / centsdiv); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return ACCIDENTAL; } int processaccidental2(char* s) { PyrSlot slot; PyrSlotNode* node; char* c; double degree = 0.; double semitones = 0.; #if 0 printf("processaccidental2: '%s'\n",s); #endif c = s; while (*c) { if (*c >= '0' && *c <= '9') degree = degree * 10. + *c - '0'; else break; c++; } while (*c) { if (*c == 'b') semitones -= 1.; else if (*c == 's') semitones += 1.; c++; } if (semitones > 4.) semitones = 4.; else if (semitones < -4.) semitones = -4.; SetFloat(&slot, degree + semitones / 10.); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return ACCIDENTAL; } int processsymbol(char* s) { PyrSlot slot; PyrSlotNode* node; PyrSymbol* sym; #if DEBUGLEX if (gDebugLexer) postfl("processsymbol: '%s'\n", s); #endif sym = getsym(s + 1); SetSymbol(&slot, sym); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return SYMBOL; } int processstring(char* s) { PyrSlot slot; PyrSlotNode* node; PyrString* string; #if DEBUGLEX if (gDebugLexer) postfl("processstring: '%s'\n", s); #endif int flags = compilingCmdLine ? obj_immutable : obj_permanent | obj_immutable; string = newPyrString(gMainVMGlobals->gc, s + 1, flags, false); SetObject(&slot, string); node = newPyrSlotNode(&slot); zzval = (intptr_t)node; return STRING; } void yyerror(const char* s) { parseFailed = 1; yytext[yylen] = 0; error("%s\n", s); postErrorLine(lineno, linepos, charno); // Debugger(); } void fatal() { parseFailed = 1; yytext[yylen] = 0; error("Parse error\n"); postErrorLine(lineno, linepos, charno); // Debugger(); } void postErrorLine(int linenum, int start, int charpos) { int i, j, end, pos; char str[256]; // post("start %d\n", start); // parseFailed = true; post(" in %s\n", printingCurrfilename.c_str()); post(" line %d char %d:\n\n", linenum + errLineOffset, charpos); // nice: postfl previous line for context // postfl("text '%s' %d\n", text, text); // postfl error line for context pos = start + charpos; for (i = pos; i < textlen; ++i) { if (text[i] == 0 || text[i] == '\r' || text[i] == '\n') break; } end = i; for (i = start, j = 0; i < end && j < 255; ++i) { str[j++] = text[i]; } str[j] = 0; post(" %s\n ", str); for (i = 0; i < charpos - yylen; i++) post(" "); for (i = 0; i < yylen; i++) post("^"); post("\n"); i = end + 1; if (i < textlen) { // postfl following line for context for (j = 0; j < 255 && i < textlen; ++i) { if (text[i] == 0 || text[i] == '\r' || text[i] == '\n') break; str[j++] = text[i]; } str[j] = 0; post(" %s\n", str); } post("-----------------------------------\n", str); } void pstrncpy(unsigned char* s1, unsigned char* s2, int n); void pstrncpy(unsigned char* s1, unsigned char* s2, int n) { int i, m; m = *s2++; n = (n < m) ? n : m; *s1 = n; s1++; for (i = 0; i < n; ++i) { *s1 = *s2; s1++; s2++; } } int pstrcmp(unsigned char* s1, unsigned char* s2); int pstrcmp(unsigned char* s1, unsigned char* s2) { int i, len1, len2, len; len1 = *s1++; len2 = *s2++; len = sc_min(len1, len2); for (i = 0; i < len; ++i) { if (s1[i] < s2[i]) return -1; if (s1[i] > s2[i]) return 1; } if (len1 < len2) return -1; if (len1 > len2) return 1; return 0; } bool scanForClosingBracket() { int r, c, startLevel; intptr_t d; bool res = true; // finite state machine to parse input stream into tokens #if DEBUGLEX if (gDebugLexer) postfl("->scanForClosingBracket\n"); #endif startLevel = brackets.num; start: c = input0(); if (c == 0) goto leave; else if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f') { goto start; } else if (c == '\'') goto symbol3; else if (c == '"') goto string1; else if (c == '/') { c = input0(); if (c == '/') goto comment1; else if (c == '*') goto comment2; else { unput(c); goto start; } } else if (c == '$') { c = input0(); if (c == '\\') { c = input0(); switch (c) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'f': c = '\f'; break; case 'v': c = '\v'; break; } } goto start; } else if (c == OPENPAREN || c == OPENSQUAR || c == OPENCURLY) { pushls(&brackets, (intptr_t)c); r = c; goto start; } else if (c == CLOSSQUAR) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != OPENSQUAR) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error1; } } else { fatal(); post("unmatched '%c'\n", c); goto error1; } r = c; if (brackets.num < startLevel) goto leave; else goto start; } else if (c == CLOSPAREN) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != (intptr_t)OPENPAREN) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error1; } } else { fatal(); post("unmatched '%c'\n", c); goto error1; } if (brackets.num < startLevel) goto leave; else goto start; } else if (c == CLOSCURLY) { if (!emptyls(&brackets)) { if ((d = popls(&brackets)) != OPENCURLY) { fatal(); post("opening bracket was a '%c', but found a '%c'\n", d, c); goto error1; } } else { fatal(); post("unmatched '%c'\n", c); goto error1; } if (brackets.num < startLevel) goto leave; else goto start; } else { goto start; } symbol3 : { int startline, endchar; startline = lineno; endchar = '\''; do { c = input0(); if (c == '\\') { input0(); } } while (c != endchar && c != 0); if (c == 0) { post("Open ended symbol started on line %d of %s\n", startline, printingCurrfilename.c_str()); goto error2; } goto start; } string1 : { int startline, endchar; startline = lineno; endchar = '\"'; do { c = input0(); if (c == '\\') { input0(); } } while (c != endchar && c != 0); if (c == 0) { post("Open ended string started on line %d of %s\n", startline, printingCurrfilename.c_str()); goto error2; } goto start; } comment1: /* comment -- to end of line */ do { c = input0(); } while (c != '\n' && c != '\r' && c != 0); if (c == 0) { goto leave; } else goto start; comment2 : { int startline, clevel, prevc; startline = lineno; prevc = 0; clevel = 1; do { c = input0(); if (c == '/' && prevc == '*') { if (--clevel <= 0) break; else prevc = c, c = input0(); // eat both characters } else if (c == '*' && prevc == '/') { clevel++; prevc = c, c = input0(); // eat both characters } prevc = c; } while (c != 0); if (c == 0) { post("Open ended comment started on line %d of %s\n", startline, printingCurrfilename.c_str()); goto error2; } goto start; } error1: post(" in %s line %d char %d\n", printingCurrfilename.c_str(), lineno, charno); res = false; goto leave; error2: res = false; goto leave; leave: #if DEBUGLEX if (gDebugLexer) postfl("<-scanForClosingBracket\n"); #endif return res; } int numClassDeps; static ClassExtFile* sClassExtFiles; static ClassExtFile* eClassExtFiles; ClassExtFile* newClassExtFile(PyrSymbol* fileSym, int startPos, int endPos); ClassExtFile* newClassExtFile(PyrSymbol* fileSym, int startPos, int endPos) { ClassExtFile* classext; classext = (ClassExtFile*)pyr_pool_compile->Alloc(sizeof(ClassExtFile)); MEMFAIL(classext); classext->fileSym = fileSym; classext->next = nullptr; classext->startPos = startPos; classext->endPos = endPos; if (!sClassExtFiles) sClassExtFiles = classext; else eClassExtFiles->next = classext; eClassExtFiles = classext; return classext; } ClassDependancy* newClassDependancy(PyrSymbol* className, PyrSymbol* superClassName, PyrSymbol* fileSym, int startPos, int endPos, int lineOffset) { ClassDependancy* classdep; // post("classdep '%s' '%s' '%s' %d %d\n", className->name, superClassName->name, // fileSym->name, className, superClassName); // pyrmalloc: // lifetime: kill after compile. numClassDeps++; if (className->classdep) { error("duplicate Class found: '%s' \n", className->name); post("%s\n", className->classdep->fileSym->name); postfl("%s\n\n", fileSym->name); return className->classdep; } classdep = (ClassDependancy*)pyr_pool_compile->Alloc(sizeof(ClassDependancy)); MEMFAIL(classdep); classdep->className = className; classdep->superClassName = superClassName; classdep->fileSym = fileSym; classdep->superClassDep = nullptr; classdep->next = nullptr; classdep->subclasses = nullptr; classdep->startPos = startPos; classdep->endPos = endPos; classdep->lineOffset = lineOffset; className->classdep = classdep; return classdep; } void buildDepTree() { ClassDependancy* next; SymbolTable* symbolTable = gMainVMGlobals->symbolTable; // postfl("->buildDepTree\n"); fflush(stdout); for (int i = 0; i < symbolTable->TableSize(); ++i) { PyrSymbol* sym = symbolTable->Get(i); if (sym && (sym->flags & sym_Class)) { if (sym->classdep) { if (sym->classdep->superClassName->classdep) { next = sym->classdep->superClassName->classdep->subclasses; sym->classdep->superClassName->classdep->subclasses = sym->classdep; sym->classdep->next = next; } else if (sym->classdep->superClassName != s_none) { error("Superclass '%s' of class '%s' is not defined in any file.\n%s\n", sym->classdep->superClassName->name, sym->classdep->className->name, sym->classdep->fileSym->name); } } } } // postfl("<-buildDepTree\n"); fflush(stdout); } extern PyrClass* gClassList; ClassDependancy** gClassCompileOrder; int gClassCompileOrderNum = 0; int gClassCompileOrderSize = 1000; void compileDepTree(); void traverseFullDepTree() { // postfl("->traverseFullDepTree\n"); fflush(stdout); gClassCompileOrderNum = 0; gClassCompileOrder = (ClassDependancy**)pyr_pool_compile->Alloc(gClassCompileOrderSize * sizeof(ClassDependancy)); MEMFAIL(gClassCompileOrder); // parse and compile all files initParser(); // sets compiler errors to 0 gParserResult = -1; traverseDepTree(s_object->classdep, 0); compileDepTree(); // compiles backwards using the order defined in gClassCompileOrder compileClassExtensions(); pyr_pool_compile->Free(gClassCompileOrder); finiParser(); // postfl("<-traverseFullDepTree\n"); fflush(stdout); } void traverseDepTree(ClassDependancy* classdep, int level) { ClassDependancy* subclassdep; if (!classdep) return; subclassdep = classdep->subclasses; for (; subclassdep; subclassdep = subclassdep->next) { traverseDepTree(subclassdep, level + 1); } if (gClassCompileOrderNum > gClassCompileOrderSize) { gClassCompileOrderSize *= 2; gClassCompileOrder = (ClassDependancy**)pyr_pool_compile->Realloc( gClassCompileOrder, gClassCompileOrderSize * sizeof(ClassDependancy)); MEMFAIL(gClassCompileOrder); } /* postfl("traverse level:%d, gClassCompileOrderNum:%d, '%s' '%s' '%s'\n", level, gClassCompileOrderNum, classdep->className->name, classdep->superClassName->name, classdep->fileSym->name); fflush(stdout); */ gClassCompileOrder[gClassCompileOrderNum++] = classdep; } void compileClass(PyrSymbol* fileSym, int startPos, int endPos, int lineOffset) { // fprintf(stderr, "compileClass: %d\n", fileSym->u.index); gCompilingFileSym = fileSym; gCompilingVMGlobals = nullptr; gRootParseNode = nullptr; initParserPool(); if (startLexer(fileSym, fs::path(), startPos, endPos, lineOffset)) { // postfl("->Parsing %s\n", fileSym->name); fflush(stdout); parseFailed = yyparse(); // postfl("<-Parsing %s %d\n", fileSym->name, parseFailed); fflush(stdout); // post("parseFailed %d\n", parseFailed); fflush(stdout); if (!parseFailed && gRootParseNode) { // postfl("Compiling nodes %p\n", gRootParseNode);fflush(stdout); compilingCmdLine = false; compileNodeList(gRootParseNode, true); // postfl("done compiling\n");fflush(stdout); } else { compileErrors++; fs::path pathname(fileSym->name); error("file '%s' parse failed\n", SC_Codecvt::path_to_utf8_str(pathname).c_str()); postfl("error parsing\n"); } finiLexer(); } else { error("file '%s' open failed\n", fileSym->name); } freeParserPool(); } void compileDepTree() { ClassDependancy* classdep; int i; for (i = gClassCompileOrderNum - 1; i >= 0; --i) { classdep = gClassCompileOrder[i]; /*postfl("compile %d '%s' '%s' '%s'...%d/%d/%d\n", i, classdep->className->name, classdep->superClassName->name, classdep->fileSym->name, classdep->startLine, classdep->endLine, classDep->lineOffset);*/ compileClass(classdep->fileSym, classdep->startPos, classdep->endPos, classdep->lineOffset); } // postfl("<compile\n"); } void compileClassExtensions() { if (sClassExtFiles) { ClassExtFile* classext = sClassExtFiles; do { // postfl("compile class ext: %d/%d\n", classext->startPos, classext->endPos); compileClass(classext->fileSym, classext->startPos, classext->endPos, -1); classext = classext->next; } while (classext); } } void findDiscrepancy(); void traverseFullDepTree2() { // assign a class index to all classes if (!parseFailed && !compileErrors) { buildClassTree(); gNumClasses = 0; // now I index them during pass one indexClassTree(class_object, 0); setSelectorFlags(); if (2 * numClassDeps != gNumClasses) { error("There is a discrepancy.\n"); /* not always correct if(2*numClassDeps < gNumClasses) { post("Duplicate files may exist in the directory structure.\n"); } else { post("Some class files may be missing.\n"); } */ post("numClassDeps %d gNumClasses %d\n", numClassDeps, gNumClasses); findDiscrepancy(); compileErrors++; } else { double elapsed; buildBigMethodMatrix(); SymbolTable* symbolTable = gMainVMGlobals->symbolTable; post("\tNumber of Symbols %d\n", symbolTable->NumItems()); post("\tByte Code Size %d\n", totalByteCodes); // elapsed = TickCount() - compileStartTime; // elapsed = 0; elapsed = elapsedTime() - compileStartTime; post("\tcompiled %d files in %.2f seconds\n", gNumCompiledFiles, elapsed); if (numOverwrites == 1) { post("\nInfo: One method is currently overwritten by an extension. To see which, " "execute:\nMethodOverride.printAll\n\n"); } else if (numOverwrites > 1) { post("\nInfo: %i methods are currently overwritten by extensions. To see which, " "execute:\nMethodOverride.printAll\n\n", numOverwrites); } post("compile done\n"); } } } bool parseOneClass(PyrSymbol* fileSym) { int token; PyrSymbol *className, *superClassName; ClassDependancy* classdep; bool res; int startPos, startLineOffset; res = true; startPos = textpos; startLineOffset = lineno - 1; token = yylex(); if (token == CLASSNAME) { className = slotRawSymbol(&((PyrSlotNode*)zzval)->mSlot); // I think this is wrong: zzval is space pool alloced // pyrfree((PyrSlot*)zzval); token = yylex(); if (token == 0) return false; if (token == OPENSQUAR) { scanForClosingBracket(); // eat indexing spec token = yylex(); if (token == 0) return false; } if (token == ':') { token = yylex(); // get super class if (token == 0) return false; if (token == CLASSNAME) { superClassName = slotRawSymbol(&((PyrSlotNode*)zzval)->mSlot); // I think this is wrong: zzval is space pool alloced // pyrfree((PyrSlot*)zzval); token = yylex(); if (token == 0) return false; if (token == OPENCURLY) { scanForClosingBracket(); // eat class body classdep = newClassDependancy(className, superClassName, fileSym, startPos, textpos, startLineOffset); } else { compileErrors++; postfl("Expected %c. got token: '%s' %d\n", OPENCURLY, yytext, token); postErrorLine(lineno, linepos, charno); return false; } } else { compileErrors++; post("Expected superclass name. got token: '%s' %d\n", yytext, token); postErrorLine(lineno, linepos, charno); return false; } } else if (token == OPENCURLY) { if (className == s_object) superClassName = s_none; else superClassName = s_object; scanForClosingBracket(); // eat class body classdep = newClassDependancy(className, superClassName, fileSym, startPos, textpos, startLineOffset); } else { compileErrors++; post("Expected ':' or %c. got token: '%s' %d\n", OPENCURLY, yytext, token); postErrorLine(lineno, linepos, charno); return false; } } else if (token == '+') { token = yylex(); if (token == 0) return false; scanForClosingBracket(); newClassExtFile(fileSym, startPos, textpos); return false; } else { if (token != 0) { compileErrors++; post("Expected class name. got token: '%s' %d\n", yytext, token); postErrorLine(lineno, linepos, charno); return false; } else { res = false; } } return res; } void initPassOne() { // dump_pool_histo(pyr_pool_runtime); pyr_pool_runtime->FreeAllInternal(); // dump_pool_histo(pyr_pool_runtime); // gPermanentObjPool.Init(pyr_pool_runtime, PERMOBJCHUNK); sClassExtFiles = nullptr; void* ptr = pyr_pool_runtime->Alloc(sizeof(SymbolTable)); MEMFAIL(ptr); gMainVMGlobals->symbolTable = new (ptr) SymbolTable(pyr_pool_runtime, 65536); initSymbols(); // initialize symbol globals initSpecialSelectors(); initSpecialClasses(); initClasses(); initParserPool(); initParseNodes(); initPrimitives(); initLexer(); compileErrors = 0; numClassDeps = 0; compiledOK = false; compiledDirectories.clear(); // main class library folder: only used for relative path resolution gCompileDir = SC_Filesystem::instance().getDirectory(DirName::Resource) / "SCClassLibrary"; } void finiPassOne() { // postfl("->finiPassOne\n"); freeParserPool(); // postfl("<-finiPassOne\n"); } /** * \brief \c true if \c dir is one of the language config's default classlib directories */ static bool isDefaultClassLibraryDirectory(const fs::path& dir) { auto const& defaultDirs = gLanguageConfig->defaultClassLibraryDirectories(); auto const iter = std::find(defaultDirs.begin(), defaultDirs.end(), dir); return iter != defaultDirs.end(); } /** * \brief Handles a missing directory encountered during compilation. * * If the directory is one of the default directories traversed during compilation, * try to create it, silently ignoring failure (most likely from permissions failure). * Otherwise, warn the user to help catch mistyped/missing directory names. See #3468. */ static void passOne_HandleMissingDirectory(const fs::path& dir) { if (isDefaultClassLibraryDirectory(dir)) { std::error_code ec {}; fs::create_directories(dir, ec); } else { post("WARNING: Could not open directory: '%s'\n" "\tTo resolve this, either create the directory or remove it from your compilation paths.\n\n", SC_Codecvt::path_to_utf8_str(dir).c_str()); } } fs::path relativeToCompileDir(const fs::path& p) { return fs::relative(p, gCompileDir); } /** \brief Determines whether the directory should be skipped during compilation. * * \param dir : The directory to check, as a `path` object * \returns `true` iff any of the following conditions is true: * - the directory has already been compiled * - the language configuration says this path is excluded * - SC_Filesystem::shouldNotCompileDirectory(dir) returns `true` */ static bool passOne_ShouldSkipDirectory(const fs::path& dir) { return (compiledDirectories.find(dir) != compiledDirectories.end()) || (gLanguageConfig && gLanguageConfig->pathIsExcluded(dir)) || (SC_Filesystem::instance().shouldNotCompileDirectory(dir)); } /** \brief Compile the contents of a single directory * * This method compiles any .sc files in a single directory, working * via depth-first recursion. This routine is designed to fail gracefully, * and only indicates failure if something truly unexpected happens. These * conditions are: * - an error occurred while trying to open a directory, other than the case * the case that the object doesn't exist. * - an error occurred while calling `passOne_processOneFile` on a file * - an error occurred in a recursive call of this routine on a macOS alias * Otherwise, this method returns success, even if: * - `dir` does not exist * - Iterating to the next file fails for any reason at all * * This method returns with a success state immediately if the directory * should not be compiled according to the language configuration. * * \param dir : The directory to traverse, as a `path` object * \returns `true` if processing was successful, `false` if it failed. * See above for what constitutes success and failure conditions. */ static bool passOne_ProcessDir(const fs::path& dir) { // Prefer non-throwing versions of filesystem functions, since they are actually not unexpected // and because it's faster to use error codes. std::error_code ec; // Perform tilde expansion on incoming dir. const fs::path expdir = SC_Filesystem::instance().expandTilde(dir); // Using a recursive_directory_iterator is much faster than actually calling this function // recursively. Speedup from the switch was about 1.5x. _Do_ recurse on symlinks. fs::recursive_directory_iterator rditer(expdir, fs::directory_options::follow_directory_symlink, ec); // Check preconditions: are we able to access the file, and should we compile it according to // the language configuration? if (ec) { // If we got an error, post a warning if it was because the target wasn't found, and return success. // Otherwise, post the error and fail. if (ec.default_error_condition() == std::errc::no_such_file_or_directory) { passOne_HandleMissingDirectory(expdir); return true; } else { error("Could not open directory '%s': (%d) %s\n", SC_Codecvt::path_to_utf8_str(expdir).c_str(), ec.value(), ec.message().c_str()); return false; } } else if (passOne_ShouldSkipDirectory(expdir)) { // If we should skip the directory, just return success now. return true; } else { // Let the user know we are in fact compiling this directory. post("\tCompiling directory '%s'\n", SC_Codecvt::path_to_utf8_str(expdir).c_str()); } // Record that we have touched this directory already. compiledDirectories.insert(expdir); // Invariant: we have processed (or begun to process) every directory or file already // touched by the iterator. while (rditer != fs::end(rditer)) { const fs::path path = *rditer; // If the file is a directory, perform the same checks as above to see if we should // skip compilation on it. if (fs::is_directory(path)) { if (passOne_ShouldSkipDirectory(path)) { rditer.disable_recursion_pending(); // don't "push" into the next level of the hierarchy } else { // Mark this directory as compiled. // By not calling no_push(), we allow the iterator to enter the directory compiledDirectories.insert(path); } } else { // ordinary file // Try to resolve a potential alias. Possible outcomes: // - it was an alias & is also a directory: try to recurse on it // - resolution failed: returns empty path: let the user know // - it was not an alias, or was an alias that wasn't a directory: try to process it as a source file bool isAlias = false; const fs::path& respath = SC_Filesystem::resolveIfAlias(path, isAlias); if (isAlias && fs::is_directory(respath)) { // If the resolved alias is a directory, recurse on it. if (!passOne_ProcessDir(respath)) { return false; } } else if (respath.empty()) { error("Could not resolve symlink: %s\n", SC_Codecvt::path_to_utf8_str(path).c_str()); } else if (!passOne_ProcessOneFile(respath)) { return false; } } // Error-code version of `++` rditer.increment(ec); if (ec) { // If iteration failed, allow compilation to continue, but bail out of this directory. error("Could not iterate on '%s': %s\n", SC_Codecvt::path_to_utf8_str(path).c_str(), ec.message().c_str()); return true; } } return true; } bool passOne() { initPassOne(); bool success = gLanguageConfig->forEachIncludedDirectory(passOne_ProcessDir); finiPassOne(); return success; } /// True if file doesn't begin with '.', and ends with either '.sc' or '.rtf' bool isValidSourceFileName(const fs::path& path) { const fs::path& ext = path.extension(); return path.filename().c_str()[0] != '.' && // must not be hidden file ((ext == ".sc") || (ext == ".rtf" && path.stem().extension() == ".sc")); } /** \brief Attempt to parse a single SuperCollider source file * * Parsing is aborted if the file doesn't have a valid source file name, * or if the file can't be opened. * (Sekhar's replacement) * * \returns Whether parsing was successful. The only failure condition occurs * when the file can't be opened. */ bool passOne_ProcessOneFile(const fs::path& path) { bool success = true; const std::string path_str = SC_Codecvt::path_to_utf8_str(path); const char* path_c_str = path_str.c_str(); if (gLanguageConfig && gLanguageConfig->pathIsExcluded(path)) { post("\texcluding file: '%s'\n", path_c_str); return success; } if (isValidSourceFileName(path)) { gNumCompiledFiles++; PyrSymbol* fileSym = getsym(path_c_str); fileSym->u.source = nullptr; if (startLexer(fileSym, path, -1, -1, -1)) { while (parseOneClass(fileSym)) {}; finiLexer(); } else { error("file '%s' open failed\n", path_c_str); success = false; } } else { // wasn't a valid source file; ignore } return success; } void schedRun(); void compileSucceeded(); void compileSucceeded() { compiledOK = !(parseFailed || compileErrors); if (compiledOK) { compiledOK = true; compiledOK = initRuntime(gMainVMGlobals, 128 * 1024, pyr_pool_runtime); if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; ++g->sp; SetObject(g->sp, g->process); runInterpreter(g, s_startup, 1); g->canCallOS = false; schedRun(); } flushPostBuf(); } } static void runShutdown() { // printf("->aboutToCompileLibrary\n"); gLangMutex.lock(); if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; ++g->sp; SetObject(g->sp, g->process); runInterpreter(g, s_shutdown, 1); g->canCallOS = false; } gLangMutex.unlock(); // printf("<-aboutToCompileLibrary\n"); } void closeAllGUIScreens(); void TempoClock_stopAll(void); void closeAllCustomPorts(); void shutdownLibrary() { closeAllGUIScreens(); schedStop(); runShutdown(); TempoClock_stopAll(); gLangMutex.lock(); closeAllCustomPorts(); if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; g->gc->RunAllFinalizers(); g->canCallOS = false; } pyr_pool_runtime->FreeAll(); compiledOK = false; gLangMutex.unlock(); deinitPrimitives(); } SCLANG_DLLEXPORT_C bool compileLibrary(bool standalone) { // printf("->compileLibrary\n"); shutdownLibrary(); gLangMutex.lock(); gNumCompiledFiles = 0; compiledOK = false; if (!gLanguageConfig) { SC_LanguageConfig::readLibraryConfig(standalone); } compileStartTime = elapsedTime(); totalByteCodes = 0; #ifdef NDEBUG postfl("compiling class library...\n"); #else postfl("compiling class library (debug build)...\n"); #endif bool res = passOne(); if (res) { if (!compileErrors) { buildDepTree(); traverseFullDepTree(); traverseFullDepTree2(); flushPostBuf(); if (!compileErrors && gShowWarnings) { SymbolTable* symbolTable = gMainVMGlobals->symbolTable; symbolTable->CheckSymbols(); } } pyr_pool_compile->FreeAll(); flushPostBuf(); compileSucceeded(); } else { compiledOK = false; } gLangMutex.unlock(); // printf("<-compileLibrary\n"); return compiledOK; } void signal_init_globs(); void dumpByteCodes(PyrBlock* theBlock); SCLANG_DLLEXPORT_C void runLibrary(PyrSymbol* selector) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; try { if (compiledOK) { ++g->sp; SetObject(g->sp, g->process); runInterpreter(g, selector, 1); } else { postfl("Library has not been compiled successfully.\n"); } } catch (std::exception& ex) { PyrMethod* meth = g->method; if (meth) { int ip = slotRawInt8Array(&meth->code) ? g->ip - slotRawInt8Array(&meth->code)->b : -1; post("caught exception in runLibrary %s:%s %3d\n", slotRawSymbol(&slotRawClass(&meth->ownerclass)->name)->name, slotRawSymbol(&meth->name)->name, ip); dumpByteCodes(meth); } else { post("caught exception in runLibrary\n"); } error(ex.what()); } catch (...) { postfl("DANGER: OUT of MEMORY. Operation failed.\n"); } g->canCallOS = false; }
62,501
C++
.cpp
2,032
23.399606
120
0.545328
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
29,851
SC_LanguageClient.cpp
supercollider_supercollider/lang/LangSource/SC_LanguageClient.cpp
/* Abstract interpreter interface. Copyright (c) 2003 2004 stefan kersten. ==================================================================== 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_LanguageClient.h" #include "SC_Lock.h" #include <cstring> #include <string> #include <cerrno> #ifdef _WIN32 # include <stdio.h> # include <direct.h> # ifndef PATH_MAX # define PATH_MAX _MAX_PATH # endif #else # include <unistd.h> #endif #include "PyrObject.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrSched.h" #include "GC.h" #include "VMGlobals.h" #include "SCBase.h" #include "SC_StringBuffer.h" void closeAllGUIScreens(); void initGUI(); void initGUIPrimitives(); extern PyrString* newPyrStringN(class PyrGC* gc, long length, long flags, long collect); // ===================================================================== // SC_LanguageClient // ===================================================================== SC_LanguageClient* gInstance = nullptr; SC_Lock gInstanceMutex; class HiddenLanguageClient { public: HiddenLanguageClient(): mPostFile(nullptr), mScratch(0), mRunning(false) {} std::string mName; FILE* mPostFile; SC_StringBuffer mScratch; bool mRunning; }; SC_LanguageClient::SC_LanguageClient(const char* name) { mHiddenClient = new HiddenLanguageClient; lockInstance(); if (gInstance) { unlockInstance(); fprintf(stderr, "SC_LanguageClient already running\n"); abort(); } mHiddenClient->mName = name; gInstance = this; unlockInstance(); } SC_LanguageClient::~SC_LanguageClient() { lockInstance(); gInstance = nullptr; delete mHiddenClient; unlockInstance(); } void SC_LanguageClient::initRuntime(const Options& opt) { // start virtual machine if (!mHiddenClient->mRunning) { mHiddenClient->mRunning = true; if (opt.mRuntimeDir) { int err = chdir(opt.mRuntimeDir); if (err) error("Cannot change to runtime directory: %s", strerror(errno)); } pyr_init_mem_pools(opt.mMemSpace, opt.mMemGrow); init_OSC(opt.mPort); schedInit(); onInitRuntime(); } } void SC_LanguageClient::shutdownRuntime() { schedCleanup(); cleanup_OSC(); } void SC_LanguageClient::compileLibrary(bool standalone) { ::compileLibrary(standalone); } extern void shutdownLibrary(); void SC_LanguageClient::shutdownLibrary() { ::shutdownLibrary(); flush(); } void SC_LanguageClient::recompileLibrary(bool standalone) { compileLibrary(standalone); } void SC_LanguageClient::setCmdLine(const char* buf, size_t size) { if (isLibraryCompiled()) { lock(); if (isLibraryCompiled()) { VMGlobals* g = gMainVMGlobals; PyrString* strobj = newPyrStringN(g->gc, size, 0, true); memcpy(strobj->s, buf, size); SetObject(&slotRawInterpreter(&g->process->interpreter)->cmdLine, strobj); g->gc->GCWriteNew(slotRawObject(&g->process->interpreter), strobj); // we know strobj is white so we can use GCWriteNew } unlock(); } } void SC_LanguageClient::setCmdLine(const char* str) { setCmdLine(str, strlen(str)); } void SC_LanguageClient::setCmdLinef(const char* fmt, ...) { SC_StringBuffer& scratch = mHiddenClient->mScratch; va_list ap; va_start(ap, fmt); scratch.reset(); scratch.vappendf(fmt, ap); va_end(ap); setCmdLine(scratch.getData()); } void SC_LanguageClient::runLibrary(PyrSymbol* symbol) { lock(); ::runLibrary(symbol); unlock(); } void SC_LanguageClient::runLibrary(const char* methodName) { lock(); ::runLibrary(getsym(methodName)); unlock(); } void SC_LanguageClient::executeFile(const char* fileName) { std::string escaped_file_name(fileName); int i = 0; while (i < escaped_file_name.size()) { if (escaped_file_name[i] == '\\') escaped_file_name.insert(++i, 1, '\\'); ++i; } setCmdLinef("thisProcess.interpreter.executeFile(\"%s\")", escaped_file_name.c_str()); runLibrary(s_interpretCmdLine); } void SC_LanguageClient::snprintMemArg(char* dst, size_t size, int arg) { int rem = arg; int mod = 0; const char* modstr = ""; while (((rem % 1024) == 0) && (mod < 4)) { rem /= 1024; mod++; } switch (mod) { case 0: modstr = ""; break; case 1: modstr = "k"; break; case 2: modstr = "m"; break; case 3: modstr = "g"; break; default: rem = arg; modstr = ""; break; } snprintf(dst, size, "%d%s", rem, modstr); } bool SC_LanguageClient::parseMemArg(const char* arg, int* res) { long value, factor = 1; char* endPtr = nullptr; if (*arg == '\0') return false; value = strtol(arg, &endPtr, 0); char spec = *endPtr++; if (spec != '\0') { if (*endPtr != '\0') // trailing characters return false; switch (spec) { case 'k': factor = 1024; break; case 'm': factor = 1024 * 1024; break; default: // invalid mem spec return false; } } *res = value * factor; return true; } bool SC_LanguageClient::parsePortArg(const char* arg, int* res) { long value; char* endPtr; if (*arg == '\0') return false; value = strtol(arg, &endPtr, 0); if ((*endPtr != '\0') || (value < 0) || (value > 65535)) return false; *res = value; return true; } void SC_LanguageClient::tick() { if (trylock()) { if (isLibraryCompiled()) { ::runLibrary(s_tick); } unlock(); } flush(); } bool SC_LanguageClient::tickLocked(double* nextTime) { if (isLibraryCompiled()) { ::runLibrary(s_tick); } return slotDoubleVal(&gMainVMGlobals->result, nextTime) == errNone; } void SC_LanguageClient::onInitRuntime() {} void SC_LanguageClient::onLibraryStartup() {} void SC_LanguageClient::onLibraryShutdown() {} void SC_LanguageClient::onInterpStartup() {} // runLibrary methods void SC_LanguageClient::interpretCmdLine() { runLibrary(s_interpretCmdLine); } void SC_LanguageClient::interpretPrintCmdLine() { runLibrary(s_interpretPrintCmdLine); } void SC_LanguageClient::runMain() { runLibrary(s_run); } void SC_LanguageClient::stopMain() { runLibrary(s_stop); } // locks void SC_LanguageClient::lock() { gLangMutex.lock(); } bool SC_LanguageClient::trylock() { return gLangMutex.try_lock(); } void SC_LanguageClient::unlock() { gLangMutex.unlock(); } SC_LanguageClient* SC_LanguageClient::instance() { return gInstance; } void SC_LanguageClient::lockInstance() { gInstanceMutex.lock(); } void SC_LanguageClient::unlockInstance() { gInstanceMutex.unlock(); } extern bool compiledOK; const char* SC_LanguageClient::getName() const { return mHiddenClient->mName.c_str(); } FILE* SC_LanguageClient::getPostFile() { return mHiddenClient->mPostFile; } void SC_LanguageClient::setPostFile(FILE* file) { mHiddenClient->mPostFile = file; } bool SC_LanguageClient::isLibraryCompiled() { return compiledOK; } int SC_LanguageClient::run(int argc, char** argv) { throw std::runtime_error("SC_LanguageClient::run only supported on terminal client"); } // ===================================================================== // library functions // ===================================================================== void setPostFile(FILE* file) { SC_LanguageClient::instance()->setPostFile(file); } int vpost(const char* fmt, va_list ap) { char buf[512]; int n = vsnprintf(buf, sizeof(buf), fmt, ap); if (n > 0) { SC_LanguageClient* client = SC_LanguageClient::lockedInstance(); if (client) client->postText(buf, sc_min(n, sizeof(buf) - 1)); SC_LanguageClient::unlockInstance(); } return 0; } void post(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vpost(fmt, ap); va_end(ap); } void postfl(const char* fmt, ...) { char buf[512]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof(buf), fmt, ap); if (n > 0) { SC_LanguageClient* client = SC_LanguageClient::lockedInstance(); if (client) client->postFlush(buf, sc_min(n, sizeof(buf) - 1)); SC_LanguageClient::unlockInstance(); } va_end(ap); } void postText(const char* str, long len) { SC_LanguageClient* client = SC_LanguageClient::lockedInstance(); if (client) client->postFlush(str, len); SC_LanguageClient::unlockInstance(); } void postChar(char c) { SC_LanguageClient* client = SC_LanguageClient::lockedInstance(); if (client) client->postFlush(&c, sizeof(char)); SC_LanguageClient::unlockInstance(); } void error(const char* fmt, ...) { char buf[512]; va_list ap; va_start(ap, fmt); int n = vsnprintf(buf, sizeof(buf), fmt, ap); if (n > 0) { SC_LanguageClient* client = SC_LanguageClient::lockedInstance(); if (client) client->postError(buf, sc_min(n, sizeof(buf) - 1)); SC_LanguageClient::unlockInstance(); } va_end(ap); } void flushPostBuf(void) { SC_LanguageClient::instance()->flush(); } void closeAllGUIScreens() { SC_LanguageClient::instance()->onLibraryShutdown(); } void initGUI() { SC_LanguageClient::instance()->onInterpStartup(); } void initGUIPrimitives() { SC_LanguageClient::instance()->onLibraryStartup(); } long scMIDIout(int port, int len, int statushi, int chan, int data1, int data2); long scMIDIout(int port, int len, int statushi, int chan, int data1, int data2) { return 0; } // EOF
10,689
C++
.cpp
317
28.637224
93
0.634765
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
29,853
PyrSymbolTable.cpp
supercollider_supercollider/lang/LangSource/PyrSymbolTable.cpp
/* 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 "SCBase.h" #include "PyrSymbolTable.h" #include "clz.h" #include <stdlib.h> #include <string.h> #include "InitAlloc.h" #include "VMGlobals.h" #include "Hash.h" SCLANG_DLLEXPORT_C PyrSymbol* getsym(const char* name) { PyrSymbol* symbol = gMainVMGlobals->symbolTable->Make(name); if (!symbol) { fprintf(stderr, "getsym failed '%s'\n", name); exit(-1); } return symbol; } SCLANG_DLLEXPORT_C PyrSymbol* getmetasym(const char* name) { char str[256]; strcpy(str, "Meta_"); strncat(str, name, 250); return getsym(str); } SCLANG_DLLEXPORT_C PyrSymbol* findsym(const char* name) { PyrSymbol* symbol = gMainVMGlobals->symbolTable->Find(name); return symbol; } SymbolSpace::SymbolSpace(AllocPool* inPool) { mPool = inPool; mStringPool.Init(inPool, STRINGCHUNK, STRINGCHUNK, STRINGCHUNK / 5); mSymbolPool.Init(inPool, SYMBOLCHUNK, SYMBOLCHUNK, SYMBOLCHUNK / 5); } PyrSymbol* SymbolSpace::NewSymbol(const char* inName, int inHash, int inLength) { PyrSymbol* sym; sym = (PyrSymbol*)mSymbolPool.Alloc(sizeof(PyrSymbol)); MEMFAIL(sym); sym->name = (char*)mStringPool.Alloc(inLength + 1); MEMFAIL(sym->name); strcpy(sym->name, inName); sym->hash = inHash; sym->length = inLength; sym->specialIndex = -1; sym->flags = 0; if (inName[0] >= 'A' && inName[0] <= 'Z') sym->flags |= sym_Class; if (inLength > 1 && inName[0] == '_') sym->flags |= sym_Primitive; if (inLength > 1 && inName[inLength - 1] == '_') sym->flags |= sym_Setter; sym->u.index = 0; sym->classdep = nullptr; return sym; } SymbolTable::SymbolTable(AllocPool* inPool, int inSize): mPool(inPool), mSpace(inPool), mMaxItems(inSize) { assert(ISPOWEROFTWO(inSize)); AllocTable(); } void SymbolTable::CopyFrom(SymbolTable& inTable) { MakeEmpty(); Rehash(inTable.mTable, inTable.mMaxItems); } int SymbolTable::StrHash(const char* inName, size_t* outLength) { return Hash(inName, outLength); } PyrSymbol* SymbolTable::Find(const char* inName) { size_t length; int hash = StrHash(inName, &length); return Find(inName, hash); } PyrSymbol* SymbolTable::Find(const char* inName, int inHash) { int index = inHash & mMask; PyrSymbol* sym = mTable[index]; while (sym && (sym->hash != inHash || strcmp(inName, sym->name) != 0)) { index = (index + 1) & mMask; sym = mTable[index]; } return sym; } void SymbolTable::Add(PyrSymbol* inSymbol) { if (mNumItems + 1 > (mMaxItems >> 1)) Grow(); int index = inSymbol->hash & mMask; PyrSymbol* testSymbol = mTable[index]; while (testSymbol && testSymbol != inSymbol) { index = (index + 1) & mMask; testSymbol = mTable[index]; } if (!testSymbol) { // if it is not already in the table. mTable[index] = inSymbol; mNumItems++; } } PyrSymbol* SymbolTable::MakeNew(const char* inName, int inHash, int inLength) { PyrSymbol* symbol = mSpace.NewSymbol(inName, inHash, inLength); Add(symbol); return symbol; } PyrSymbol* SymbolTable::Make(const char* inName) { size_t length; int hash = StrHash(inName, &length); PyrSymbol* symbol = Find(inName, hash); if (!symbol) symbol = MakeNew(inName, hash, length); return symbol; } void SymbolTable::MakeEmpty() { int size = mMaxItems * sizeof(PyrSymbol*); memset(mTable, 0, size); mNumItems = 0; } void SymbolTable::AllocTable() { int size = mMaxItems * sizeof(PyrSymbol*); mTable = (PyrSymbol**)mPool->Alloc(size); MEMFAIL(mTable); MakeEmpty(); mMask = mMaxItems - 1; } void SymbolTable::Rehash(PyrSymbol** inTable, int inSize) { // rehash all entries from inTable into the new table for (int i = 0; i < inSize; ++i) { if (inTable[i]) Add(inTable[i]); } } void SymbolTable::Grow() { PyrSymbol** oldtable = mTable; int oldsize = mMaxItems; // create new table mMaxItems += mMaxItems; AllocTable(); Rehash(oldtable, oldsize); mPool->Free(oldtable); } void SymbolTable::CheckSymbols() { for (int i = 0; i < TableSize(); ++i) { PyrSymbol* symbol = Get(i); if (symbol && symbol->u.index == 0) { int c; c = symbol->name[0]; if (c == '_') { post("WARNING: Primitive '%s' used but not bound\n", symbol->name); } else if (c >= 'A' && c <= 'Z') { post("WARNING: Symbol '%s' used but not defined as a Class\n", symbol->name); } else if ((symbol->flags & sym_Called) && !(symbol->flags & sym_Selector)) { post("WARNING: Method '%s' called but not defined\n", symbol->name); } } } }
5,658
C++
.cpp
162
29.851852
107
0.650439
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
29,854
PyrInterpreter3.cpp
supercollider_supercollider/lang/LangSource/PyrInterpreter3.cpp
/* 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 "Opcodes.h" #include "PyrInterpreter.h" #include "PyrPrimitive.h" #include "PyrPrimitiveProto.h" #include "PyrMathPrim.h" #include "PyrListPrim.h" #include "PyrKernel.h" #include "PyrMessage.h" #include "PyrParseNode.h" #include "PyrSignal.h" #include "PyrSched.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrKernelProto.h" #include "PyrSymbolTable.h" #include <math.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <boost/chrono.hpp> #include <float.h> #define kBigBigFloat DBL_MAX #define kSmallSmallFloat DBL_MIN #include <new> #include "InitAlloc.h" #include "function_attributes.h" #ifdef __clang__ # pragma clang diagnostic ignored "-Warray-bounds" #endif // void tellPlugInsAboutToRun(); double timeNow(); int32 timeseed() { using namespace std::chrono; high_resolution_clock::time_point now = high_resolution_clock::now(); high_resolution_clock::duration since_epoch = now.time_since_epoch(); seconds secs = duration_cast<seconds>(since_epoch); nanoseconds nanosecs = since_epoch - secs; int_least64_t seed = secs.count() ^ nanosecs.count(); return (int32)seed; } VMGlobals gVMGlobals; VMGlobals* gMainVMGlobals = &gVMGlobals; void debugf(char* fmt, ...); #define DEBUGINTERPRETER 0 #define METHODMETER 0 #define BCSTAT 0 #define CHECK_MAX_STACK_USE 0 #if CHECK_MAX_STACK_USE int gMaxStackDepth = 0; #endif unsigned char* dumpOneByteCode(PyrBlock* theBlock, PyrClass* theClass, unsigned char* ip); void dumpSlotOneWord(const char* tagstr, PyrSlot* slot); // bool checkAllObjChecksum(PyrObject* obj); bool gTraceInterpreter = false; // bool gTraceInterpreter = true; const char* byteCodeString(int code); extern int gNumClasses; extern PyrClass* gClassList; // runInterpreter has 7 call sites: // compileLibrary (4) // runLibrary // interpretCmdLine static void endInterpreter(VMGlobals* g); SCLANG_DLLEXPORT_C void runInterpreter(VMGlobals* g, PyrSymbol* selector, int numArgsPushed) { // postfl("->runInterpreter\n"); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif // postfl(" >initInterpreter\n"); if (initInterpreter(g, selector, numArgsPushed)) { #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif // if (strcmp(selector->name, "tick") != 0) post("%s %d execMethod %d\n", selector->name, numArgsPushed, // g->execMethod); // post("->Interpret thread %p\n", g->thread); if (g->execMethod) Interpret(g); // post("<-Interpret thread %p\n", g->thread); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif } // postfl(" >endInterpreter\n"); endInterpreter(g); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif // postfl("<-runInterpreter\n"); // dumpGCStats(g->gc); } static bool initAwakeMessage(VMGlobals* g); void runAwakeMessage(VMGlobals* g) { if (initAwakeMessage(g)) { if (g->execMethod) Interpret(g); } endInterpreter(g); } void initPyrThread(VMGlobals* g, PyrThread* thread, PyrSlot* func, int stacksize, PyrInt32Array* rgenArray, double beats, double seconds, PyrSlot* clock, bool runGC); int32 timeseed(); PyrProcess* newPyrProcess(VMGlobals* g, PyrClass* procclassobj) { PyrGC* gc = g->gc; PyrProcess* proc = (PyrProcess*)instantiateObject(gc, procclassobj, 0, true, false); PyrObject* sysSchedulerQueue = newPyrArray(gc, 4096, 0, false); sysSchedulerQueue->size = 1; SetInt(sysSchedulerQueue->slots + 0, 0); // stability count SetObject(&proc->sysSchedulerQueue, sysSchedulerQueue); PyrObject* classVars = newPyrArray(gc, gNumClassVars, 0, false); classVars->size = gNumClassVars; nilSlots(classVars->slots, gNumClassVars); SetObject(&proc->classVars, classVars); g->classvars = classVars; // fill class vars from prototypes: PyrClass* classobj = gClassList; while (classobj) { if (IsObj(&classobj->cprototype)) { int numClassVars = slotRawObject(&classobj->cprototype)->size; if (numClassVars > 0) { memcpy(g->classvars->slots + slotRawInt(&classobj->classVarIndex), slotRawObject(&classobj->cprototype)->slots, numClassVars * sizeof(PyrSlot)); } } classobj = slotRawClass(&classobj->nextclass); } SetNil(&proc->nowExecutingPath); class_thread = getsym("Thread")->u.classobj; if (class_thread) { SetNil(&proc->curThread); PyrThread* thread = (PyrThread*)instantiateObject(gc, class_thread, 0, true, false); // SetObject(&threadsArray->slots[0], thread); SetObject(&proc->mainThread, thread); PyrInt32Array* rgenArray = newPyrInt32Array(gc, 4, 0, false); rgenArray->size = 4; rgenArray->i[0] = 0; rgenArray->i[1] = 0; rgenArray->i[2] = 0; rgenArray->i[3] = 0; ((RGen*)(rgenArray->i))->init(timeseed()); PyrSlot clockSlot; SetObject(&clockSlot, s_systemclock->u.classobj); initPyrThread(g, thread, &o_nil, EVALSTACKDEPTH, rgenArray, 0., 0., &clockSlot, false); // postfl("elapsedTime %.6f\n", elapsedTime()); } else { error("Class Thread not found.\n"); } PyrSymbol* contextsym = getsym("functionCompileContext"); size_t index = slotRawInt(&class_interpreter->classIndex) + contextsym->u.index; PyrMethod* meth = gRowTable[index]; if (!meth || slotRawSymbol(&meth->name) != contextsym) { error("compile context method 'functionCompileContext' not found.\n"); // SetNil(&proc->interpreter); } else { PyrObject* proto; PyrFrame* frame; PyrMethodRaw* methraw; PyrInterpreter* interpreter = (PyrInterpreter*)instantiateObject(gc, class_interpreter, 0, true, false); SetObject(&proc->interpreter, interpreter); proto = slotRawObject(&meth->prototypeFrame); methraw = METHRAW(meth); frame = (PyrFrame*)gc->New(methraw->frameSize, 0, obj_slot, false); frame->classptr = class_frame; frame->size = FRAMESIZE + proto->size; /// <- IS THIS WRONG ?? SetObject(&frame->method, meth); SetObject(&frame->homeContext, frame); SetInt(&frame->caller, 0); SetNil(&frame->context); SetPtr(&frame->ip, nullptr); SetObject(&frame->vars[0], interpreter); SetObject(&interpreter->context, frame); } return proc; } #if BCSTAT int prevop = 0; int bcstat[256]; int bcpair[256][256]; void clearbcstat(); void clearbcstat() { int i, j; for (i = 0; i < 256; ++i) { bcstat[i] = 0; for (j = 0; j < 256; ++j) { bcpair[i][j] = 0; } } } void dumpbcstat(); void dumpbcstat() { FILE* file; int i, j, k, total; file = fopen("bcstat", "w"); if (file) { fprintf(file, "----------\n"); total = 0; for (i = 0; i < 256; ++i) { total += bcstat[i]; if (bcstat[i]) fprintf(file, "%3d %8d %-32s\n", i, bcstat[i], byteCodeString(i)); } fprintf(file, "\ntotal %d\n", total); fprintf(file, "-----cur,next-----\n"); for (i = 0, k = 0; i < 256; ++i) { for (j = 0; j < 256; j++) { if (bcpair[i][j] > 0) { fprintf(file, "%4d %3d %3d %8d %-32s %-32s\n", k++, i, j, bcpair[i][j], byteCodeString(i), byteCodeString(j)); } } } fprintf(file, "-----cur,prev-----\n"); for (i = 0, k = 0; i < 256; ++i) { for (j = 0; j < 256; j++) { if (bcpair[j][i] > 0) { fprintf(file, "%4d %3d %3d %8d %-32s %-32s\n", k++, i, j, bcpair[j][i], byteCodeString(i), byteCodeString(j)); } } } } fclose(file); } #endif void initPatterns(); void initThreads(); void initGUI(); #ifndef _WIN32 bool running = true; static void handleSigUsr1(int param) { printf("handleSigUsr1()...\n"); running = false; } #endif bool initRuntime(VMGlobals* g, int poolSize, AllocPool* inPool) { /* create a GC environment create a vmachine instance of main initialize VMGlobals */ PyrClass* class_main = s_main->u.classobj; if (!class_main) { error("Class 'Main' not defined.\n"); return false; } if (!isSubclassOf(class_main, class_process)) { error("Class Main is not a subclass of Process.\n"); return false; } // create GC environment, process g->allocPool = inPool; g->gc = (PyrGC*)g->allocPool->Alloc(sizeof(PyrGC)); MEMFAIL(g->gc); new (g->gc) PyrGC(g, g->allocPool, class_main, poolSize); g->thread = slotRawThread(&g->process->mainThread); SetObject(&g->receiver, g->process); // these will be set up when the run method is called g->method = nullptr; g->block = nullptr; g->frame = nullptr; g->ip = nullptr; // initialize process random number generator g->rgen = (RGen*)(slotRawObject(&g->thread->randData)->slots); initThreads(); initPatterns(); initUniqueMethods(); initGUI(); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif // tellPlugInsAboutToRun(); #ifndef _WIN32 signal(SIGUSR1, handleSigUsr1); #endif assert((g->gc->SanityCheck())); #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif return true; } static bool initAwakeMessage(VMGlobals* g) { // post("initAwakeMessage %p %p\n", g->thread, slotRawThread(&g->process->mainThread)); slotCopy(&g->process->curThread, &g->process->mainThread); //?? g->thread = slotRawThread(&g->process->mainThread); //?? // these will be set up when the run method is called g->method = nullptr; g->block = nullptr; g->frame = nullptr; g->ip = nullptr; g->execMethod = 0; // set process as the receiver PyrSlot* slot = g->sp - 3; slotCopy(&g->receiver, slot); SetFloat(&g->thread->beats, slotRawFloat(&slot[1])); SetFloat(&g->thread->seconds, slotRawFloat(&slot[2])); slotCopy(&g->thread->clock, &slot[3]); g->gc->GCWrite(g->thread, slot + 3); // start it sendMessage(g, s_awake, 4, 0); return g->method != nullptr; } bool initInterpreter(VMGlobals* g, PyrSymbol* selector, int numArgsPushed) { slotCopy(&g->process->curThread, &g->process->mainThread); g->thread = slotRawThread(&g->process->mainThread); // these will be set up when the run method is called #if TAILCALLOPTIMIZE g->tailCall = 0; #endif g->method = nullptr; g->block = nullptr; g->frame = nullptr; g->ip = nullptr; g->execMethod = 0; double elapsed = elapsedTime(); SetFloat(&g->thread->beats, elapsed); SetFloat(&g->thread->seconds, elapsed); SetObject(&g->thread->clock, s_systemclock->u.classobj); g->gc->GCWrite(g->thread, s_systemclock->u.classobj); // set process as the receiver PyrSlot* slot = g->sp - numArgsPushed + 1; slotCopy(&g->receiver, slot); // start it sendMessage(g, selector, numArgsPushed, 0); return g->method != nullptr; } static void endInterpreter(VMGlobals* g) { slotCopy(&g->result, g->sp); // dumpObjectSlot(&g->result); g->gc->Stack()->size = 0; g->sp = g->gc->Stack()->slots - 1; g->gc->LazyCollect(); } static void StoreToImmutableA(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip) { // only the value is on the stack slotCopy(sp + 1, sp); // copy value up one slotCopy(sp, &g->receiver); // put receiver in place sp++; g->sp = sp; g->ip = ip; post("StoreToImmutableA\n"); dumpObjectSlot(sp - 1); dumpObjectSlot(sp); sendMessage(g, getsym("immutableError"), 2, 0); sp = g->sp; ip = g->ip; } void StoreToImmutableB(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip) { // receiver and value are on the stack. sp++; g->sp = sp; g->ip = ip; post("StoreToImmutableB\n"); dumpObjectSlot(sp - 1); dumpObjectSlot(sp); PyrSymbol* selector = getsym("immutableError"); sendMessage(g, selector, 2, 0); sp = g->sp; ip = g->ip; } void dumpByteCodes(PyrBlock* theBlock); static inline void handlePushClassVar(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip, unsigned char op2) { unsigned char op3 = ip[1]; ++ip; // get class var index slotCopy(++sp, &g->classvars->slots[(op2 << 8) | op3]); } static inline void handleStoreInstVar(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip, unsigned int index) { PyrObject* obj = slotRawObject(&g->receiver); if (obj->IsImmutable()) StoreToImmutableA(g, sp, ip); else { PyrSlot* slot = obj->slots + index; slotCopy(slot, sp--); g->gc->GCWrite(obj, slot); } } static inline void handleSendSpecialUnaryArithMsg(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip, unsigned char op1) { g->sp = sp; g->ip = ip; g->primitiveIndex = op1 & 15; doSpecialUnaryArithMsg(g, -1); sp = g->sp; ip = g->ip; } static inline void handleSendSpecialBinaryArithMsg(VMGlobals* g, PyrSlot*& sp, unsigned char*& ip, unsigned char op1) { g->sp = sp; g->ip = ip; g->primitiveIndex = op1 & 15; doSpecialBinaryArithMsg(g, 2, false); sp = g->sp; ip = g->ip; } static inline bool checkStackOverflow(VMGlobals* g, PyrSlot* sp) { PyrObject* stack = g->gc->Stack(); int depth = sp - stack->slots; return depth < slotRawInt(&g->thread->stackSize); } static inline void checkStackDepth(VMGlobals* g, PyrSlot* sp) { #if CHECK_MAX_STACK_USE int stackDepth = sp - g->sp + 1; if (stackDepth > gMaxStackDepth) { gMaxStackDepth = stackDepth; printf("gMaxStackDepth %d\n", gMaxStackDepth); } #endif } #if defined(__GNUC__) || defined(__INTEL_COMPILER) # define LABELS_AS_VALUES #endif #ifdef LABELS_AS_VALUES # define dispatch_opcode \ op1 = ip[1]; \ ++ip; \ checkStackDepth(g, sp); \ assert(checkStackOverflow(g, sp)); \ goto* opcode_labels[op1] #else # define dispatch_opcode break #endif #if defined(__GNUC__) # define LIKELY(x) __builtin_expect((x), 1) # define UNLIKELY(x) __builtin_expect((x), 0) #else # define LIKELY(x) x # define UNLIKELY(x) x #endif #if defined(__GNUC__) && !defined(__clang__) // gcc manual: // Note: When compiling a program using computed gotos, a GCC extension, you may get better run-time performance if // you disable the global common subexpression elimination pass by adding -fno-gcse to the command line. # pragma GCC push_options # pragma GCC optimize("-fno-gcse") #endif HOT void Interpret(VMGlobals* g) { // byte code values unsigned char* ip; unsigned char op1; // interpreter globals int numArgsPushed, numKeyArgsPushed; PyrSymbol* selector; PyrClass* classobj; // temporary variables used in the interpreter PyrSlot* slot; PyrSlot* sp; #ifdef LABELS_AS_VALUES static void* opcode_labels[] = { &&handle_op_0, &&handle_op_1, &&handle_op_2, &&handle_op_3, &&handle_op_4, &&handle_op_5, &&handle_op_6, &&handle_op_7, &&handle_op_8, &&handle_op_9, &&handle_op_10, &&handle_op_11, &&handle_op_12, &&handle_op_13, &&handle_op_14, &&handle_op_15, &&handle_op_16, &&handle_op_17, &&handle_op_18, &&handle_op_19, &&handle_op_20, &&handle_op_21, &&handle_op_22, &&handle_op_23, &&handle_op_24, &&handle_op_25, &&handle_op_26, &&handle_op_27, &&handle_op_28, &&handle_op_29, &&handle_op_30, &&handle_op_31, &&handle_op_32, &&handle_op_33, &&handle_op_34, &&handle_op_35, &&handle_op_36, &&handle_op_37, &&handle_op_38, &&handle_op_39, &&handle_op_40, &&handle_op_41, &&handle_op_42, &&handle_op_43, &&handle_op_44, &&handle_op_45, &&handle_op_46, &&handle_op_47, &&handle_op_48, &&handle_op_49, &&handle_op_50, &&handle_op_51, &&handle_op_52, &&handle_op_53, &&handle_op_54, &&handle_op_55, &&handle_op_56, &&handle_op_57, &&handle_op_58, &&handle_op_59, &&handle_op_60, &&handle_op_61, &&handle_op_62, &&handle_op_63, &&handle_op_64, &&handle_op_65, &&handle_op_66, &&handle_op_67, &&handle_op_68, &&handle_op_69, &&handle_op_70, &&handle_op_71, &&handle_op_72, &&handle_op_73, &&handle_op_74, &&handle_op_75, &&handle_op_76, &&handle_op_77, &&handle_op_78, &&handle_op_79, &&handle_op_80, &&handle_op_81, &&handle_op_82, &&handle_op_83, &&handle_op_84, &&handle_op_85, &&handle_op_86, &&handle_op_87, &&handle_op_88, &&handle_op_89, &&handle_op_90, &&handle_op_91, &&handle_op_92, &&handle_op_93, &&handle_op_94, &&handle_op_95, &&handle_op_96, &&handle_op_97, &&handle_op_98, &&handle_op_99, &&handle_op_100, &&handle_op_101, &&handle_op_102, &&handle_op_103, &&handle_op_104, &&handle_op_105, &&handle_op_106, &&handle_op_107, &&handle_op_108, &&handle_op_109, &&handle_op_110, &&handle_op_111, &&handle_op_112, &&handle_op_113, &&handle_op_114, &&handle_op_115, &&handle_op_116, &&handle_op_117, &&handle_op_118, &&handle_op_119, &&handle_op_120, &&handle_op_121, &&handle_op_122, &&handle_op_123, &&handle_op_124, &&handle_op_125, &&handle_op_126, &&handle_op_127, &&handle_op_128, &&handle_op_129, &&handle_op_130, &&handle_op_131, &&handle_op_132, &&handle_op_133, &&handle_op_134, &&handle_op_135, &&handle_op_136, &&handle_op_137, &&handle_op_138, &&handle_op_139, &&handle_op_140, &&handle_op_141, &&handle_op_142, &&handle_op_143, &&handle_op_144, &&handle_op_145, &&handle_op_146, &&handle_op_147, &&handle_op_148, &&handle_op_149, &&handle_op_150, &&handle_op_151, &&handle_op_152, &&handle_op_153, &&handle_op_154, &&handle_op_155, &&handle_op_156, &&handle_op_157, &&handle_op_158, &&handle_op_159, &&handle_op_160, &&handle_op_161, &&handle_op_162, &&handle_op_163, &&handle_op_164, &&handle_op_165, &&handle_op_166, &&handle_op_167, &&handle_op_168, &&handle_op_169, &&handle_op_170, &&handle_op_171, &&handle_op_172, &&handle_op_173, &&handle_op_174, &&handle_op_175, &&handle_op_176, &&handle_op_177, &&handle_op_178, &&handle_op_179, &&handle_op_180, &&handle_op_181, &&handle_op_182, &&handle_op_183, &&handle_op_184, &&handle_op_185, &&handle_op_186, &&handle_op_187, &&handle_op_188, &&handle_op_189, &&handle_op_190, &&handle_op_191, &&handle_op_192, &&handle_op_193, &&handle_op_194, &&handle_op_195, &&handle_op_196, &&handle_op_197, &&handle_op_198, &&handle_op_199, &&handle_op_200, &&handle_op_201, &&handle_op_202, &&handle_op_203, &&handle_op_204, &&handle_op_205, &&handle_op_206, &&handle_op_207, &&handle_op_208, &&handle_op_209, &&handle_op_210, &&handle_op_211, &&handle_op_212, &&handle_op_213, &&handle_op_214, &&handle_op_215, &&handle_op_216, &&handle_op_217, &&handle_op_218, &&handle_op_219, &&handle_op_220, &&handle_op_221, &&handle_op_222, &&handle_op_223, &&handle_op_224, &&handle_op_225, &&handle_op_226, &&handle_op_227, &&handle_op_228, &&handle_op_229, &&handle_op_230, &&handle_op_231, &&handle_op_232, &&handle_op_233, &&handle_op_234, &&handle_op_235, &&handle_op_236, &&handle_op_237, &&handle_op_238, &&handle_op_239, &&handle_op_240, &&handle_op_241, &&handle_op_242, &&handle_op_243, &&handle_op_244, &&handle_op_245, &&handle_op_246, &&handle_op_247, &&handle_op_248, &&handle_op_249, &&handle_op_250, &&handle_op_251, &&handle_op_252, &&handle_op_253, &&handle_op_254, &&handle_op_255 }; #endif #if 0 unsigned char *bzero; PyrSlot *szero; char str[80]; #endif #if BCSTAT // clearbcstat(); op1 = 0; prevop = 0; #endif #if 0 bzero = g->ip; szero = g->sp; //SetSymbol(g->sp, getsym("STACK TOP")); // just for debugging //g->sp++; // just for debugging #endif // Codewarrior puts them in registers. take advantage.. sp = g->sp; ip = g->ip; numKeyArgsPushed = 0; if (setjmp(g->escapeInterpreter) != 0) { return; } #ifndef _WIN32 while (running) { // not going to indent body to save line space #else while (true) { #endif checkStackDepth(g, sp); #if BCSTAT prevop = op1; #endif op1 = ip[1]; ++ip; assert(checkStackOverflow(g, sp)); #if BCSTAT ++bcstat[op1]; ++bcpair[prevop][op1]; prevop = op1; #endif // printf("op1 %d\n", op1); // postfl("sp %p frame %p caller %p ip %p\n", sp, g->frame, g->frame->caller.uof, // slotRawInt(&g->frame->caller.uof->ip)); postfl("sp %p frame %p diff %d caller %p\n", sp, g->frame, // ((int)sp - (int)g->frame)>>3, g->frame->caller.uof); #if DEBUGINTERPRETER if (gTraceInterpreter) { // DumpStack(g, sp); if (FrameSanity(g->frame, "dbgint")) { // Debugger(); } // g->gc->SanityCheck(); // assert(g->gc->SanityCheck()); g->sp = sp; g->ip = ip; g->gc->FullCollection(); sp = g->sp; ip = g->ip; postfl("[%3d] %20s-%-16s ", (sp - g->gc->Stack()->slots) + 1, slotRawSymbol(&slotRawClass(&g->method->ownerclass)->name)->name, slotRawSymbol(&g->method->name)->name); dumpOneByteCode(g->block, NULL, ip); } #endif #ifdef GC_SANITYCHECK // gcLinkSanity(g->gc); g->gc->SanityCheck(); // do_check_pool(pyr_pool_runtime); // do_check_pool(pyr_pool_compile); #endif #if METHODMETER if (gTraceInterpreter) { slotRawInt(&g->method->byteMeter)++; } #endif switch (op1) { case 0: // push class handle_op_0 : { int op2 = ip[1]; ++ip; // get literal index classobj = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2])->u.classobj; if (classobj) { ++sp; SetObject(sp, classobj); } else { postfl("Execution warning: Class '%s' not found\n", slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2])->name); slotCopy(++sp, &gSpecialValues[svNil]); } dispatch_opcode; } case 1: // opExtended, opPushInstVar handle_op_1 : { int op2 = ip[1]; ++ip; // get inst var index slotCopy(++sp, &slotRawObject(&g->receiver)->slots[op2]); dispatch_opcode; } case 2: // opExtended, opPushTempVar handle_op_2 : { int op2 = ip[1]; // get temp var level int op3 = ip[2]; // get temp var index ip += 2; PyrFrame* tframe = g->frame; for (; op2--; tframe = slotRawFrame(&tframe->context)) { /* noop */ } slotCopy(++sp, &tframe->vars[op3]); dispatch_opcode; } case 3: // opExtended, opPushTempZeroVar handle_op_3 : { int op2 = ip[1]; ++ip; // get temp var index slotCopy(++sp, &g->frame->vars[op2]); dispatch_opcode; } case 4: // opExtended, opPushLiteral handle_op_4 : { int op2 = ip[1]; ++ip; // get literal index // push a block as a closure if it is one slot = slotRawObject(&g->block->selectors)->slots + op2; if (IsObj(slot) && slotRawObject(slot)->classptr == gSpecialClasses[op_class_fundef]->u.classobj) { // push a closure g->sp = sp; // gc may push the stack PyrClosure* closure = (PyrClosure*)g->gc->New(2 * sizeof(PyrSlot), 0, obj_notindexed, true); sp = g->sp; closure->classptr = gSpecialClasses[op_class_func]->u.classobj; closure->size = 2; slotCopy(&closure->block, slot); if (IsNil(&slotRawBlock(slot)->contextDef)) { slotCopy(&closure->context, &slotRawInterpreter(&g->process->interpreter)->context); } else { SetObject(&closure->context, g->frame); } ++sp; SetObject(sp, closure); } else { slotCopy(++sp, slot); } dispatch_opcode; } case 5: // opExtended, opPushClassVar handle_op_5 : { int op2 = ip[1]; // get class int op3 = ip[2]; // get class var index ip += 2; slotCopy(++sp, &g->classvars->slots[(op2 << 8) | op3]); dispatch_opcode; } case 6: // opExtended, opPushSpecialValue == push a special class handle_op_6 : { int op2 = ip[1]; ++ip; // get class name index classobj = gSpecialClasses[op2]->u.classobj; if (classobj) { ++sp; SetObject(sp, classobj); } else { slotCopy(++sp, &gSpecialValues[svNil]); } dispatch_opcode; } case 7: // opExtended, opStoreInstVar handle_op_7 : { int op2 = ip[1]; ++ip; // get inst var index PyrObject* obj = slotRawObject(&g->receiver); if (obj->IsImmutable()) { StoreToImmutableA(g, sp, ip); } else { slot = obj->slots + op2; slotCopy(slot, sp); g->gc->GCWrite(obj, slot); } dispatch_opcode; } case 8: // opExtended, opStoreTempVar handle_op_8 : { int op2 = ip[1]; // get temp var level int op3 = ip[2]; // get temp var index ip += 2; PyrFrame* tframe = g->frame; for (; op2--; tframe = slotRawFrame(&tframe->context)) { /* noop */ } slot = tframe->vars + op3; slotCopy(slot, sp); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 9: // opExtended, opStoreClassVar handle_op_9 : { int op2 = ip[1]; // get index of class name literal int op3 = ip[2]; // get class var index ip += 2; slotCopy(&g->classvars->slots[(op2 << 8) | op3], sp); g->gc->GCWrite(g->classvars, sp); dispatch_opcode; } case 10: // opExtended, opSendMsg handle_op_10 : { numArgsPushed = ip[1]; // get num args numKeyArgsPushed = ip[2]; // get num keyword args int op3 = ip[3]; // get selector index ip += 3; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op3]); slot = sp - numArgsPushed + 1; if (numKeyArgsPushed) goto key_class_lookup; else goto class_lookup; } case 11: // opExtended, opSendSuper handle_op_11 : { numArgsPushed = ip[1]; // get num args numKeyArgsPushed = ip[2]; // get num keyword args int op3 = ip[3]; // get selector index ip += 3; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op3]); slot = g->sp - numArgsPushed + 1; classobj = slotRawSymbol(&slotRawClass(&g->method->ownerclass)->superclass)->u.classobj; if (numKeyArgsPushed) goto key_msg_lookup; else goto msg_lookup; } case 12: // opExtended, opSendSpecialMsg handle_op_12 : { numArgsPushed = ip[1]; // get num args numKeyArgsPushed = ip[2]; // get num keyword args int op3 = ip[3]; // get selector index ip += 3; selector = gSpecialSelectors[op3]; slot = sp - numArgsPushed + 1; if (numKeyArgsPushed) goto key_class_lookup; else goto class_lookup; } case 13: // opExtended, opSendSpecialUnaryArithMsg handle_op_13 : { int op2 = ip[1]; ++ip; // get selector index g->sp = sp; g->ip = ip; g->primitiveIndex = op2; doSpecialUnaryArithMsg(g, -1); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif sp = g->sp; ip = g->ip; dispatch_opcode; } case 14: // opExtended, opSendSpecialBinaryArithMsg handle_op_14 : { int op2 = ip[1]; ++ip; // get selector index g->sp = sp; g->ip = ip; g->primitiveIndex = op2; doSpecialBinaryArithMsg(g, 2, false); sp = g->sp; ip = g->ip; dispatch_opcode; } case 15: // opExtended, opSpecialOpcode (none yet) handle_op_15 : { int op2 = ip[1]; ++ip; // get extended special opcode switch (op2) { case opgProcess: // push thisProcess ++sp; SetObject(sp, g->process); break; case opgThread: // push thisProcess ++sp; SetObject(sp, g->thread); break; case opgMethod: // push thisMethod ++sp; SetObject(sp, g->method); break; case opgFunctionDef: // push thisFunctionDef ++sp; SetObject(sp, g->block); break; case opgFunction: { // push thisFunc // push a closure g->sp = sp; // gc may push the stack PyrClosure* closure = (PyrClosure*)g->gc->New(2 * sizeof(PyrSlot), 0, obj_notindexed, true); sp = g->sp; closure->classptr = gSpecialClasses[op_class_func]->u.classobj; closure->size = 2; SetObject(&closure->block, g->block); SetObject(&closure->context, slotRawFrame(&g->frame->context)); ++sp; SetObject(sp, closure); break; } default: slotCopy(++sp, &gSpecialValues[svNil]); break; } dispatch_opcode; } // opPushInstVar, 0..15 case 16: handle_op_16: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[0]); dispatch_opcode; case 17: handle_op_17: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[1]); dispatch_opcode; case 18: handle_op_18: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[2]); dispatch_opcode; case 19: handle_op_19: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[3]); dispatch_opcode; case 20: handle_op_20: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[4]); dispatch_opcode; case 21: handle_op_21: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[5]); dispatch_opcode; case 22: handle_op_22: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[6]); dispatch_opcode; case 23: handle_op_23: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[7]); dispatch_opcode; case 24: handle_op_24: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[8]); dispatch_opcode; case 25: handle_op_25: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[9]); dispatch_opcode; case 26: handle_op_26: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[10]); dispatch_opcode; case 27: handle_op_27: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[11]); dispatch_opcode; case 28: handle_op_28: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[12]); dispatch_opcode; case 29: handle_op_29: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[13]); dispatch_opcode; case 30: handle_op_30: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[14]); dispatch_opcode; case 31: handle_op_31: slotCopy(++sp, &slotRawObject(&g->receiver)->slots[15]); dispatch_opcode; case 32: // JumpIfTrue handle_op_32: // cannot compare with o_false because it is NaN if (IsTrue(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else if (IsFalse(sp)) { ip += 2; } else { numArgsPushed = 1; selector = gSpecialSelectors[opmNonBooleanError]; slot = sp; goto class_lookup; } --sp; dispatch_opcode; // opPushTempVar, levels 1..7 case 33: handle_op_33: slotCopy(++sp, &slotRawFrame(&g->frame->context)->vars[ip[1]]); ++ip; dispatch_opcode; case 34: handle_op_34: slotCopy(++sp, &slotRawFrame(&slotRawFrame(&g->frame->context)->context)->vars[ip[1]]); ++ip; dispatch_opcode; case 35: handle_op_35: slotCopy(++sp, &slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context)->vars[ip[1]]); ++ip; dispatch_opcode; case 36: handle_op_36: slotCopy(++sp, &slotRawFrame( &slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context)->context) ->vars[ip[1]]); ++ip; dispatch_opcode; case 37: handle_op_37: slotCopy( ++sp, &slotRawFrame( &slotRawFrame( &slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context)->context) ->context) ->vars[ip[1]]); ++ip; dispatch_opcode; case 38: handle_op_38: slotCopy(++sp, &slotRawFrame( &slotRawFrame( &slotRawFrame( &slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context) ->context) ->context) ->context) ->vars[ip[1]]); ++ip; dispatch_opcode; case 39: handle_op_39: slotCopy( ++sp, &slotRawFrame( &slotRawFrame( &slotRawFrame( &slotRawFrame( &slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context) ->context) ->context) ->context) ->context) ->vars[ip[1]]); ++ip; dispatch_opcode; // push literal constants. case 40: handle_op_40 : { int ival = ip[1]; ip += 1; slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[ival]); dispatch_opcode; } case 41: handle_op_41 : { int ival = (ip[1] << 8) | ip[2]; ip += 2; slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[ival]); dispatch_opcode; } case 42: handle_op_42 : { int ival = (ip[1] << 16) | (ip[2] << 8) | ip[3]; ip += 3; slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[ival]); dispatch_opcode; } case 43: handle_op_43 : { int ival = (ip[1] << 24) | (ip[2] << 16) | (ip[3] << 8) | ip[4]; ip += 4; slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[ival]); dispatch_opcode; } // push integers. case 44: handle_op_44 : { int ival = (int32)(ip[1] << 24) >> 24; ip += 1; ++sp; SetInt(sp, ival); dispatch_opcode; } case 45: handle_op_45 : { int ival = (int32)((ip[1] << 24) | (ip[2] << 16)) >> 16; ip += 2; ++sp; SetInt(sp, ival); dispatch_opcode; } case 46: handle_op_46 : { int ival = (int32)((ip[1] << 24) | (ip[2] << 16) | (ip[3] << 8)) >> 8; ip += 3; ++sp; SetInt(sp, ival); dispatch_opcode; } case 47: handle_op_47 : { int ival = (int32)((ip[1] << 24) | (ip[2] << 16) | (ip[3] << 8) | ip[4]); ip += 4; ++sp; SetInt(sp, ival); dispatch_opcode; } // opPushTempZeroVar case 48: handle_op_48: slotCopy(++sp, &g->frame->vars[0]); dispatch_opcode; case 49: handle_op_49: slotCopy(++sp, &g->frame->vars[1]); dispatch_opcode; case 50: handle_op_50: slotCopy(++sp, &g->frame->vars[2]); dispatch_opcode; case 51: handle_op_51: slotCopy(++sp, &g->frame->vars[3]); dispatch_opcode; case 52: handle_op_52: slotCopy(++sp, &g->frame->vars[4]); dispatch_opcode; case 53: handle_op_53: slotCopy(++sp, &g->frame->vars[5]); dispatch_opcode; case 54: handle_op_54: slotCopy(++sp, &g->frame->vars[6]); dispatch_opcode; case 55: handle_op_55: slotCopy(++sp, &g->frame->vars[7]); dispatch_opcode; case 56: handle_op_56: slotCopy(++sp, &g->frame->vars[8]); dispatch_opcode; case 57: handle_op_57: slotCopy(++sp, &g->frame->vars[9]); dispatch_opcode; case 58: handle_op_58: slotCopy(++sp, &g->frame->vars[10]); dispatch_opcode; case 59: handle_op_59: slotCopy(++sp, &g->frame->vars[11]); dispatch_opcode; case 60: handle_op_60: slotCopy(++sp, &g->frame->vars[12]); dispatch_opcode; case 61: handle_op_61: slotCopy(++sp, &g->frame->vars[13]); dispatch_opcode; case 62: handle_op_62: slotCopy(++sp, &g->frame->vars[14]); dispatch_opcode; case 63: handle_op_63: slotCopy(++sp, &g->frame->vars[15]); dispatch_opcode; // case opPushLiteral case 64: handle_op_64: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[0]); dispatch_opcode; case 65: handle_op_65: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[1]); dispatch_opcode; case 66: handle_op_66: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[2]); dispatch_opcode; case 67: handle_op_67: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[3]); dispatch_opcode; case 68: handle_op_68: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[4]); dispatch_opcode; case 69: handle_op_69: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[5]); dispatch_opcode; case 70: handle_op_70: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[6]); dispatch_opcode; case 71: handle_op_71: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[7]); dispatch_opcode; case 72: handle_op_72: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[8]); dispatch_opcode; case 73: handle_op_73: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[9]); dispatch_opcode; case 74: handle_op_74: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[10]); dispatch_opcode; case 75: handle_op_75: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[11]); dispatch_opcode; case 76: handle_op_76: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[12]); dispatch_opcode; case 77: handle_op_77: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[13]); dispatch_opcode; case 78: handle_op_78: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[14]); dispatch_opcode; case 79: handle_op_79: slotCopy(++sp, &slotRawObject(&g->block->constants)->slots[15]); dispatch_opcode; // opPushClassVar case 80: handle_op_80: handlePushClassVar(g, sp, ip, 0); dispatch_opcode; case 81: handle_op_81: handlePushClassVar(g, sp, ip, 1); dispatch_opcode; case 82: handle_op_82: handlePushClassVar(g, sp, ip, 2); dispatch_opcode; case 83: handle_op_83: handlePushClassVar(g, sp, ip, 3); dispatch_opcode; case 84: handle_op_84: handlePushClassVar(g, sp, ip, 4); dispatch_opcode; case 85: handle_op_85: handlePushClassVar(g, sp, ip, 5); dispatch_opcode; case 86: handle_op_86: handlePushClassVar(g, sp, ip, 6); dispatch_opcode; case 87: handle_op_87: handlePushClassVar(g, sp, ip, 7); dispatch_opcode; case 88: handle_op_88: handlePushClassVar(g, sp, ip, 8); dispatch_opcode; case 89: handle_op_89: handlePushClassVar(g, sp, ip, 9); dispatch_opcode; case 90: handle_op_90: handlePushClassVar(g, sp, ip, 10); dispatch_opcode; case 91: handle_op_91: handlePushClassVar(g, sp, ip, 11); dispatch_opcode; case 92: handle_op_92: handlePushClassVar(g, sp, ip, 12); dispatch_opcode; case 93: handle_op_93: handlePushClassVar(g, sp, ip, 13); dispatch_opcode; case 94: handle_op_94: handlePushClassVar(g, sp, ip, 14); dispatch_opcode; case 95: handle_op_95: handlePushClassVar(g, sp, ip, 15); dispatch_opcode; // opPushSpecialValue case 96: handle_op_96: slotCopy(++sp, &g->receiver); dispatch_opcode; case 97: // push one and subtract handle_op_97: if (IsInt(sp)) { SetRaw(sp, slotRawInt(sp) - 1); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else { slotCopy(++sp, &gSpecialValues[svOne]); g->sp = sp; g->ip = ip; g->primitiveIndex = opSub; prSubNum(g, -1); sp = g->sp; ip = g->ip; } dispatch_opcode; case 98: handle_op_98: slotCopy(++sp, &gSpecialValues[svNegOne]); dispatch_opcode; case 99: handle_op_99: slotCopy(++sp, &gSpecialValues[svZero]); dispatch_opcode; case 100: handle_op_100: slotCopy(++sp, &gSpecialValues[svOne]); dispatch_opcode; case 101: handle_op_101: slotCopy(++sp, &gSpecialValues[svTwo]); dispatch_opcode; case 102: handle_op_102: slotCopy(++sp, &gSpecialValues[svFHalf]); dispatch_opcode; case 103: handle_op_103: slotCopy(++sp, &gSpecialValues[svFNegOne]); dispatch_opcode; case 104: handle_op_104: slotCopy(++sp, &gSpecialValues[svFZero]); dispatch_opcode; case 105: handle_op_105: slotCopy(++sp, &gSpecialValues[svFOne]); dispatch_opcode; case 106: handle_op_106: slotCopy(++sp, &gSpecialValues[svFTwo]); dispatch_opcode; case 107: // push one and add handle_op_107: if (IsInt(sp)) { SetRaw(sp, slotRawInt(sp) + 1); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else { slotCopy(++sp, &gSpecialValues[svOne]); g->sp = sp; g->ip = ip; g->primitiveIndex = opAdd; prAddNum(g, -1); sp = g->sp; ip = g->ip; } dispatch_opcode; case 108: handle_op_108: slotCopy(++sp, &gSpecialValues[svTrue]); dispatch_opcode; case 109: handle_op_109: slotCopy(++sp, &gSpecialValues[svFalse]); dispatch_opcode; case 110: handle_op_110: slotCopy(++sp, &gSpecialValues[svNil]); dispatch_opcode; case 111: handle_op_111: slotCopy(++sp, &gSpecialValues[svInf]); dispatch_opcode; // opStoreInstVar, 0..15 case 112: handle_op_112: handleStoreInstVar(g, sp, ip, 0); dispatch_opcode; case 113: handle_op_113: handleStoreInstVar(g, sp, ip, 1); dispatch_opcode; case 114: handle_op_114: handleStoreInstVar(g, sp, ip, 2); dispatch_opcode; case 115: handle_op_115: handleStoreInstVar(g, sp, ip, 3); dispatch_opcode; case 116: handle_op_116: handleStoreInstVar(g, sp, ip, 4); dispatch_opcode; case 117: handle_op_117: handleStoreInstVar(g, sp, ip, 5); dispatch_opcode; case 118: handle_op_118: handleStoreInstVar(g, sp, ip, 6); dispatch_opcode; case 119: handle_op_119: handleStoreInstVar(g, sp, ip, 7); dispatch_opcode; case 120: handle_op_120: handleStoreInstVar(g, sp, ip, 8); dispatch_opcode; case 121: handle_op_121: handleStoreInstVar(g, sp, ip, 9); dispatch_opcode; case 122: handle_op_122: handleStoreInstVar(g, sp, ip, 10); dispatch_opcode; case 123: handle_op_123: handleStoreInstVar(g, sp, ip, 11); dispatch_opcode; case 124: handle_op_124: handleStoreInstVar(g, sp, ip, 12); dispatch_opcode; case 125: handle_op_125: handleStoreInstVar(g, sp, ip, 13); dispatch_opcode; case 126: handle_op_126: handleStoreInstVar(g, sp, ip, 14); dispatch_opcode; case 127: handle_op_127: handleStoreInstVar(g, sp, ip, 15); dispatch_opcode; // opStoreTempVar case 128: handle_op_128 : { int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = g->frame; // zero level slot = tframe->vars + op3; slotCopy(slot, sp--); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 129: handle_op_129 : { int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = slotRawFrame(&g->frame->context); // one level slot = tframe->vars + op3; slotCopy(slot, sp--); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 130: handle_op_130 : { int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = slotRawFrame(&slotRawFrame(&g->frame->context)->context); // two levels slot = tframe->vars + op3; slotCopy(slot, sp--); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 131: handle_op_131 : { int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context); // three levels slot = tframe->vars + op3; slotCopy(slot, sp--); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 132: handle_op_132 : { int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = slotRawFrame(&slotRawFrame(&slotRawFrame(&slotRawFrame(&g->frame->context)->context)->context) ->context); // four levels slot = tframe->vars + op3; slotCopy(slot, sp--); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 133: case 134: case 135: handle_op_133: handle_op_134: handle_op_135 : { int op2 = op1 & 15; int op3 = ip[1]; ++ip; // get temp var index PyrFrame* tframe = g->frame; for (; op2--; tframe = slotRawFrame(&tframe->context)) { /* noop */ } slot = tframe->vars + op3; slotCopy(slot, sp); g->gc->GCWrite(tframe, slot); dispatch_opcode; } case 136: // push inst var, send special selector handle_op_136 : { int op2 = ip[1]; // get inst var index int op3 = ip[2]; // get selector ip += 2; slotCopy(++sp, &slotRawObject(&g->receiver)->slots[op2]); numArgsPushed = 1; selector = gSpecialSelectors[op3]; slot = sp; goto class_lookup; } case 137: // push all args, send msg handle_op_137 : { numArgsPushed = METHRAW(g->block)->numargs; PyrSlot* pslot = g->frame->vars - 1; for (int m = 0; m < numArgsPushed; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector index selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp - numArgsPushed + 1; goto class_lookup; } case 138: // push all but first arg, send msg handle_op_138 : { numArgsPushed = METHRAW(g->block)->numargs; PyrSlot* pslot = g->frame->vars; for (int m = 0; m < numArgsPushed - 1; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector index selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp - numArgsPushed + 1; goto class_lookup; } case 139: // push all args, send special handle_op_139 : { numArgsPushed = METHRAW(g->block)->numargs; PyrSlot* pslot = g->frame->vars - 1; for (int m = 0; m < numArgsPushed; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector selector = gSpecialSelectors[op2]; slot = sp - numArgsPushed + 1; goto class_lookup; } case 140: // push all but first arg, send special handle_op_140 : { numArgsPushed = METHRAW(g->block)->numargs; PyrSlot* pslot = g->frame->vars; for (int m = 0; m < numArgsPushed - 1; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector selector = gSpecialSelectors[op2]; slot = sp - numArgsPushed + 1; goto class_lookup; } case 141: // one arg pushed, push all but first arg, send msg handle_op_141 : { numArgsPushed = METHRAW(g->block)->numargs + 1; PyrSlot* pslot = g->frame->vars; for (int m = 0; m < numArgsPushed - 2; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector index selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp - numArgsPushed + 1; goto class_lookup; } case 142: // one arg pushed, push all but first arg, send special handle_op_142 : { numArgsPushed = METHRAW(g->block)->numargs + 1; PyrSlot* pslot = g->frame->vars; for (int m = 0; m < numArgsPushed - 2; ++m) *++sp = *++pslot; int op2 = ip[1]; ++ip; // get selector selector = gSpecialSelectors[op2]; slot = sp - numArgsPushed + 1; goto class_lookup; } case 143: // loop byte codes handle_op_143 : { // this is major cheating to speed up often used looping methods // these byte codes are specific to their method and should only be used there. int op2 = ip[1]; ++ip; // get which one switch (op2) { // Integer-do : 143 0, 143 1 case 0: { PyrSlot* vars = g->frame->vars; if (slotRawInt(&vars[2]) < slotRawInt(&g->receiver)) { slotCopy(++sp, &vars[1]); // push function slotCopy(++sp, &vars[2]); // push i slotCopy(++sp, &vars[2]); // push i // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 1: --sp; // Drop SetRaw(&g->frame->vars[2], slotRawInt(&g->frame->vars[2]) + 1); // inc i ip -= 4; dispatch_opcode; // Integer-reverseDo : 143 2, 143 3, 143 4 case 2: SetRaw(&g->frame->vars[2], slotRawInt(&g->receiver) - 1); dispatch_opcode; case 3: { PyrSlot* vars = g->frame->vars; if (slotRawInt(&vars[2]) >= 0) { slotCopy(++sp, &vars[1]); // push function slotCopy(++sp, &vars[2]); // push i slotCopy(++sp, &vars[3]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 4: { --sp; // Drop PyrSlot* vars = g->frame->vars; SetRaw(&vars[2], slotRawInt(&vars[2]) - 1); // dec i SetRaw(&vars[3], slotRawInt(&vars[3]) + 1); // inc j ip -= 4; dispatch_opcode; } // Integer-for : 143 5, 143 6, 143 16 case 5: { PyrSlot* vars = g->frame->vars; int tag = GetTag(&vars[1]); if (tag != tagInt) { if (IsFloat(&vars[1])) { // coerce to int SetInt(&vars[1], (int32)(slotRawFloat(&vars[1]))); } else { error("Integer-for : endval not a SimpleNumber.\n"); slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = gSpecialSelectors[opmPrimitiveFailed]; slot = sp; goto class_lookup; } } if (slotRawInt(&g->receiver) <= slotRawInt(&vars[1])) { SetRaw(&vars[5], 1); } else { SetRaw(&vars[5], -1); } slotCopy(&vars[3], &g->receiver); dispatch_opcode; } case 6: { PyrSlot* vars = g->frame->vars; if ((slotRawInt(&vars[5]) > 0 && slotRawInt(&vars[3]) <= slotRawInt(&vars[1])) || (slotRawInt(&vars[5]) < 0 && slotRawInt(&vars[3]) >= slotRawInt(&vars[1]))) { slotCopy(++sp, &vars[2]); // push function slotCopy(++sp, &vars[3]); // push i slotCopy(++sp, &vars[4]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } // Integer-forBy : 143 7, 143 8, 143 9 case 7: { PyrSlot* vars = g->frame->vars; // Detect case of a zero-valued stepval argument, which // would result in an infinite loop. if ((IsFloat(vars + 2) && slotRawFloat(&vars[2]) == 0.0) || (IsInt(vars + 2) && slotRawInt(&vars[2]) == 0)) { error("Integer-forBy: zero-valued stepval argument.\n"); slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = gSpecialSelectors[opmPrimitiveFailed]; slot = sp; goto class_lookup; } // If any argument is floating point we cast all arguments // to floating point, including the accumulator. This avoids // potential infinite loops due to integer truncation. if (IsFloat(vars + 1) || IsFloat(vars + 2)) { if (IsInt(vars + 1)) { SetFloat(&vars[1], (double)(slotRawInt(&vars[1]))); } if (IsInt(vars + 2)) { SetFloat(&vars[2], (double)(slotRawInt(&vars[2]))); } SetFloat(&vars[4], (double)(slotRawInt(&g->receiver))); } else { int tag = GetTag(&vars[1]); if ((tag != tagInt) || NotInt(&vars[2])) { error("Integer-forBy : endval or stepval not an Integer or Float.\n"); slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = gSpecialSelectors[opmPrimitiveFailed]; slot = sp; goto class_lookup; } slotCopy(&vars[4], &g->receiver); } dispatch_opcode; } case 8: { PyrSlot* vars = g->frame->vars; bool continueForBy = false; if (IsFloat(vars + 4)) { continueForBy = (slotRawFloat(&vars[2]) >= 0.0 && slotRawFloat(&vars[4]) <= slotRawFloat(&vars[1])) || (slotRawFloat(&vars[2]) < 0.0 && slotRawFloat(&vars[4]) >= slotRawFloat(&vars[1])); } else { continueForBy = (slotRawInt(&vars[2]) >= 0 && slotRawInt(&vars[4]) <= slotRawInt(&vars[1])) || (slotRawInt(&vars[2]) < 0 && slotRawInt(&vars[4]) >= slotRawInt(&vars[1])); } if (continueForBy) { slotCopy(++sp, &vars[3]); // push function slotCopy(++sp, &vars[4]); // push i slotCopy(++sp, &vars[5]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 9: { --sp; // Drop PyrSlot* vars = g->frame->vars; if (IsFloat(vars + 4)) { SetRaw(&vars[4], slotRawFloat(&vars[4]) + slotRawFloat(&vars[2])); } else { SetRaw(&vars[4], slotRawInt(&vars[4]) + slotRawInt(&vars[2])); // inc i } SetRaw(&vars[5], slotRawInt(&vars[5]) + 1); // inc j ip -= 4; dispatch_opcode; } // ArrayedCollection-do : 143 10, 143 1 case 10: { // 0 this, 1 func, 2 i PyrSlot* vars = g->frame->vars; if (slotRawInt(&vars[2]) < slotRawObject(&g->receiver)->size) { slotCopy(++sp, &vars[1]); // push function getIndexedSlot(slotRawObject(&g->receiver), ++sp, slotRawInt(&vars[2])); // push this.at(i) slotCopy(++sp, &vars[2]); // push i // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } // ArrayedCollection-reverseDo : 143 11, 143 12, 143 4 case 11: SetRaw(&g->frame->vars[2], slotRawObject(&g->receiver)->size - 1); dispatch_opcode; case 12: { PyrSlot* vars = g->frame->vars; if (slotRawInt(&vars[2]) >= 0) { slotCopy(++sp, &vars[1]); // push function getIndexedSlot(slotRawObject(&g->receiver), ++sp, slotRawInt(&vars[2])); // push this.at(i) slotCopy(++sp, &vars[3]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; // class_lookup: } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } // Dictionary-keysValuesArrayDo case 13: { PyrSlot* vars = g->frame->vars; if (IsNil(&vars[1])) { error("Dictionary-keysValuesArrayDo: first argument should not be nil.\n"); slotCopy(++sp, &g->receiver); numArgsPushed = 0; selector = gSpecialSelectors[opmPrimitiveFailed]; slot = sp; goto class_lookup; } int m = slotRawInt(&vars[3]); PyrObject* obj = slotRawObject(&vars[1]); if (m < obj->size) { slot = obj->slots + m; // key while (IsNil(slot)) { m += 2; if (m >= obj->size) { SetRaw(&vars[3], m); goto keysValuesArrayDo_return; } slot = obj->slots + m; // key } SetRaw(&vars[3], m); slotCopy(++sp, &vars[2]); // function slotCopy(++sp, &slot[0]); // key slotCopy(++sp, &slot[1]); // val slotCopy(++sp, &vars[4]); // j SetRaw(&vars[4], slotRawInt(&vars[4]) + 1); // SendSpecialMsg value numArgsPushed = 4; selector = gSpecialSelectors[opmValue]; slot = sp - 3; goto class_lookup; // class_lookup: } else { keysValuesArrayDo_return: slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 14: --sp; // Drop SetRaw(&g->frame->vars[3], slotRawInt(&g->frame->vars[3]) + 2); // inc i ip -= 4; dispatch_opcode; case 15: // unused opcode. break; case 16: { --sp; // Drop PyrSlot* vars = g->frame->vars; SetRaw(&vars[3], slotRawInt(&vars[3]) + slotRawInt(&vars[5])); // inc i by stepval SetRaw(&vars[4], slotRawInt(&vars[4]) + 1); // inc j ip -= 4; dispatch_opcode; } // Float-do : 143 17, 143 18 case 17: { PyrSlot* vars = g->frame->vars; if (slotRawFloat(&vars[2]) + 0.5 < slotRawFloat(&g->receiver)) { slotCopy(++sp, &vars[1]); // push function slotCopy(++sp, &vars[2]); // push i slotCopy(++sp, &vars[2]); // push i // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 18: { --sp; // Drop SetRaw(&g->frame->vars[2], slotRawFloat(&g->frame->vars[2]) + 1.0); // inc i ip -= 4; dispatch_opcode; } // Float-reverseDo : 143 19, 143 20, 143 21 case 19: { SetFloat(&g->frame->vars[2], slotRawFloat(&g->receiver) - 1.0); dispatch_opcode; } case 20: { PyrSlot* vars = g->frame->vars; if (slotRawFloat(&vars[2]) + 0.5 >= 0.0) { slotCopy(++sp, &vars[1]); // push function slotCopy(++sp, &vars[2]); // push i slotCopy(++sp, &vars[3]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } dispatch_opcode; } case 21: { --sp; // Drop PyrSlot* vars = g->frame->vars; SetRaw(&vars[2], slotRawFloat(&vars[2]) - 1.0); // dec i SetRaw(&vars[3], slotRawFloat(&vars[3]) - 1.0); // inc j ip -= 4; dispatch_opcode; } case 22: // ? question mark method --sp; if (IsNil(sp)) { *sp = *(sp + 1); } dispatch_opcode; case 23: // if not nil push this and jump. used to implement ?? if (NotNil(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else { --sp; ip += 2; } dispatch_opcode; case 24: // ifNil if (NotNil(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else { ip += 2; } --sp; dispatch_opcode; case 25: // ifNotNil if (IsNil(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else { ip += 2; } --sp; dispatch_opcode; case 26: // ifNotNilPushNil if (NotNil(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; slotCopy(sp, &gSpecialValues[svNil]); } else { ip += 2; --sp; } dispatch_opcode; case 27: // ifNilPushNil if (IsNil(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else { ip += 2; --sp; } dispatch_opcode; case 28: { // switch PyrObject* obj = slotRawObject(sp); op2 = 1 + arrayAtIdentityHashInPairs(obj, (sp - 1)); sp -= 2; ip += slotRawInt(&obj->slots[op2]); dispatch_opcode; } // Number-forSeries : 143 29, 143 30, 143 31 case 29: { PyrSlot* vars = g->frame->vars; // 0 receiver, 1 step, 2 last, 3 function, 4 i, 5 j if (IsInt(vars + 0) && (IsInt(vars + 1) || IsNil(vars + 1)) && (IsInt(vars + 2) || IsNil(vars + 2))) { if (IsNil(vars + 1)) { if (IsNil(vars + 2)) SetInt(vars + 2, 0x7FFFFFFF); if (slotRawInt(&vars[0]) < slotRawInt(&vars[2])) SetInt(vars + 1, 1); else SetInt(vars + 1, -1); } else { if (IsNil(vars + 2)) { if (slotRawInt(&vars[1]) < slotRawInt(&vars[0])) SetInt(vars + 2, 0x80000000); else SetInt(vars + 2, 0x7FFFFFFF); } SetInt(vars + 1, slotRawInt(&vars[1]) - slotRawInt(&vars[0])); } slotCopy(&vars[4], &vars[0]); } else { if (IsInt(vars + 0)) { SetFloat(&vars[4], slotRawInt(&vars[0])); } else if (IsFloat(vars + 0)) { SetFloat(&vars[4], slotRawFloat(&vars[0])); } else { bailFromNumberSeries: error("Number-forSeries : first, second or last not an Integer or Float.\n"); slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = gSpecialSelectors[opmPrimitiveFailed]; slot = sp; goto class_lookup; } if (IsNil(vars + 1)) { if (IsNil(vars + 2)) SetFloat(vars + 2, kBigBigFloat); else if (IsInt(vars + 2)) SetFloat(&vars[2], slotRawInt(&vars[2])); else if (!IsFloat(vars + 2)) goto bailFromNumberSeries; if (slotRawFloat(&vars[4]) < slotRawFloat(&vars[2])) SetFloat(vars + 1, 1.); else SetFloat(vars + 1, -1.); } else { if (IsInt(vars + 1)) SetFloat(&vars[1], slotRawInt(&vars[1])); else if (!IsFloat(vars + 1)) goto bailFromNumberSeries; if (IsNil(vars + 2)) { if (slotRawFloat(&vars[1]) < slotRawFloat(&vars[4])) SetFloat(vars + 2, kSmallSmallFloat); else SetFloat(vars + 2, kBigBigFloat); } else if (IsInt(vars + 2)) SetFloat(&vars[2], slotRawInt(&vars[2])); else if (!IsFloat(vars + 2)) goto bailFromNumberSeries; SetFloat(vars + 1, slotRawFloat(&vars[1]) - slotRawFloat(&vars[4])); } } dispatch_opcode; } case 30: { PyrSlot* vars = g->frame->vars; int tag = GetTag(&vars[1]); if (tag == tagInt) { if ((slotRawInt(&vars[1]) >= 0 && slotRawInt(&vars[4]) <= slotRawInt(&vars[2])) || (slotRawInt(&vars[1]) < 0 && slotRawInt(&vars[4]) >= slotRawInt(&vars[2]))) { slotCopy(++sp, &vars[3]); // push function slotCopy(++sp, &vars[4]); // push i slotCopy(++sp, &vars[5]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } } else { if ((slotRawFloat(&vars[1]) >= 0. && slotRawFloat(&vars[4]) <= slotRawFloat(&vars[2])) || (slotRawFloat(&vars[1]) < 0. && slotRawFloat(&vars[4]) >= slotRawFloat(&vars[2]))) { slotCopy(++sp, &vars[3]); // push function slotCopy(++sp, &vars[4]); // push i slotCopy(++sp, &vars[5]); // push j // SendSpecialMsg value numArgsPushed = 3; selector = gSpecialSelectors[opmValue]; slot = sp - 2; goto class_lookup; } else { slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; } } dispatch_opcode; } case 31: { --sp; // Drop PyrSlot* vars = g->frame->vars; int tag = GetTag(&vars[1]); if (tag == tagInt) { SetRaw(&vars[4], slotRawInt(&vars[4]) + slotRawInt(&vars[1])); // inc i } else { SetRaw(&vars[4], slotRawFloat(&vars[4]) + slotRawFloat(&vars[1])); // inc i } SetRaw(&vars[5], slotRawInt(&vars[5]) + 1); // inc j ip -= 4; dispatch_opcode; } } dispatch_opcode; } // opStoreClassVar case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: handle_op_144: handle_op_145: handle_op_146: handle_op_147: handle_op_148: handle_op_149: handle_op_150: handle_op_151: handle_op_152: handle_op_153: handle_op_154: handle_op_155: handle_op_156: handle_op_157: handle_op_158: handle_op_159 : { int op2 = op1 & 15; int op3 = ip[1]; ++ip; // get class var index slotCopy(&g->classvars->slots[(op2 << 8) | op3], sp--); g->gc->GCWrite(g->classvars, (sp + 1)); dispatch_opcode; } // opSendMsg case 160: handle_op_160 : { // special case for this as only arg int op2 = ip[1]; ++ip; // get selector index slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp; goto class_lookup; } case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: handle_op_161: handle_op_162: handle_op_163: handle_op_164: handle_op_165: handle_op_166: handle_op_167: handle_op_168: handle_op_169: handle_op_170: handle_op_171: handle_op_172: handle_op_173: handle_op_174: handle_op_175 : { int op2 = ip[1]; ++ip; // get selector index numArgsPushed = op1 & 15; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp - numArgsPushed + 1; goto class_lookup; } case 176: // opcTailCallReturnFromFunction handle_op_176: #if TAILCALLOPTIMIZE g->tailCall = 2; #endif dispatch_opcode; // opSuperMsg case 177: handle_op_177 : { // special case for this as only arg int op2 = ip[1]; ++ip; // get selector index slotCopy(++sp, &g->receiver); numArgsPushed = 1; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp; classobj = slotRawSymbol(&slotRawClass(&g->method->ownerclass)->superclass)->u.classobj; goto msg_lookup; } case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: handle_op_178: handle_op_179: handle_op_180: handle_op_181: handle_op_182: handle_op_183: handle_op_184: handle_op_185: handle_op_186: handle_op_187: handle_op_188: handle_op_189: handle_op_190: handle_op_191 : { int op2 = ip[1]; ++ip; // get selector index numArgsPushed = op1 & 15; selector = slotRawSymbol(&slotRawObject(&g->block->selectors)->slots[op2]); slot = sp - numArgsPushed + 1; classobj = slotRawSymbol(&slotRawClass(&g->method->ownerclass)->superclass)->u.classobj; goto msg_lookup; } // opSendSpecialMsg case 192: handle_op_192 : { slotCopy(++sp, &g->receiver); int op2 = ip[1]; ++ip; // get selector index numArgsPushed = 1; selector = gSpecialSelectors[op2]; slot = sp; goto class_lookup; } case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: handle_op_193: handle_op_194: handle_op_195: handle_op_196: handle_op_197: handle_op_198: handle_op_199: handle_op_200: handle_op_201: handle_op_202: handle_op_203: handle_op_204: handle_op_205: handle_op_206: handle_op_207 : { int op2 = ip[1]; ++ip; // get selector index numArgsPushed = op1 & 15; selector = gSpecialSelectors[op2]; slot = sp - numArgsPushed + 1; goto class_lookup; } // opSendSpecialUnaryArithMsg case 208: // opNeg handle_op_208: if (IsFloat(sp)) { SetFloat(sp, -slotRawFloat(sp)); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else if (IsInt(sp)) { SetRaw(sp, -slotRawInt(sp)); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 209: // opNot handle_op_209: if (IsTrue(sp)) { SetTagRaw(sp, tagFalse); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else if (IsFalse(sp)) { SetTagRaw(sp, tagTrue); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 210: // opIsNil handle_op_210: if (IsNil(sp)) { SetTagRaw(sp, tagTrue); } else { slotCopy(sp, &gSpecialValues[svFalse]); } #if TAILCALLOPTIMIZE g->tailCall = 0; #endif dispatch_opcode; case 211: // opNotNil handle_op_211: if (NotNil(sp)) { slotCopy(sp, &gSpecialValues[svTrue]); } else { SetTagRaw(sp, tagFalse); } #if TAILCALLOPTIMIZE g->tailCall = 0; #endif dispatch_opcode; case 212: handle_op_212: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 213: handle_op_213: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 214: handle_op_214: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 215: handle_op_215: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 216: handle_op_216: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 217: handle_op_217: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 218: handle_op_218: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 219: handle_op_219: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 220: handle_op_220: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 221: handle_op_221: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 222: handle_op_222: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 223: handle_op_223: handleSendSpecialUnaryArithMsg(g, sp, ip, op1); dispatch_opcode; // opSendSpecialBinaryArithMsg case 224: // add handle_op_224: if (IsInt(sp - 1)) { if (IsInt(sp)) { --sp; SetRaw(sp, slotRawInt(sp) + slotRawInt(sp + 1)); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opAdd; prAddInt(g, -1); sp = g->sp; ip = g->ip; } } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opAdd; prAddNum(g, -1); sp = g->sp; ip = g->ip; } dispatch_opcode; case 225: // subtract handle_op_225: if (IsInt(sp - 1)) { if (IsInt(sp)) { --sp; SetRaw(sp, slotRawInt(sp) - slotRawInt(sp + 1)); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opSub; prSubInt(g, -1); sp = g->sp; ip = g->ip; } } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opSub; prSubNum(g, -1); sp = g->sp; ip = g->ip; } dispatch_opcode; case 226: // multiply handle_op_226: if (IsInt(sp - 1)) { if (IsInt(sp)) { --sp; SetRaw(sp, slotRawInt(sp) * slotRawInt(sp + 1)); #if TAILCALLOPTIMIZE g->tailCall = 0; #endif } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opMul; prMulInt(g, -1); sp = g->sp; ip = g->ip; } } else { g->sp = sp; g->ip = ip; g->primitiveIndex = opMul; prMulNum(g, -1); sp = g->sp; ip = g->ip; } dispatch_opcode; case 227: handle_op_227: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 228: handle_op_228: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 229: handle_op_229: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 230: handle_op_230: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 231: handle_op_231: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 232: handle_op_232: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 233: handle_op_233: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 234: handle_op_234: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 235: handle_op_235: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 236: handle_op_236: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 237: handle_op_237: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 238: handle_op_238: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; case 239: handle_op_239: handleSendSpecialBinaryArithMsg(g, sp, ip, op1); dispatch_opcode; // opSpecialOpcodes case 240: handle_op_240: --sp; dispatch_opcode; // opDrop case 241: handle_op_241: ++sp; *sp = sp[-1]; dispatch_opcode; // opDup case 242: // opcFunctionReturn handle_op_242: g->sp = sp; g->ip = ip; returnFromBlock(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 243: // opcReturn handle_op_243: g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 244: // opcReturnSelf handle_op_244: slotCopy(++sp, &g->receiver); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 245: // opcReturnTrue handle_op_245: slotCopy(++sp, &gSpecialValues[svTrue]); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 246: // opcReturnFalse handle_op_246: slotCopy(++sp, &gSpecialValues[svFalse]); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 247: // opcReturnNil handle_op_247: slotCopy(++sp, &gSpecialValues[svNil]); g->sp = sp; g->ip = ip; returnFromMethod(g); sp = g->sp; ip = g->ip; dispatch_opcode; case 248: // opcJumpIfFalse handle_op_248: // cannot compare with o_false because it is NaN if (IsFalse(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; } else if (IsTrue(sp)) { ip += 2; } else { numArgsPushed = 1; selector = gSpecialSelectors[opmNonBooleanError]; slot = sp; goto class_lookup; } --sp; dispatch_opcode; case 249: // opcJumpIfFalsePushNil handle_op_249: if (IsFalse(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; slotCopy(sp, &gSpecialValues[svNil]); } else if (IsTrue(sp)) { --sp; ip += 2; } else { numArgsPushed = 1; selector = gSpecialSelectors[opmNonBooleanError]; slot = sp; goto class_lookup; } dispatch_opcode; case 250: // opcJumpIfFalsePushFalse handle_op_250: if (IsFalse(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; //*sp = r_false; } else if (IsTrue(sp)) { --sp; ip += 2; } else { numArgsPushed = 1; selector = gSpecialSelectors[opmNonBooleanError]; slot = sp; goto class_lookup; } dispatch_opcode; case 251: // opcJumpIfTruePushTrue handle_op_251: if (IsFalse(sp)) { --sp; ip += 2; } else if (IsTrue(sp)) { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; slotCopy(sp, &gSpecialValues[svTrue]); } else { numArgsPushed = 1; selector = gSpecialSelectors[opmNonBooleanError]; slot = sp; goto class_lookup; } dispatch_opcode; case 252: // opcJumpFwd handle_op_252 : { int jmplen = (ip[1] << 8) | ip[2]; ip += jmplen + 2; dispatch_opcode; } case 253: // opcJumpBak handle_op_253 : { --sp; // also drops the stack. This saves an opcode in the while loop // which is the only place this opcode is used. int jmplen = (ip[1] << 8) | ip[2]; ip -= jmplen; // assert(g->gc->SanityCheck()); dispatch_opcode; } case 254: // opcSpecialBinaryOpWithAdverb handle_op_254 : { int op2 = ip[1]; ++ip; // get selector index g->sp = sp; g->ip = ip; g->primitiveIndex = op2; doSpecialBinaryArithMsg(g, 3, false); sp = g->sp; ip = g->ip; dispatch_opcode; } case 255: // opcTailCallReturnFromMethod handle_op_255: #if TAILCALLOPTIMIZE g->tailCall = 1; #endif dispatch_opcode; //////////////////////////////////// class_lookup: // normal class lookup classobj = classOfSlot(slot); // message sends handled here: msg_lookup : { size_t index = slotRawInt(&classobj->classIndex) + selector->u.index; PyrMethod* meth = nullptr; if (UNLIKELY((selector->flags & sym_Class) != 0)) { // You have sent a message which is a class name. This is a bad thing. // There are two cases. It is either an illegitimate classname like // 1 FooBaz: 2 // in which case selector->u.index == 0 and you get a message or it is a real one like // 1 Object: 2 // in which case selector->u.index isn't pointing to a method and you get a segfault. So... meth = nullptr; } else { meth = gRowTable[index]; } // and now if meth is null, bail out just like if I don't understand it if (UNLIKELY(meth == nullptr || (slotRawSymbol(&meth->name) != selector))) { g->sp = sp; g->ip = ip; doesNotUnderstand(g, selector, numArgsPushed, 0); sp = g->sp; ip = g->ip; } else { PyrMethodRaw* methraw = METHRAW(meth); switch (methraw->methType) { case methNormal: /* normal msg send */ g->sp = sp; g->ip = ip; executeMethod(g, meth, numArgsPushed, 0); sp = g->sp; ip = g->ip; break; case methReturnSelf: /* return self */ sp -= numArgsPushed - 1; break; case methReturnLiteral: /* return literal */ sp -= numArgsPushed - 1; slotCopy(sp, &meth->selectors); /* in this case selectors is just a single value */ break; case methReturnArg: /* return an argument */ sp -= numArgsPushed - 1; index = methraw->specialIndex; // zero is index of the first argument if (index < numArgsPushed) { slotCopy(sp, sp + index); } else { slotCopy(sp, &slotRawObject(&meth->prototypeFrame)->slots[index]); } break; case methReturnInstVar: /* return inst var */ sp -= numArgsPushed - 1; index = methraw->specialIndex; slotCopy(sp, &slotRawObject(slot)->slots[index]); break; case methAssignInstVar: { /* assign inst var */ sp -= numArgsPushed - 1; index = methraw->specialIndex; PyrObject* obj = slotRawObject(slot); if (obj->IsImmutable()) { StoreToImmutableB(g, sp, ip); } else { if (numArgsPushed >= 2) { slotCopy(&obj->slots[index], sp + 1); g->gc->GCWrite(obj, sp + 1); } else { slotCopy(&obj->slots[index], &gSpecialValues[svNil]); } slotCopy(sp, slot); } break; } case methReturnClassVar: /* return class var */ sp -= numArgsPushed - 1; slotCopy(sp, &g->classvars->slots[methraw->specialIndex]); break; case methAssignClassVar: /* assign class var */ sp -= numArgsPushed - 1; if (numArgsPushed >= 2) { slotCopy(&g->classvars->slots[methraw->specialIndex], sp + 1); g->gc->GCWrite(g->classvars, sp + 1); } else slotCopy(&g->classvars->slots[methraw->specialIndex], &gSpecialValues[svNil]); slotCopy(sp, slot); break; case methRedirect: /* send a different selector to self */ if (numArgsPushed < methraw->numargs) { // not enough args pushed /* push default arg values */ PyrSlot* qslot; int m, mmax; qslot = slotRawObject(&meth->prototypeFrame)->slots + numArgsPushed - 1; for (m = 0, mmax = methraw->numargs - numArgsPushed; m < mmax; ++m) slotCopy(++sp, ++qslot); numArgsPushed = methraw->numargs; } selector = slotRawSymbol(&meth->selectors); goto msg_lookup; case methRedirectSuper: /* send a different selector to self */ if (numArgsPushed < methraw->numargs) { // not enough args pushed /* push default arg values */ PyrSlot* qslot; int m, mmax; qslot = slotRawObject(&meth->prototypeFrame)->slots + numArgsPushed - 1; for (m = 0, mmax = methraw->numargs - numArgsPushed; m < mmax; ++m) slotCopy(++sp, ++qslot); numArgsPushed = methraw->numargs; } selector = slotRawSymbol(&meth->selectors); classobj = slotRawSymbol(&slotRawClass(&meth->ownerclass)->superclass)->u.classobj; goto msg_lookup; case methForwardInstVar: /* forward to an instance variable */ if (numArgsPushed < methraw->numargs) { // not enough args pushed /* push default arg values */ PyrSlot* qslot; int m, mmax; qslot = slotRawObject(&meth->prototypeFrame)->slots + numArgsPushed - 1; for (m = 0, mmax = methraw->numargs - numArgsPushed; m < mmax; ++m) slotCopy(++sp, ++qslot); numArgsPushed = methraw->numargs; } selector = slotRawSymbol(&meth->selectors); index = methraw->specialIndex; slotCopy(slot, &slotRawObject(slot)->slots[index]); classobj = classOfSlot(slot); goto msg_lookup; case methForwardClassVar: /* forward to an instance variable */ if (numArgsPushed < methraw->numargs) { // not enough args pushed /* push default arg values */ PyrSlot* qslot; int m, mmax; qslot = slotRawObject(&meth->prototypeFrame)->slots + numArgsPushed - 1; for (m = 0, mmax = methraw->numargs - numArgsPushed; m < mmax; ++m) slotCopy(++sp, ++qslot); numArgsPushed = methraw->numargs; } selector = slotRawSymbol(&meth->selectors); slotCopy(slot, &g->classvars->slots[methraw->specialIndex]); classobj = classOfSlot(slot); goto msg_lookup; case methPrimitive: /* primitive */ g->sp = sp; g->ip = ip; doPrimitive(g, meth, numArgsPushed); sp = g->sp; ip = g->ip; break; } // switch (meth->methType) } // end handle message #if TAILCALLOPTIMIZE g->tailCall = 0; #endif dispatch_opcode; } //////////////////////////////////// key_class_lookup: // normal class lookup classobj = classOfSlot(slot); // message sends handled here: key_msg_lookup : { size_t index = slotRawInt(&classobj->classIndex) + selector->u.index; PyrMethod* meth = gRowTable[index]; if (UNLIKELY(slotRawSymbol(&meth->name) != selector)) { g->sp = sp; g->ip = ip; doesNotUnderstand(g, selector, numArgsPushed, numKeyArgsPushed); sp = g->sp; ip = g->ip; } else { PyrMethodRaw* methraw; methraw = METHRAW(meth); switch (methraw->methType) { case methNormal: /* normal msg send */ g->sp = sp; g->ip = ip; executeMethod(g, meth, numArgsPushed, numKeyArgsPushed); sp = g->sp; ip = g->ip; break; case methReturnSelf: /* return self */ sp -= numArgsPushed - 1; break; case methReturnLiteral: /* return literal */ sp -= numArgsPushed - 1; slotCopy(sp, &meth->selectors); /* in this case selectors is just a single value */ break; case methReturnArg: /* return an argument */ g->sp = sp; numArgsPushed = keywordFixStack(g, meth, methraw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; sp = g->sp; sp -= numArgsPushed - 1; index = methraw->specialIndex; // zero is index of the first argument if (index < numArgsPushed) { slotCopy(sp, sp + index); } else { slotCopy(sp, &slotRawObject(&meth->prototypeFrame)->slots[index]); } break; case methReturnInstVar: /* return inst var */ sp -= numArgsPushed - 1; index = methraw->specialIndex; slotCopy(sp, &slotRawObject(slot)->slots[index]); break; case methAssignInstVar: { /* assign inst var */ sp -= numArgsPushed - 1; numArgsPushed -= numKeyArgsPushed << 1; index = methraw->specialIndex; PyrObject* obj = slotRawObject(slot); if (obj->IsImmutable()) { StoreToImmutableB(g, sp, ip); } else { if (numArgsPushed >= 2) { slotCopy(&obj->slots[index], sp + 1); g->gc->GCWrite(obj, sp + 1); } else slotCopy(&obj->slots[index], &gSpecialValues[svNil]); slotCopy(sp, slot); } break; } case methReturnClassVar: /* return class var */ sp -= numArgsPushed - 1; slotCopy(sp, &g->classvars->slots[methraw->specialIndex]); break; case methAssignClassVar: /* assign class var */ sp -= numArgsPushed - 1; if (numArgsPushed >= 2) { slotCopy(&g->classvars->slots[methraw->specialIndex], sp + 1); g->gc->GCWrite(g->classvars, sp + 1); } else slotCopy(&g->classvars->slots[methraw->specialIndex], &gSpecialValues[svNil]); slotCopy(sp, slot); break; case methRedirect: /* send a different selector to self, e.g. this.subclassResponsibility */ g->sp = sp; numArgsPushed = keywordFixStack(g, meth, methraw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; sp = g->sp; selector = slotRawSymbol(&meth->selectors); goto msg_lookup; case methRedirectSuper: /* send a different selector to super */ g->sp = sp; numArgsPushed = keywordFixStack(g, meth, methraw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; sp = g->sp; selector = slotRawSymbol(&meth->selectors); classobj = slotRawSymbol(&slotRawClass(&meth->ownerclass)->superclass)->u.classobj; goto msg_lookup; case methForwardInstVar: /* forward to an instance variable */ g->sp = sp; numArgsPushed = keywordFixStack(g, meth, methraw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; sp = g->sp; selector = slotRawSymbol(&meth->selectors); index = methraw->specialIndex; slotCopy(slot, &slotRawObject(slot)->slots[index]); classobj = classOfSlot(slot); goto msg_lookup; case methForwardClassVar: /* forward to an instance variable */ g->sp = sp; numArgsPushed = keywordFixStack(g, meth, methraw, numArgsPushed, numKeyArgsPushed); numKeyArgsPushed = 0; sp = g->sp; selector = slotRawSymbol(&meth->selectors); slotCopy(slot, &g->classvars->slots[methraw->specialIndex]); classobj = classOfSlot(slot); goto msg_lookup; case methPrimitive: /* primitive */ g->sp = sp; g->ip = ip; doPrimitiveWithKeys(g, meth, numArgsPushed, numKeyArgsPushed); sp = g->sp; ip = g->ip; break; } // switch (meth->methType) } // end handle message numKeyArgsPushed = 0; #if TAILCALLOPTIMIZE g->tailCall = 0; #endif dispatch_opcode; } } // switch(op1) } // end while(running) #ifndef _WIN32 running = true; // reset the signal #endif g->sp = sp; g->ip = ip; } #if defined(__GNUC__) && !defined(__clang__) # pragma GCC pop_options #endif void DumpSimpleBackTrace(VMGlobals* g); void DumpSimpleBackTrace(VMGlobals* g) { int i; PyrFrame* frame; post("CALL STACK:\n"); // print the variables and arguments for the most recent frames in the // call graph frame = g->frame; for (i = 0; i < 16; ++i) { char str[256]; slotOneWord(&frame->method, str); post("%s ip %d\n", str, (char*)slotRawPtr(&frame->ip) - (char*)slotRawObject(&slotRawMethod(&frame->method)->code)->slots); frame = slotRawFrame(&frame->caller); if (!frame) break; } if (frame) { post("...\n"); } // DumpStack(g, g->sp); } void DumpBackTrace(VMGlobals* g) { int i; PyrFrame* frame; post("CALL STACK:\n"); // print the variables and arguments for the most recent frames in the // call graph frame = g->frame; for (i = 0; i < 16; ++i) { if (FrameSanity(frame, "DumpBackTrace")) { post("FRAME CORRUPTED\n"); return; } DumpFrame(frame); frame = slotRawFrame(&frame->caller); if (!frame) break; } if (frame) { post("...\n"); } // DumpStack(g, g->sp); } void DumpDetailedFrame(PyrFrame* frame); void DumpDetailedBackTrace(VMGlobals* g); void DumpDetailedBackTrace(VMGlobals* g) { int i; PyrFrame* frame; post("CALL STACK:\n"); // print the variables and arguments for the most recent frames in the // call graph frame = g->frame; for (i = 0; i < 16; ++i) { if (FrameSanity(frame, "DumpDetailedBackTrace")) { post("FRAME CORRUPTED\n"); return; } DumpDetailedFrame(frame); frame = slotRawFrame(&frame->caller); if (!frame) break; } if (frame) { post("...\n"); } // DumpStack(g, g->sp); } void DumpStack(VMGlobals* g, PyrSlot* sp) { PyrSlot* slot; char str[128]; #if BCSTAT dumpbcstat(); #endif postfl("STACK:\n"); slot = sp - 64; if (slot < g->gc->Stack()->slots) slot = g->gc->Stack()->slots; for (size_t i = slot - g->gc->Stack()->slots; slot <= sp; slot++, ++i) { slotString(slot, str); post(" %2d %s\n", i, str); } }
113,723
C++
.cpp
3,035
24.644481
120
0.475641
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
29,855
DumpParseNode.cpp
supercollider_supercollider/lang/LangSource/DumpParseNode.cpp
/* 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 "SCBase.h" #include "PyrParseNode.h" #include "PyrLexer.h" #include "PyrKernel.h" #include "Opcodes.h" #include "PyrPrimitive.h" #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <ctype.h> #ifdef _WIN32 # define PATH_MAX _MAX_PATH #endif extern int textpos; void dumpNodeList(PyrParseNode* node) { for (; node; node = node->mNext) { DUMPNODE(node, 0); } } void PyrCurryArgNode::dump(int level) { postfl("%2d CurryArg %d\n", level, mArgNum); } void PyrSlotNode::dump(int level) { if (mClassno == pn_PushLitNode) dumpPushLit(level); else if (mClassno == pn_PushNameNode) postfl("%2d PushName '%s'\n", level, slotRawSymbol(&mSlot)->name); else if (mClassno == pn_LiteralNode) dumpLiteral(level); else { postfl("%2d SlotNode\n", level); dumpPyrSlot(&mSlot); } DUMPNODE(mNext, level); } void PyrPushKeyArgNode::dump(int level) { postfl("%2d PushKeyArgNode\n", level); DUMPNODE(mSelector, level + 1); DUMPNODE(mExpr, level + 1); DUMPNODE(mNext, level); } void PyrClassExtNode::dump(int level) { postfl("%2d ClassExt '%s'\n", level, slotRawSymbol(&mClassName->mSlot)->name); DUMPNODE(mMethods, level + 1); DUMPNODE(mNext, level); } void PyrClassNode::dump(int level) { postfl("%2d Class '%s'\n", level, slotRawSymbol(&mClassName->mSlot)->name); DUMPNODE(mSuperClassName, level + 1); DUMPNODE(mVarlists, level + 1); DUMPNODE(mMethods, level + 1); DUMPNODE(mNext, level); } void PyrMethodNode::dump(int level) { postfl("%2d MethodNode '%s' %s\n", level, slotRawSymbol(&mMethodName->mSlot)->name, mPrimitiveName ? slotRawSymbol(&mPrimitiveName->mSlot)->name : ""); DUMPNODE(mArglist, level + 1); DUMPNODE(mBody, level + 1); DUMPNODE(mNext, level); } void PyrArgListNode::dump(int level) { postfl("%2d ArgList\n", level); DUMPNODE(mVarDefs, level + 1); DUMPNODE(mRest, level + 1); DUMPNODE(mKeywordArgs, level + 1); DUMPNODE(mNext, level); } void PyrVarListNode::dump(int level) { postfl("%2d VarList\n", level); DUMPNODE(mVarDefs, level + 1); DUMPNODE(mNext, level); } void PyrVarDefNode::dump(int level) { postfl("%2d VarDef '%s'\n", level, slotRawSymbol(&mVarName->mSlot)->name); DUMPNODE(mDefVal, level); DUMPNODE(mNext, level); } void PyrCallNode::dump(int level) { postfl("%2d Call '%s'\n", level, slotRawSymbol(&mSelector->mSlot)->name); DUMPNODE(mArglist, level + 1); DUMPNODE(mKeyarglist, level + 1); DUMPNODE(mNext, level); } void PyrBinopCallNode::dump(int level) { postfl("%2d BinopCall '%s'\n", level, slotRawSymbol(&mSelector->mSlot)->name); DUMPNODE(mArglist, level + 1); DUMPNODE(mNext, level); } void PyrDropNode::dump(int level) { postfl("%2d Drop (\n", level); DUMPNODE(mExpr1, level + 1); postfl(" -> %2d Drop\n", level); DUMPNODE(mExpr2, level + 1); postfl(") %2d Drop\n", level); DUMPNODE(mNext, level); } void PyrSlotNode::dumpPushLit(int level) { postfl("%2d PushLit\n", level); if (!IsPtr(&mSlot)) dumpPyrSlot(&mSlot); else { DUMPNODE((PyrParseNode*)slotRawObject(&mSlot), level); } } void PyrSlotNode::dumpLiteral(int level) { postfl("%2d Literal\n", level); if (!IsPtr(&mSlot)) dumpPyrSlot(&mSlot); else { DUMPNODE((PyrParseNode*)slotRawObject(&mSlot), level); } } void PyrReturnNode::dump(int level) { postfl("%2d Return (\n", level); DUMPNODE(mExpr, level + 1); postfl(") %2d Return \n", level); DUMPNODE(mNext, level); } void PyrBlockReturnNode::dump(int level) { postfl("%2d FuncReturn\n", level); DUMPNODE(mNext, level); } void PyrAssignNode::dump(int level) { postfl("%2d Assign '%s'\n", level, slotRawSymbol(&mVarName->mSlot)->name); DUMPNODE(mVarName, level + 1); DUMPNODE(mExpr, level + 1); DUMPNODE(mNext, level); } void PyrSetterNode::dump(int level) { // postfl("%2d Assign '%s'\n", level, slotRawSymbol(&mVarName->mSlot)->name); DUMPNODE(mSelector, level + 1); DUMPNODE(mExpr1, level + 1); DUMPNODE(mExpr2, level + 1); } void PyrMultiAssignNode::dump(int level) { postfl("%2d MultiAssign\n", level); DUMPNODE(mVarList, level + 1); DUMPNODE(mExpr, level + 1); DUMPNODE(mNext, level); } void PyrMultiAssignVarListNode::dump(int level) { postfl("%2d MultiAssignVarList\n", level); DUMPNODE(mVarNames, level + 1); DUMPNODE(mRest, level + 1); DUMPNODE(mNext, level); } void PyrDynDictNode::dump(int level) { postfl("%2d DynDict\n", level); DUMPNODE(mElems, level + 1); DUMPNODE(mNext, level); } void PyrDynListNode::dump(int level) { postfl("%2d DynList\n", level); DUMPNODE(mElems, level + 1); DUMPNODE(mNext, level); } void PyrLitListNode::dump(int level) { postfl("%2d LitList\n", level); postfl(" %2d mElems\n", level); DUMPNODE(mElems, level + 1); postfl(" %2d mNext\n", level); DUMPNODE(mNext, level); } void PyrBlockNode::dump(int level) { postfl("%2d Func\n", level); DUMPNODE(mArglist, level + 1); DUMPNODE(mBody, level + 1); DUMPNODE(mNext, level); } void dumpPyrSlot(PyrSlot* slot) { char str[1024]; slotString(slot, str); post(" %s\n", str); } void slotString(PyrSlot* slot, char* str) { switch (GetTag(slot)) { case tagInt: sprintf(str, "Integer %d", slotRawInt(slot)); break; case tagChar: sprintf(str, "Character %d '%c'", static_cast<int>(slotRawChar(slot)), static_cast<int>(slotRawChar(slot))); break; case tagSym: if (strlen(slotRawSymbol(slot)->name) > 240) { char str2[256]; memcpy(str2, slotRawSymbol(slot)->name, 240); str2[240] = 0; snprintf(str, 256, "Symbol '%s...'", str2); } else { snprintf(str, 256, "Symbol '%s'", slotRawSymbol(slot)->name); } break; case tagObj: if (slotRawObject(slot)) { PyrClass* classptr = slotRawObject(slot)->classptr; if (classptr == class_class) { sprintf(str, "class %s (%p)", slotRawSymbol(&((PyrClass*)slotRawObject(slot))->name)->name, slotRawObject(slot)); } else if (classptr == class_string) { char str2[48]; int len; if (slotRawObject(slot)->size > 47) { memcpy(str2, (char*)slotRawObject(slot)->slots, 44); str2[44] = '.'; str2[45] = '.'; str2[46] = '.'; str2[47] = 0; } else { len = sc_min(47, slotRawObject(slot)->size); memcpy(str2, (char*)slotRawObject(slot)->slots, len); str2[len] = 0; } sprintf(str, "\"%s\"", str2); } else if (classptr == class_method) { sprintf(str, "instance of Method %s:%s (%p)", slotRawSymbol(&slotRawClass(&slotRawMethod(slot)->ownerclass)->name)->name, slotRawSymbol(&slotRawMethod(slot)->name)->name, slotRawMethod(slot)); } else if (classptr == class_fundef) { PyrSlot *context, *nextcontext; // find function's method nextcontext = &slotRawBlock(slot)->contextDef; if (NotNil(nextcontext)) { do { context = nextcontext; nextcontext = &slotRawBlock(context)->contextDef; } while (NotNil(nextcontext)); if (isKindOf(slotRawObject(context), class_method)) { sprintf(str, "instance of FunctionDef in Method %s:%s", slotRawSymbol(&slotRawClass(&slotRawMethod(context)->ownerclass)->name)->name, slotRawSymbol(&slotRawMethod(context)->name)->name); } else { sprintf(str, "instance of FunctionDef in closed FunctionDef"); } } else { sprintf(str, "instance of FunctionDef - closed"); } } else if (classptr == class_frame) { if (!slotRawFrame(slot)) { sprintf(str, "Frame (%0X)", slotRawInt(slot)); } else if (slotRawBlock(&slotRawFrame(slot)->method)->classptr == class_method) { sprintf(str, "Frame (%p) of %s:%s", slotRawObject(slot), slotRawSymbol(&slotRawClass(&slotRawMethod(&slotRawFrame(slot)->method)->ownerclass)->name) ->name, slotRawSymbol(&slotRawMethod(&slotRawFrame(slot)->method)->name)->name); } else { sprintf(str, "Frame (%p) of Function", slotRawFrame(slot)); } } else { sprintf(str, "instance of %s (%p, size=%d, set=%d)", slotRawSymbol(&classptr->name)->name, slotRawObject(slot), slotRawObject(slot)->size, slotRawObject(slot)->obj_sizeclass); } } else { sprintf(str, "NULL Object Pointer"); } break; case tagNil: sprintf(str, "nil"); break; case tagFalse: sprintf(str, "false"); break; case tagTrue: sprintf(str, "true"); break; case tagPtr: sprintf(str, "RawPointer %p", slotRawPtr(slot)); break; default: { union { int32 i[2]; double f; } u; u.f = slotRawFloat(slot); sprintf(str, "Float %f %08X %08X", u.f, u.i[0], u.i[1]); break; } } } static void printObject(PyrSlot* slot, PyrObject* obj, char* str) { assert(obj); PyrClass* classptr = obj->classptr; if (classptr == class_class) { sprintf(str, "class %s", slotRawSymbol(&((PyrClass*)obj)->name)->name); } else if (classptr == class_string) { char str2[32]; int len; if (obj->size > 31) { memcpy(str2, (char*)obj->slots, 28); str2[28] = '.'; str2[29] = '.'; str2[30] = '.'; str2[31] = 0; } else { len = sc_min(31, obj->size); memcpy(str2, (char*)obj->slots, len); str2[len] = 0; } sprintf(str, "\"%s\"", str2); } else if (classptr == class_method) { sprintf(str, "%s:%s", slotRawSymbol(&slotRawClass(&slotRawMethod(slot)->ownerclass)->name)->name, slotRawSymbol(&slotRawMethod(slot)->name)->name); } else if (classptr == class_fundef) { PyrSlot *context, *nextcontext; // find function's method nextcontext = &slotRawBlock(slot)->contextDef; if (NotNil(nextcontext)) { do { context = nextcontext; nextcontext = &slotRawBlock(context)->contextDef; } while (NotNil(nextcontext)); if (isKindOf(slotRawObject(context), class_method)) { sprintf(str, "< FunctionDef in Method %s:%s >", slotRawSymbol(&slotRawClass(&slotRawMethod(context)->ownerclass)->name)->name, slotRawSymbol(&slotRawMethod(context)->name)->name); } else { sprintf(str, "< FunctionDef in closed FunctionDef >"); } } else { sprintf(str, "< closed FunctionDef >"); } } else if (classptr == class_frame) { if (!slotRawFrame(slot)) { sprintf(str, "Frame (null)"); } else if (!slotRawBlock(&slotRawFrame(slot)->method)) { sprintf(str, "Frame (null method)"); } else if (slotRawBlock(&slotRawFrame(slot)->method)->classptr == class_method) { sprintf(str, "Frame (%p) of %s:%s", obj, slotRawSymbol(&slotRawClass(&slotRawMethod(&slotRawFrame(slot)->method)->ownerclass)->name)->name, slotRawSymbol(&slotRawMethod(&slotRawFrame(slot)->method)->name)->name); } else { sprintf(str, "Frame (%p) of Function", obj); } } else if (classptr == class_array) { sprintf(str, "[*%d]", obj->size); } else { sprintf(str, "<instance of %s>", slotRawSymbol(&classptr->name)->name); } } // Assumed: str has enough space to hold the representation of d static void prettyFormatFloat(char* str, double d) { sprintf(str, "%.14g", d); // append a trailing '.0' if the number would look like an integer. for (; *str; ++str) { if ((*str < '0' || *str > '9') && *str != '-') return; } str[0] = '.'; str[1] = '0'; str[2] = '\0'; } void slotOneWord(PyrSlot* slot, char* str) { str[0] = 0; switch (GetTag(slot)) { case tagInt: sprintf(str, "%d", slotRawInt(slot)); break; case tagChar: sprintf(str, "$%c", static_cast<int>(slotRawChar(slot))); break; case tagSym: if (strlen(slotRawSymbol(slot)->name) > 240) { char str2[256]; memcpy(str2, slotRawSymbol(slot)->name, 240); str2[240] = 0; snprintf(str, 256, "'%s...'", str2); } else { snprintf(str, 256, "'%s'", slotRawSymbol(slot)->name); } break; case tagObj: { PyrObject* slotObj = slotRawObject(slot); if (slotObj) printObject(slot, slotObj, str); else sprintf(str, "NULL Object Pointer"); break; } case tagNil: sprintf(str, "nil"); break; case tagFalse: sprintf(str, "false"); break; case tagTrue: sprintf(str, "true"); break; case tagPtr: sprintf(str, "ptr%p", slotRawPtr(slot)); break; default: prettyFormatFloat(str, slotRawFloat(slot)); break; } } bool postString(PyrSlot* slot, char* str) { bool res = true; switch (GetTag(slot)) { case tagInt: sprintf(str, "%d", slotRawInt(slot)); break; case tagChar: sprintf(str, "%c", slotRawChar(slot)); break; case tagSym: str[0] = 0; res = false; break; case tagObj: { PyrObject* slotObj = slotRawObject(slot); if (slotObj) { PyrClass* classptr = slotRawObject(slot)->classptr; if (classptr == class_class || classptr == class_method || classptr == class_fundef || classptr == class_frame) printObject(slot, slotObj, str); else { str[0] = 0; res = false; } } else sprintf(str, "NULL Object Pointer"); break; } case tagNil: sprintf(str, "nil"); break; case tagFalse: sprintf(str, "false"); break; case tagTrue: sprintf(str, "true"); break; case tagPtr: sprintf(str, "%p", slotRawPtr(slot)); break; default: prettyFormatFloat(str, slotRawFloat(slot)); break; } return res; } int asCompileString(PyrSlot* slot, char* str) { switch (GetTag(slot)) { case tagInt: sprintf(str, "%d", slotRawInt(slot)); break; case tagChar: { int c = slotRawChar(slot); if (isprint(c)) { sprintf(str, "$%c", c); } else { switch (c) { case '\n': strcpy(str, "$\\n"); break; case '\r': strcpy(str, "$\\r"); break; case '\t': strcpy(str, "$\\t"); break; case '\f': strcpy(str, "$\\f"); break; case '\v': strcpy(str, "$\\v"); break; default: sprintf(str, "%d.asAscii", c); } } break; } case tagSym: return errFailed; case tagObj: return errFailed; case tagNil: sprintf(str, "nil"); break; case tagFalse: sprintf(str, "false"); break; case tagTrue: sprintf(str, "true"); break; case tagPtr: strcpy(str, "/*Ptr*/ nil"); break; default: sprintf(str, "%f", slotRawFloat(slot)); break; } return errNone; } void stringFromPyrString(PyrString* obj, char* str, int maxlength); void stringFromPyrString(PyrString* obj, char* str, int maxlength) { if (obj->classptr == class_string) { int len; if (obj->size > maxlength - 4) { memcpy(str, obj->s, maxlength - 4); str[maxlength - 4] = '.'; str[maxlength - 3] = '.'; str[maxlength - 2] = '.'; str[maxlength - 1] = 0; } else { len = sc_min(maxlength - 1, obj->size); memcpy(str, obj->s, len); str[len] = 0; } } else { sprintf(str, "not a string"); } } void pstrncpy(unsigned char* s1, unsigned char* s2, int n); void pstringFromPyrString(PyrString* obj, unsigned char* str, int maxlength) { static const char not_a_string[] = "not a string"; const char* src; int len; if (obj && obj->classptr == class_string) { len = sc_min(maxlength - 1, obj->size); src = obj->s; } else { len = sizeof(not_a_string); src = not_a_string; } memcpy(str + 1, src, len); str[0] = len; }
18,556
C++
.cpp
542
25.846863
119
0.560775
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
29,856
SimpleStack.cpp
supercollider_supercollider/lang/LangSource/SimpleStack.cpp
/* 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 <stdlib.h> #include <string.h> //#include <stdio.h> #include "SCBase.h" #include "SimpleStack.h" #include "InitAlloc.h" void initLongStack(LongStack* self) { // dbg("initLongStack"); self->maxsize = 0; self->stak = nullptr; self->num = 0; } void freeLongStack(LongStack* self) { // dbg("freeLongStack"); self->maxsize = 0; self->num = 0; if (self->stak) { pyr_pool_compile->Free((void*)self->stak); self->stak = nullptr; } } void growLongStack(LongStack* self) { if (self->maxsize) { intptr_t* oldstak; self->maxsize += self->maxsize >> 1; // grow by 50% oldstak = self->stak; // pyrmalloc: // lifetime: kill after compile. self->stak = (intptr_t*)pyr_pool_compile->Alloc(self->maxsize * sizeof(intptr_t)); MEMFAIL(self->stak); // BlockMoveData(oldstak, self->stak, self->num * sizeof(intptr_t)); memcpy(self->stak, oldstak, self->num * sizeof(intptr_t)); pyr_pool_compile->Free((void*)oldstak); } else { self->maxsize = 32; self->stak = (intptr_t*)pyr_pool_compile->Alloc(self->maxsize * sizeof(intptr_t)); MEMFAIL(self->stak); } } void pushls(LongStack* self, intptr_t value) { // dbg2("pushls %lX", value); if (self->num + 1 > self->maxsize) { growLongStack(self); } self->stak[self->num++] = value; } intptr_t popls(LongStack* self) { if (self->num > 0) return self->stak[--self->num]; else { error("stack empty! (pop)\n"); return 0; } } int emptyls(LongStack* self) { return self->num <= 0; }
2,516
C++
.cpp
71
30.28169
90
0.654067
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
29,857
SC_LanguageConfig.cpp
supercollider_supercollider/lang/LangSource/SC_LanguageConfig.cpp
/* * Copyright 2003 Maurizio Umberto Puxeddu * Copyright 2011 Jakob Leben * * This file is part of SuperCollider. * * 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_LanguageConfig.hpp" #include "SC_Filesystem.hpp" // getDirectory #include "SCBase.h" // postfl #include <algorithm> // std::find #include <functional> // std::function #include <filesystem> #include <fstream> #include <yaml-cpp/yaml.h> // YAML SC_LanguageConfig::Path SC_LanguageConfig::gConfigFile; bool SC_LanguageConfig::gPostInlineWarnings = false; SC_LanguageConfig* gLanguageConfig; static const char* INCLUDE_PATHS = "includePaths"; static const char* EXCLUDE_PATHS = "excludePaths"; static const char* POST_INLINE_WARNINGS = "postInlineWarnings"; static const char* CLASS_LIB_DIR_NAME = "SCClassLibrary"; const char* SCLANG_YAML_CONFIG_FILENAME = "sclang_conf.yaml"; static const char* EXCLUDE_DEFAULT_PATHS = "excludeDefaultPaths"; using DirName = SC_Filesystem::DirName; namespace fs = std::filesystem; void SC_LanguageConfig::setExcludeDefaultPaths(bool value) { if (mExcludeDefaultPaths != value) { if (value) { mDefaultClassLibraryDirectories.clear(); } else { const Path& classLibraryDir = SC_Filesystem::instance().getDirectory(DirName::Resource) / CLASS_LIB_DIR_NAME; addPath(mDefaultClassLibraryDirectories, classLibraryDir); const Path& systemExtensionDir = SC_Filesystem::instance().getDirectory(DirName::SystemExtension); addPath(mDefaultClassLibraryDirectories, systemExtensionDir); const Path& userExtensionDir = SC_Filesystem::instance().getDirectory(DirName::UserExtension); addPath(mDefaultClassLibraryDirectories, userExtensionDir); } } mExcludeDefaultPaths = value; } void SC_LanguageConfig::postExcludedDirectories(void) const { for (auto it : mExcludedDirectories) { post("\texcluding dir: '%s'\n", it.c_str()); } } bool SC_LanguageConfig::forEachIncludedDirectory(bool (*func)(const Path&)) const { for (const auto& it : mDefaultClassLibraryDirectories) { if (!pathIsExcluded(it)) { if (!func(it)) return false; } } for (const auto& it : mIncludedDirectories) { if (!pathIsExcluded(it)) { if (!func(it)) return false; } } return true; } bool SC_LanguageConfig::pathIsExcluded(const Path& path) const { return findPath(mExcludedDirectories, path); } bool SC_LanguageConfig::addIncludedDirectory(const Path& path) { return addPath(mIncludedDirectories, path); } bool SC_LanguageConfig::addExcludedDirectory(const Path& path) { return addPath(mExcludedDirectories, path); } bool SC_LanguageConfig::removeIncludedDirectory(const Path& path) { return removePath(mIncludedDirectories, path); } bool SC_LanguageConfig::removeExcludedDirectory(const Path& path) { return removePath(mExcludedDirectories, path); } static void processPathList(const char* nodeName, YAML::Node& doc, const std::function<void(const std::filesystem::path&)>& func) { const YAML::Node& items = doc[nodeName]; if (items && items.IsSequence()) { for (auto const& item : items) { const std::string& path = item.as<std::string>(""); if (!path.empty()) { const std::filesystem::path& native_path = SC_Codecvt::utf8_str_to_path(path); func(native_path); } } } } static void processBool(const char* nodeName, YAML::Node& doc, const std::function<void(bool)>& successFunc, const std::function<void()>& failFunc) { const YAML::Node& item = doc[nodeName]; if (item) { try { successFunc(item.as<bool>()); } catch (...) { postfl("WARNING: Cannot parse config file entry \"%s\"\n", nodeName); failFunc(); } } else { failFunc(); // call failFunc if item is not found } } bool SC_LanguageConfig::readLibraryConfigYAML(const Path& fileName, bool standalone) { freeLibraryConfig(); gLanguageConfig = new SC_LanguageConfig(); using namespace YAML; try { std::ifstream fin(fileName); Node doc = Load(fin); if (doc) { processBool( POST_INLINE_WARNINGS, doc, [](bool b) { gPostInlineWarnings = b; }, []() {}); processBool( EXCLUDE_DEFAULT_PATHS, doc, [standalone](bool b) { gLanguageConfig->setExcludeDefaultPaths(standalone || b); }, [standalone] { gLanguageConfig->setExcludeDefaultPaths(standalone); }); processPathList(INCLUDE_PATHS, doc, [](const Path& p) { gLanguageConfig->addIncludedDirectory(p); }); processPathList(EXCLUDE_PATHS, doc, [](const Path& p) { gLanguageConfig->addExcludedDirectory(p); }); } return true; } catch (std::exception& e) { postfl("Exception while parsing YAML config file: %s\n", e.what()); freeLibraryConfig(); return false; } } bool SC_LanguageConfig::writeLibraryConfigYAML(const Path& fileName) { if (!fs::exists(fileName.parent_path())) return false; using namespace YAML; Emitter out; out.SetIndent(4); out.SetMapFormat(Block); out.SetSeqFormat(Block); out.SetBoolFormat(TrueFalseBool); out << BeginMap; out << Key << INCLUDE_PATHS; out << Value << BeginSeq; for (const fs::path& it : gLanguageConfig->mIncludedDirectories) out << SC_Codecvt::path_to_utf8_str(it); out << EndSeq; out << Key << EXCLUDE_PATHS; out << Value << BeginSeq; for (const fs::path& it : gLanguageConfig->mExcludedDirectories) out << SC_Codecvt::path_to_utf8_str(it); out << EndSeq; out << Key << POST_INLINE_WARNINGS; out << Value << gPostInlineWarnings; out << Key << EXCLUDE_DEFAULT_PATHS; out << Value << gLanguageConfig->mExcludeDefaultPaths; out << EndMap; std::ofstream fout(fileName); fout << out.c_str(); return fout.good(); } bool SC_LanguageConfig::defaultLibraryConfig(bool standalone) { freeLibraryConfig(); gLanguageConfig = new SC_LanguageConfig(); gLanguageConfig->setExcludeDefaultPaths(standalone); return true; } bool SC_LanguageConfig::readLibraryConfig(bool standalone) { bool configured = false; if (fs::exists(gConfigFile)) configured = readLibraryConfigYAML(gConfigFile, standalone); if (!configured && !standalone) { const Path userYamlConfigFile = SC_Filesystem::instance().getDirectory(DirName::UserConfig) / SCLANG_YAML_CONFIG_FILENAME; if (fs::exists(userYamlConfigFile)) configured = readLibraryConfigYAML(userYamlConfigFile, standalone); if (!configured) { const Path globalYamlConfigFile = Path("/etc") / SCLANG_YAML_CONFIG_FILENAME; if (fs::exists(globalYamlConfigFile)) configured = readLibraryConfigYAML(globalYamlConfigFile, standalone); } } if (!configured) configured = SC_LanguageConfig::defaultLibraryConfig(standalone); return configured; } void SC_LanguageConfig::freeLibraryConfig() { if (gLanguageConfig) { delete gLanguageConfig; gLanguageConfig = nullptr; } } bool SC_LanguageConfig::findPath(const DirVector& vec, const Path& path) { return std::find(vec.begin(), vec.end(), path) != vec.end(); } bool SC_LanguageConfig::addPath(DirVector& vec, const Path& path) { if (!findPath(vec, path)) { vec.push_back(path); return true; } else { return false; } } bool SC_LanguageConfig::removePath(DirVector& vec, const Path& path) { const DirVector::iterator& end = std::remove(vec.begin(), vec.end(), path); const bool removed = end != vec.end(); vec.erase(end, vec.end()); return removed; }
8,690
C++
.cpp
210
35.07619
116
0.67489
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
29,858
PyrObject.cpp
supercollider_supercollider/lang/LangSource/PyrObject.cpp
/* 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 <atomic> #include <cstdlib> #include <cstring> #include <climits> #include "GC.h" #include "PyrMessage.h" #include "PyrInterpreter.h" #include "PyrSymbolTable.h" #include "PyrObjectProto.h" #include "PyrKernelProto.h" #include "PyrLexer.h" #include "InitAlloc.h" #include "Hash.h" #include "SC_Alloca.h" #include "SC_Lock.h" #include <set> #include <limits> #include <boost/range/irange.hpp> #define BOOST_THREAD_VERSION 4 #define BOOST_THREAD_PROVIDES_EXECUTORS #include <boost/thread/future.hpp> #include <boost/thread/executor.hpp> #include <boost/thread/executors/basic_thread_pool.hpp> #ifdef _MSC_VER # include <future> #endif #if 0 // not yet # include <parallel/algorithm> #endif PyrClass* gClassList = nullptr; int gNumSelectors = 0; int gNumClasses = 0; int gNumClassVars = 0; int gFormatElemSize[NUMOBJFORMATS]; int gFormatElemCapc[NUMOBJFORMATS]; int gFormatElemTag[NUMOBJFORMATS]; PyrMethod* gNullMethod; // used to fill row table PyrClass* gTagClassTable[16]; PyrClass* class_object; PyrClass* class_dict; PyrClass* class_array; PyrClass *class_list, *class_method, *class_fundef, *class_frame, *class_class; PyrClass *class_symbol, *class_nil; PyrClass *class_boolean, *class_true, *class_false; PyrClass *class_int, *class_char, *class_float, *class_complex; PyrClass* class_rawptr; PyrClass* class_string; PyrClass *class_magnitude, *class_number, *class_collection, *class_ordered_collection; PyrClass* class_arrayed_collection; PyrClass* class_sequenceable_collection; PyrClass* class_simple_number; PyrClass* class_rawarray; PyrClass* class_signal; PyrClass* class_wavetable; PyrClass* class_floatarray; PyrClass* class_int8array; PyrClass* class_int16array; PyrClass* class_int32array; PyrClass* class_symbolarray; PyrClass* class_doublearray; PyrClass *class_func, *class_absfunc; PyrClass* class_stream; PyrClass* class_process; PyrClass* class_interpreter; PyrClass* class_thread; PyrClass* class_routine; PyrClass* class_finalizer; PyrClass* class_server_shm_interface; PyrSymbol* s_none; PyrSymbol* s_object; PyrSymbol* s_bag; PyrSymbol* s_set; PyrSymbol* s_identityset; PyrSymbol* s_dictionary; PyrSymbol* s_identitydictionary; PyrSymbol* s_linkedlist; PyrSymbol* s_sortedlist; PyrSymbol* s_array; PyrSymbol *s_list, *s_method, *s_fundef, *s_frame, *s_class; PyrSymbol *s_symbol, *s_nil; PyrSymbol *s_boolean, *s_true, *s_false; PyrSymbol *s_int, *s_char, *s_color, *s_float, *s_complex; PyrSymbol* s_rawptr; PyrSymbol* s_string; PyrSymbol *s_magnitude, *s_number, *s_collection, *s_ordered_collection; PyrSymbol* s_arrayed_collection; PyrSymbol* s_sequenceable_collection; PyrSymbol* s_simple_number; PyrSymbol* s_signal; PyrSymbol* s_wavetable; PyrSymbol* s_rawarray; PyrSymbol* s_int8array; PyrSymbol* s_int16array; PyrSymbol* s_int32array; PyrSymbol* s_symbolarray; PyrSymbol* s_doublearray; PyrSymbol* s_floatarray; PyrSymbol* s_rect; PyrSymbol *s_func, *s_absfunc; PyrSymbol* s_stream; PyrSymbol* s_process; PyrSymbol* s_main; PyrSymbol* s_thread; PyrSymbol* s_routine; PyrSymbol* s_task; PyrSymbol* s_prstart; PyrSymbol* s_interpreter; PyrSymbol* s_finalizer; PyrSymbol* s_awake; PyrSymbol* s_systemclock; PyrSymbol* s_server_shm_interface; PyrSymbol *s_interpretCmdLine, *s_interpretPrintCmdLine; PyrSymbol* s_doesNotUnderstand; PyrSymbol *s_curProcess, *s_curMethod, *s_curBlock, *s_curClosure, *s_curThread; PyrSymbol *s_run, *s_stop, *s_tick; PyrSymbol* s_startup; PyrSymbol* s_next; PyrSymbol* s_env; PyrSymbol *s_new, *s_ref, *s_value, *s_at, *s_put; PyrSymbol *s_performList, *s_superPerformList; PyrSymbol* s_performArgs; PyrSymbol *s_series, *s_copyseries, *s_putseries; PyrSymbol *s_envirGet, *s_envirPut; PyrSymbol *s_synth, *s_environment, *s_event; PyrSymbol* s_shutdown; PyrSymbol *s_super, *s_this; PyrSlot o_nil, o_true, o_false; PyrSlot o_fhalf, o_fnegone, o_fzero, o_fone, o_ftwo, o_inf; PyrSlot o_negone, o_zero, o_one, o_two; PyrSlot o_none; PyrSlot o_emptyarray, o_onenilarray, o_argnamethis; void initSymbols() { // basic keywords s_new = getsym("new"); s_none = getsym("__none"); /* Dummy symbol for null superclass or primitive. Prefixed with * `__` to avoid collisions with possible method and primitive names. */ s_this = getsym("this"); s_super = getsym("super"); s_curProcess = getsym("thisProcess"); s_curThread = getsym("thisThread"); s_curMethod = getsym("thisMethod"); s_curBlock = getsym("thisFunctionDef"); s_curClosure = getsym("thisFunction"); // classes s_object = getsym("Object"); s_ref = getsym("Ref"); s_dictionary = getsym("Dictionary"); s_bag = getsym("Bag"); s_set = getsym("Set"); s_identityset = getsym("IdentitySet"); s_identitydictionary = getsym("IdentityDictionary"); s_linkedlist = getsym("LinkedList"); s_sortedlist = getsym("SortedList"); s_array = getsym("Array"); s_list = getsym("List"); s_method = getsym("Method"); s_fundef = getsym("FunctionDef"); s_frame = getsym("Frame"); s_class = getsym("Class"); s_symbol = getsym("Symbol"); s_nil = getsym("Nil"); s_true = getsym("True"); s_false = getsym("False"); s_int = getsym("Integer"); s_float = getsym("Float"); s_char = getsym("Char"); s_color = getsym("Color"); s_rawptr = getsym("RawPointer"); s_string = getsym("String"); s_magnitude = getsym("Magnitude"); s_number = getsym("Number"); s_simple_number = getsym("SimpleNumber"); s_collection = getsym("Collection"); s_arrayed_collection = getsym("ArrayedCollection"); s_sequenceable_collection = getsym("SequenceableCollection"); s_boolean = getsym("Boolean"); s_signal = getsym("Signal"); s_wavetable = getsym("Wavetable"); s_rawarray = getsym("RawArray"); s_int8array = getsym("Int8Array"); s_int16array = getsym("Int16Array"); s_int32array = getsym("Int32Array"); s_symbolarray = getsym("SymbolArray"); s_floatarray = getsym("FloatArray"); s_doublearray = getsym("DoubleArray"); s_complex = getsym("Complex"); s_rect = getsym("Rect"); s_absfunc = getsym("AbstractFunction"); s_func = getsym("Function"); s_stream = getsym("Stream"); s_process = getsym("Process"); s_main = getsym("Main"); s_thread = getsym("Thread"); s_routine = getsym("Routine"); s_task = getsym("Task"); s_interpreter = getsym("Interpreter"); s_finalizer = getsym("Finalizer"); s_systemclock = getsym("SystemClock"); s_server_shm_interface = getsym("ServerShmInterface"); s_env = getsym("Env"); s_synth = getsym("Synth"); s_environment = getsym("Environment"); s_event = getsym("Event"); // interpreter s_interpretCmdLine = getsym("interpretCmdLine"); s_interpretPrintCmdLine = getsym("interpretPrintCmdLine"); s_doesNotUnderstand = getsym("doesNotUnderstand"); s_startup = getsym("startup"); s_awake = getsym("awake"); s_shutdown = getsym("shutdown"); // methods s_run = getsym("run"); s_stop = getsym("stop"); s_tick = getsym("tick"); s_next = getsym("next"); s_value = getsym("value"); s_performList = getsym("performList"); s_superPerformList = getsym("superPerformList"); s_performArgs = getsym("performArgs"); s_at = getsym("at"); s_put = getsym("put"); s_prstart = getsym("prStart"); s_series = getsym("prSimpleNumberSeries"); s_copyseries = getsym("copySeries"); s_putseries = getsym("putSeries"); s_envirGet = getsym("envirGet"); s_envirPut = getsym("envirPut"); // set special value slots SetSymbol(&o_none, s_none); SetNil(&o_nil); SetFalse(&o_false); SetTrue(&o_true); SetInt(&o_negone, -1); SetInt(&o_zero, 0); SetInt(&o_one, 1); SetInt(&o_two, 2); SetFloat(&o_fhalf, .5); SetFloat(&o_fnegone, -1.); SetFloat(&o_fzero, 0.); SetFloat(&o_fone, 1.); SetFloat(&o_ftwo, 2.); SetFloat(&o_inf, std::numeric_limits<double>::infinity()); slotCopy(&gSpecialValues[svNil], &o_nil); slotCopy(&gSpecialValues[svFalse], &o_false); slotCopy(&gSpecialValues[svTrue], &o_true); slotCopy(&gSpecialValues[svNegOne], &o_negone); slotCopy(&gSpecialValues[svZero], &o_zero); slotCopy(&gSpecialValues[svOne], &o_one); slotCopy(&gSpecialValues[svTwo], &o_two); slotCopy(&gSpecialValues[svFHalf], &o_fhalf); slotCopy(&gSpecialValues[svFNegOne], &o_fnegone); slotCopy(&gSpecialValues[svFZero], &o_fzero); slotCopy(&gSpecialValues[svFOne], &o_fone); slotCopy(&gSpecialValues[svFTwo], &o_ftwo); slotCopy(&gSpecialValues[svInf], &o_inf); gFormatElemSize[obj_notindexed] = sizeof(PyrSlot); gFormatElemSize[obj_slot] = sizeof(PyrSlot); gFormatElemSize[obj_double] = sizeof(double); gFormatElemSize[obj_float] = sizeof(float); gFormatElemSize[obj_int32] = sizeof(int32); gFormatElemSize[obj_int16] = sizeof(int16); gFormatElemSize[obj_int8] = sizeof(int8); gFormatElemSize[obj_char] = sizeof(char); gFormatElemSize[obj_symbol] = sizeof(PyrSymbol*); gFormatElemCapc[obj_notindexed] = sizeof(PyrSlot) / sizeof(PyrSlot); gFormatElemCapc[obj_slot] = sizeof(PyrSlot) / sizeof(PyrSlot); gFormatElemCapc[obj_double] = sizeof(PyrSlot) / sizeof(double); gFormatElemCapc[obj_float] = sizeof(PyrSlot) / sizeof(float); gFormatElemCapc[obj_int32] = sizeof(PyrSlot) / sizeof(int32); gFormatElemCapc[obj_int16] = sizeof(PyrSlot) / sizeof(int16); gFormatElemCapc[obj_int8] = sizeof(PyrSlot) / sizeof(int8); gFormatElemCapc[obj_char] = sizeof(PyrSlot) / sizeof(char); gFormatElemCapc[obj_symbol] = sizeof(PyrSlot) / sizeof(PyrSymbol*); gFormatElemTag[obj_notindexed] = -1; gFormatElemTag[obj_slot] = -1; gFormatElemTag[obj_double] = 0; gFormatElemTag[obj_float] = 0; gFormatElemTag[obj_int32] = tagInt; gFormatElemTag[obj_int16] = tagInt; gFormatElemTag[obj_int8] = tagInt; gFormatElemTag[obj_char] = tagChar; gFormatElemTag[obj_symbol] = tagSym; } const char* slotSymString(PyrSlot* slot) { switch (GetTag(slot)) { case tagObj: return slotRawSymbol(&slotRawObject(slot)->classptr->name)->name; case tagInt: return "Integer"; case tagChar: return "Char"; case tagSym: return slotRawSymbol(slot)->name; case tagNil: return "Nil"; case tagFalse: return "False"; case tagTrue: return "True"; default: return "<float>"; } } PyrClass* newClassObj(PyrClass* classObjSuperClass, PyrSymbol* className, PyrSymbol* superClassName, int numInstVars, int numClassVars, int numConsts, int numInstMethods, int instFormat, int instFlags) { PyrClass *classobj, *superclassobj; PyrObject* array; PyrSymbolArray* symarray; int classFlags; /*{ int c; c = className->name[0]; if (!(c >= 'A' && c <= 'Z')) Debugger(); }*/ // pyrmalloc: // lifetime: kill upon recompiling library classobj = (PyrClass*)pyr_pool_runtime->Alloc(sizeof(PyrClass)); MEMFAIL(classobj); classobj->size = (sizeof(PyrClass) - sizeof(PyrObjectHdr)) / sizeof(PyrSlot); classobj->prev = classobj->next = nullptr; classobj->obj_flags = obj_immutable; classobj->obj_format = obj_notindexed; classobj->gc_color = obj_permanent; classobj->obj_sizeclass = LOG2CEIL(classobj->size); classobj->classptr = classObjSuperClass; // append to the list of classes if (gClassList) SetObject(&classobj->nextclass, gClassList); else SetNil(&classobj->nextclass); gClassList = classobj; className->u.classobj = classobj; // postfl("> '%s' %d %d\n", className->name, className, classobj); SetSymbol(&classobj->name, className); if (superClassName) { SetSymbol(&classobj->superclass, superClassName); superclassobj = superClassName->u.classobj; } else { SetSymbol(&classobj->superclass, s_none); superclassobj = nullptr; } SetInt(&classobj->subclasses, 0); // to be filled with subclasses later // in the meantime it is used as a tally of subclasses so that its allocation // size can be known if (numInstMethods) { array = newPyrArray(nullptr, numInstMethods, obj_permanent | obj_immutable, false); SetObject(&classobj->methods, array); } else { SetNil(&classobj->methods); } if (numInstVars) { symarray = newPyrSymbolArray(nullptr, numInstVars, obj_permanent | obj_immutable, false); SetObject(&classobj->instVarNames, symarray); array = newPyrArray(nullptr, numInstVars, obj_permanent | obj_immutable, false); SetObject(&classobj->iprototype, array); nilSlots(array->slots, numInstVars); } else { SetNil(&classobj->instVarNames); SetNil(&classobj->iprototype); } if (numClassVars) { symarray = newPyrSymbolArray(nullptr, numClassVars, obj_permanent | obj_immutable, false); SetObject(&classobj->classVarNames, symarray); array = newPyrArray(nullptr, numClassVars, obj_permanent | obj_immutable, false); SetObject(&classobj->cprototype, array); nilSlots(array->slots, numClassVars); } else { SetNil(&classobj->classVarNames); SetNil(&classobj->cprototype); } if (numConsts) { symarray = newPyrSymbolArray(nullptr, numConsts, obj_permanent | obj_immutable, false); SetObject(&classobj->constNames, symarray); array = newPyrArray(nullptr, numConsts, obj_permanent | obj_immutable, false); SetObject(&classobj->constValues, array); nilSlots(array->slots, numConsts); } else { SetNil(&classobj->constNames); SetNil(&classobj->constValues); } classFlags = 0; if (instFormat != obj_notindexed) { classFlags |= classHasIndexableInstances; } SetInt(&classobj->instanceFormat, instFormat); SetInt(&classobj->instanceFlags, instFlags); SetInt(&classobj->classIndex, -1); SetInt(&classobj->classFlags, classFlags); SetInt(&classobj->maxSubclassIndex, 0); SetNil(&classobj->filenameSym); SetInt(&classobj->charPos, 0); SetInt(&classobj->classVarIndex, gNumClassVars); // if (numClassVars) post("%16s %4d %4d\n", className->name, gNumClassVars, numClassVars); gNumClassVars += numClassVars; return classobj; } void reallocClassObj(PyrClass* classobj, int numInstVars, int numClassVars, int numConsts, int numMethods, int instFormat, int instFlags) { PyrObject* array; PyrSymbolArray* symarray; PyrClass* superclassobj; freePyrSlot(&classobj->methods); freePyrSlot(&classobj->instVarNames); freePyrSlot(&classobj->classVarNames); freePyrSlot(&classobj->iprototype); freePyrSlot(&classobj->cprototype); freePyrSlot(&classobj->constNames); freePyrSlot(&classobj->constValues); if (numMethods) { array = newPyrArray(nullptr, numMethods, obj_permanent | obj_immutable, false); SetObject(&classobj->methods, array); } else { SetNil(&classobj->methods); } if (numInstVars) { // post("reallocClassObj %s numInstVars %d\n", slotRawSymbol(&classobj->name)->name, numInstVars); symarray = newPyrSymbolArray(nullptr, numInstVars, obj_permanent | obj_immutable, false); SetObject(&classobj->instVarNames, symarray); array = newPyrArray(nullptr, numInstVars, obj_permanent | obj_immutable, false); SetObject(&classobj->iprototype, array); nilSlots(array->slots, numInstVars); } else { SetNil(&classobj->instVarNames); SetNil(&classobj->iprototype); } if (numClassVars) { // post("reallocClassObj %s numClassVars %d\n", slotRawSymbol(&classobj->name)->name, numClassVars); symarray = newPyrSymbolArray(nullptr, numClassVars, obj_permanent | obj_immutable, false); SetObject(&classobj->classVarNames, symarray); nilSlots(array->slots, numClassVars); array = newPyrArray(nullptr, numClassVars, obj_permanent | obj_immutable, false); SetObject(&classobj->cprototype, array); nilSlots(array->slots, numClassVars); } else { SetNil(&classobj->classVarNames); SetNil(&classobj->cprototype); } if (numConsts) { // post("reallocClassObj %s numConsts %d\n", slotRawSymbol(&classobj->name)->name, numConsts); symarray = newPyrSymbolArray(nullptr, numConsts, obj_permanent | obj_immutable, false); SetObject(&classobj->constNames, symarray); array = newPyrArray(nullptr, numConsts, obj_permanent | obj_immutable, false); SetObject(&classobj->constValues, array); nilSlots(array->slots, numConsts); } else { SetNil(&classobj->constNames); SetNil(&classobj->constValues); } superclassobj = slotRawSymbol(&classobj->superclass)->u.classobj; SetInt(&classobj->instanceFormat, instFormat); SetInt(&classobj->instanceFlags, instFlags); SetInt(&classobj->classIndex, -1); } void fixClassArrays(PyrClass* classobj); void fixClassArrays(PyrClass* classobj) { if (IsObj(&classobj->methods)) slotRawObject(&classobj->methods)->classptr = class_array; if (IsObj(&classobj->instVarNames)) slotRawObject(&classobj->instVarNames)->classptr = class_symbolarray; if (IsObj(&classobj->classVarNames)) slotRawObject(&classobj->classVarNames)->classptr = class_symbolarray; if (IsObj(&classobj->iprototype)) slotRawObject(&classobj->iprototype)->classptr = class_array; if (IsObj(&classobj->cprototype)) slotRawObject(&classobj->cprototype)->classptr = class_array; } int numInstVars(PyrClass* classobj) { int res; if (IsNil(&classobj->instVarNames)) res = 0; else res = slotRawObject(&classobj->instVarNames)->size; return res; } int numClassVars(PyrClass* classobj) { int res; if (IsNil(&classobj->classVarNames)) res = 0; else res = slotRawObject(&classobj->classVarNames)->size; return res; } void objAddIndexedSlotGrow(PyrSlot* arraySlot, PyrSlot* addSlot); void objAddIndexedSlotGrow(PyrSlot* arraySlot, PyrSlot* addSlot) { PyrObject* obj; if (IsNil(arraySlot)) { PyrObject* newobj = (PyrObject*)newPyrArray(nullptr, 1, obj_permanent | obj_immutable, false); SetObject(arraySlot, newobj); obj = newobj; } else { obj = slotRawObject(arraySlot); if (obj->size >= ARRAYMAXINDEXSIZE(obj)) { // post("objAddIndexedSlotGrow\n"); PyrObject* newobj = (PyrObject*)newPyrArray(nullptr, obj->size * 2, obj_permanent | obj_immutable, false); memcpy(newobj->slots, obj->slots, obj->size * sizeof(PyrSlot)); newobj->size = obj->size; SetObject(arraySlot, newobj); pyr_pool_runtime->Free((void*)obj); obj = newobj; } } slotCopy(&obj->slots[obj->size++], addSlot); } void addMethod(PyrClass* classobj, PyrMethod* method) { PyrSlot slot; SetObject(&slot, method); objAddIndexedSlotGrow(&classobj->methods, &slot); } PyrMethod* classFindDirectMethod(PyrClass* classobj, PyrSymbol* name) { PyrMethod* method; PyrSlot* methods; int i, numMethods; if (IsNil(&classobj->methods)) return nullptr; methods = slotRawObject(&classobj->methods)->slots; numMethods = slotRawObject(&classobj->methods)->size; for (i = 0; i < numMethods; ++i) { method = slotRawMethod(&methods[i]); if (slotRawSymbol(&method->name) == name) break; } if (i >= numMethods) method = nullptr; return method; } int numSuperInstVars(PyrClass* superclassobj) { int superinstvars = 0; if (superclassobj) { if (IsObj(&superclassobj->iprototype)) { superinstvars = slotRawObject(&superclassobj->iprototype)->size; } } return superinstvars; } bool classFindInstVar(PyrClass* classobj, PyrSymbol* name, int* index) { PyrSymbolArray* ivnames; PyrSymbol* ivname; int i; if (NotNil(&classobj->instVarNames)) { ivnames = slotRawSymbolArray(&classobj->instVarNames); if (ivnames) { for (i = 0; i < ivnames->size; ++i) { ivname = ivnames->symbols[i]; if (ivname == name) { // numsupervars = numSuperInstVars(slotRawSymbol(&classobj->superclass)->u.classobj); //*index = numsupervars + i; *index = i; return true; } } } } return false; } int instVarOffset(const char* classname, const char* instvarname) { PyrSymbol *instvarsymbol, *classsymbol; PyrClass* classobj; int index; char c; classsymbol = getsym(classname); instvarsymbol = getsym(instvarname); c = classname[0]; if (!(c >= 'A' && c <= 'Z')) return -1; classobj = classsymbol->u.classobj; if (!classobj) return -1; if (!classFindInstVar(classobj, instvarsymbol, &index)) return -1; return index; } int classVarOffset(const char* classname, const char* classvarname, PyrClass** classobj) { PyrSymbol *classvarsymbol, *classsymbol; int index; char c; classsymbol = getsym(classname); classvarsymbol = getsym(classvarname); c = classname[0]; if (!(c >= 'A' && c <= 'Z')) return -1; *classobj = classsymbol->u.classobj; if (!*classobj) return -1; if (!classFindClassVar(classobj, classvarsymbol, &index)) return -1; return index; } bool classFindClassVar(PyrClass** classobj, PyrSymbol* name, int* index) { PyrSymbolArray* cvnames; PyrSymbol* cvname; int i, j; char* classname; PyrClass* localclassobj = *classobj; // if this is a Metaclass then we need to search its normal Class for // the class vars classname = slotRawSymbol(&localclassobj->name)->name; if (strncmp(classname, "Meta_", 5) == 0) { localclassobj = getsym(classname + 5)->u.classobj; } for (j = 0; localclassobj; ++j) { if (NotNil(&localclassobj->classVarNames)) { cvnames = slotRawSymbolArray(&localclassobj->classVarNames); if (cvnames) { for (i = 0; i < cvnames->size; ++i) { cvname = cvnames->symbols[i]; if (cvname == name) { *classobj = localclassobj; *index = i; return true; } } } } if (IsSym(&localclassobj->superclass)) { localclassobj = slotRawSymbol(&localclassobj->superclass)->u.classobj; } else { localclassobj = nullptr; } } return false; } bool classFindConst(PyrClass** classobj, PyrSymbol* name, int* index) { PyrSymbolArray* knames; PyrSymbol* kname; int i, j; char* classname; PyrClass* localclassobj = *classobj; // if this is a Metaclass then we need to search its normal Class for // the class vars classname = slotRawSymbol(&localclassobj->name)->name; if (strncmp(classname, "Meta_", 5) == 0) { localclassobj = getsym(classname + 5)->u.classobj; } for (j = 0; localclassobj; ++j) { if (NotNil(&localclassobj->constNames)) { knames = slotRawSymbolArray(&localclassobj->constNames); if (knames) { for (i = 0; i < knames->size; ++i) { kname = knames->symbols[i]; if (kname == name) { *classobj = localclassobj; *index = i; return true; } } } } if (IsSym(&localclassobj->superclass)) { localclassobj = slotRawSymbol(&localclassobj->superclass)->u.classobj; } else { localclassobj = nullptr; } } return false; } struct compareByName { bool operator()(PyrClass* lhs, PyrClass* rhs) const { return strcmp(slotRawSymbol(&lhs->name)->name, slotRawSymbol(&rhs->name)->name) < 0; } }; template <class T> class pyr_pool_compile_allocator { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class U> struct rebind { typedef pyr_pool_compile_allocator<U> other; }; pyr_pool_compile_allocator(void) {} template <class U> pyr_pool_compile_allocator(pyr_pool_compile_allocator<U> const&) {} pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type n, const void* hint = nullptr) { return (pointer)pyr_pool_compile->Alloc(n * sizeof(T)); } void deallocate(pointer p, size_type n) { pyr_pool_compile->Free(p); } void construct(pointer p, const T& val) { ::new (p) T(val); } void destroy(pointer p) { p->~T(); } }; /* sort list of classes: * we fill a binary search tree * */ static PyrClass* sortClasses(PyrClass* aClassList) { typedef std::set<PyrClass*, compareByName, pyr_pool_compile_allocator<PyrClass*>> classSetType; classSetType classSet; PyrClass* insertHead = aClassList; do { assert(classSet.find(insertHead) == classSet.end()); classSet.insert(insertHead); insertHead = slotRawClass(&insertHead->nextclass); } while (insertHead); classSetType::iterator it = classSet.begin(); PyrClass* sortedClasses = *it; ++it; PyrClass* lastClass = sortedClasses; for (; it != classSet.end(); ++it) { PyrClass* current = *it; SetObject(&lastClass->nextclass, (PyrObject*)current); lastClass = current; } SetNil(&lastClass->nextclass); return sortedClasses; } void buildClassTree() { // after all classes are compiled this function builds the tree and // indexes the classes // count subclasses // postfl("count subclasses\n"); PyrClass* classobj = gClassList; while (classobj) { PyrClass* superclassobj = slotRawSymbol(&classobj->superclass)->u.classobj; if (superclassobj) { // postfl(" superclassobj %s\n", slotRawSymbol(&superclassobj->name)->name); SetRaw(&superclassobj->subclasses, slotRawInt(&superclassobj->subclasses) + 1); } classobj = slotRawClass(&classobj->nextclass); } // allocate subclass arrays // postfl("allocate subclass arrays\n"); classobj = gClassList; while (classobj) { int numSubclasses; numSubclasses = slotRawInt(&classobj->subclasses); // postfl(" %s %d\n", slotRawSymbol(&classobj->name)->name, numSubclasses); if (numSubclasses) { SetObject(&classobj->subclasses, (PyrObject*)newPyrArray(nullptr, numSubclasses, obj_permanent | obj_immutable, false)); slotRawObject(&classobj->subclasses)->size = 0; } else { SetNil(&classobj->subclasses); } classobj = slotRawClass(&classobj->nextclass); } // fill in subclass arrays // postfl("fill in subclass arrays\n"); classobj = gClassList; while (classobj) { // postfl(" %s\n", slotRawSymbol(&classobj->name)->name); PyrClass* superclassobj = slotRawSymbol(&classobj->superclass)->u.classobj; if (superclassobj) { objAddIndexedObject(slotRawObject(&superclassobj->subclasses), (PyrObject*)classobj); // postfl(" superclassobj %s %d\n", slotRawSymbol(&superclassobj->name)->name, // slotRawObject(&superclassobj->subclasses)->size); } classobj = slotRawClass(&classobj->nextclass); } // alpha sort the classes via insertion sort gClassList = sortClasses(gClassList); } void indexClassTree(PyrClass* classobj, int numSuperMethods) { int i, numMethods; if (!classobj) return; SetInt(&classobj->classIndex, gNumClasses); gNumClasses++; if (IsObj(&classobj->methods)) { PyrObject* methods = slotRawObject(&classobj->methods); numMethods = methods->size; } else numMethods = 0; numMethods = numSuperMethods + numMethods; if (IsObj(&classobj->subclasses)) { PyrObject* subclasses = slotRawObject(&classobj->subclasses); for (i = 0; i < subclasses->size; ++i) indexClassTree(slotRawClass(&subclasses->slots[i]), numMethods); } SetInt(&classobj->maxSubclassIndex, gNumClasses - 1); } void findDiscrepancy(); void findDiscrepancy() { PyrClass *classobjA, *classobjB; classobjA = gClassList; while (classobjA) { classobjB = slotRawClass(&classobjA->nextclass); ; while (classobjB) { if (slotRawSymbol(&classobjA->name) == slotRawSymbol(&classobjB->name)) { post("duplicate %s\n", slotRawSymbol(&classobjA->name)->name); } classobjB = slotRawClass(&classobjB->nextclass); } classobjA = slotRawClass(&classobjA->nextclass); } } static void indent(int n) { for (int i = 0; i < n; ++i) { post(" "); } } void postClassTree(PyrClass* classobj, int level) { PyrObject* subclasses; int i; // post("%4d ", slotRawInt(&classobj->classIndex)); indent(level); post("%s\n", slotRawSymbol(&classobj->name)->name); if (classobj == class_class) { indent(level + 1); post(" [.. all metaclasses ..]\n"); } else { if (IsNil(&classobj->subclasses)) return; // FIXME: can we initialize subclasses with a NULL pointer? subclasses = slotRawObject(&classobj->subclasses); if (subclasses) { // determine if can put on one line bool oneline = subclasses->size <= 5; for (i = 0; oneline && i < subclasses->size; ++i) { PyrClass* subclassobj = slotRawClass(&subclasses->slots[i]); if (IsObj(&subclassobj->subclasses)) // FIXME: shall we do a null-pointer check? oneline = false; } if (oneline) { indent(level + 1); post("["); for (i = 0; i < subclasses->size; ++i) { PyrClass* subclassobj = slotRawClass(&subclasses->slots[i]); post(" %s", slotRawSymbol(&subclassobj->name)->name); } post(" ]\n"); } else { indent(level); post("[\n"); for (i = 0; i < subclasses->size; ++i) { postClassTree(slotRawClass(&subclasses->slots[i]), level + 1); } indent(level); post("]\n"); } } } } void setSelectorFlags() { int i; PyrClass* classobj = gClassList; while (classobj) { if (IsObj(&classobj->methods)) { PyrObject* methods = slotRawObject(&classobj->methods); for (i = 0; i < methods->size; ++i) { PyrMethod* method = slotRawMethod(&methods->slots[i]); slotRawSymbol(&method->name)->flags |= sym_Selector; // if (method->methType == methRedirect) { // post("rd: %3d %s:%s\n", k++, slotRawSymbol(&classobj->name)->name, // slotRawSymbol(&method->name)->name); //} } } classobj = slotRawClass(&classobj->nextclass); } // count selectors gNumSelectors = 0; SymbolTable* symbolTable = gMainVMGlobals->symbolTable; for (int i = 0; i < symbolTable->TableSize(); ++i) { PyrSymbol* sym = symbolTable->Get(i); if (sym && (sym->flags & sym_Selector)) { sym->u.index = gNumSelectors++; } } // post("gNumSelectors %d\n", gNumSelectors); } // the chunky stuff can be commented back in for implementing a better // compression scheme. The Q&D method works fine for my small class tree for now. typedef struct { PyrSymbol* selector; int minClassIndex; int maxClassIndex; int rowWidth; // int largestChunk; // int chunkOffset; int selectorIndex; int population; int rowOffset; } ColumnDescriptor; int compareColDescs(const void* va, const void* vb); int compareColDescs(const void* va, const void* vb) { ColumnDescriptor* a = (ColumnDescriptor*)va; ColumnDescriptor* b = (ColumnDescriptor*)vb; int diff; // diff = b->largestChunk - a->largestChunk; // if (diff != 0) return diff; diff = b->rowWidth - a->rowWidth; if (diff != 0) return diff; // diff = b->chunkOffset - a->chunkOffset; diff = b->minClassIndex - a->minClassIndex; return diff; } #define CHECK_METHOD_LOOKUP_TABLE_BUILD_TIME 0 #if CHECK_METHOD_LOOKUP_TABLE_BUILD_TIME double elapsedTime(); #endif #ifdef _MSC_VER static size_t fillClassRows(const PyrClass* classobj, PyrMethod** bigTable); #else static size_t fillClassRows(const PyrClass* classobj, PyrMethod** bigTable, boost::basic_thread_pool& pool); #endif static void binsortClassRows(PyrMethod const** bigTable, const ColumnDescriptor* sels, size_t numSelectors, size_t begin, size_t end) { // bin sort the class rows to the new ordering // post("reorder rows\n"); const int allocaThreshold = 16384; PyrMethod** temprow = (numSelectors < allocaThreshold) ? (PyrMethod**)alloca(numSelectors * sizeof(PyrMethod*)) : (PyrMethod**)malloc(numSelectors * sizeof(PyrMethod*)); for (int j = begin; j < end; ++j) { PyrMethod const** row = bigTable + j * numSelectors; memcpy(temprow, row, numSelectors * sizeof(PyrMethod*)); #pragma GCC ivdep for (int i = 0; i < numSelectors; ++i) row[i] = temprow[sels[i].selectorIndex]; } if (numSelectors >= allocaThreshold) free(temprow); } static ColumnDescriptor* prepareColumnTable(ColumnDescriptor* sels, int numSelectors) { // fill selector table // post("fill selector table\n"); SymbolTable* symbolTable = gMainVMGlobals->symbolTable; int selectorTableIndex = 0; for (int i : boost::irange(0, symbolTable->TableSize())) { PyrSymbol* sym = symbolTable->Get(i); if (sym && (sym->flags & sym_Selector)) sels[selectorTableIndex++].selector = sym; } assert(selectorTableIndex == numSelectors); for (int i = 0; i < numSelectors; ++i) { // postfl("%3d %s\n", i, sels[i].selector->name); sels[i].minClassIndex = INT_MAX; sels[i].maxClassIndex = 0; // sels[i].largestChunk = 0; // sels[i].chunkOffset = 0; sels[i].selectorIndex = i; sels[i].population = 0; } return sels; } static void calcRowStats(PyrMethod const* const* bigTable, ColumnDescriptor* sels, int numClasses, int numSelectors, int begin, int end) { // chunkSize = 0; // chunkOffset = 0; for (int classIndex = 0; classIndex < numClasses; ++classIndex) { for (int selectorIndex = begin; selectorIndex < end; ++selectorIndex) { PyrMethod const* method = bigTable[classIndex * numSelectors + selectorIndex]; if (method) { // classobj = method->ownerclass.uoc; if (classIndex > sels[selectorIndex].maxClassIndex) sels[selectorIndex].maxClassIndex = classIndex; if (classIndex < sels[selectorIndex].minClassIndex) sels[selectorIndex].minClassIndex = classIndex; sels[selectorIndex].population++; // if (chunkSize == 0) chunkOffset = j; // chunkSize++; // postfl(" %8s %3d %3d %3d %3d\n", slotRawSymbol(&classobj->name)->name, i, j, // chunkSize, slotRawInt(&classobj->classIndex)); //} else { // if (chunkSize > sels[i].largestChunk) { // sels[i].largestChunk = chunkSize; // sels[i].chunkOffset = chunkOffset; //} // chunkSize = 0; } } } for (int i = begin; i < end; ++i) sels[i].rowWidth = sels[i].maxClassIndex - sels[i].minClassIndex + 1; } void buildBigMethodMatrix() { PyrMethod **bigTable, **row; PyrClass** classes; int j, k; int popSum, widthSum; int rowOffset, freeIndex; int rowTableSize; int bigTableSize; const size_t numSelectors = gNumSelectors; const size_t numClasses = gNumClasses; // post("allocate arrays\n"); #if CHECK_METHOD_LOOKUP_TABLE_BUILD_TIME double t0 = elapsedTime(); #endif const int hw_concurrency = SC_Thread::hardware_concurrency(); const int cpuCount = hw_concurrency > 0 ? hw_concurrency : 1; const int helperThreadCount = cpuCount > 1 ? cpuCount - 1 : 1; boost::basic_thread_pool pool(helperThreadCount); // pyrmalloc: // lifetime: kill after compile bigTableSize = numSelectors * numClasses; // post("bigTableSize %d %d %d\n", bigTableSize, numSelectors, numClasses); ColumnDescriptor* sels = (ColumnDescriptor*)pyr_pool_compile->Alloc(numSelectors * sizeof(ColumnDescriptor)); MEMFAIL(sels); #ifdef _MSC_VER auto filledSelectorsFuture = std::async(std::launch::deferred, std::bind(&prepareColumnTable, sels, numSelectors)); #else auto filledSelectorsFuture = boost::async(pool, std::bind(&prepareColumnTable, sels, numSelectors)); #endif classes = (PyrClass**)pyr_pool_compile->Alloc(numClasses * sizeof(PyrClass*)); MEMFAIL(classes); auto fillClassIndices = [](PyrClass** classes) { PyrClass* classobj = gClassList; while (classobj) { classes[slotRawInt(&classobj->classIndex)] = classobj; classobj = slotRawClass(&classobj->nextclass); } return classes; }; #ifdef _MSC_VER auto filledClassIndices = std::async(std::launch::deferred, fillClassIndices, classes); #else auto filledClassIndices = boost::async(pool, fillClassIndices, classes); #endif bigTable = (PyrMethod**)pyr_pool_compile->Alloc(bigTableSize * sizeof(PyrMethod*)); MEMFAIL(bigTable); #ifndef _MSC_VER pool.try_executing_one(); #endif filledClassIndices.wait(); #ifdef _MSC_VER size_t numentries = fillClassRows(class_object, bigTable); #else size_t numentries = fillClassRows(class_object, bigTable, pool); #endif post("\tnumentries = %lu / %d = %.2g\n", numentries, bigTableSize, (double)numentries / (double)bigTableSize); ColumnDescriptor* filledSelectors = filledSelectorsFuture.get(); #ifdef _MSC_VER std::vector<std::future<void>> columnDescriptorsWithStats; #else std::vector<boost::future<void>> columnDescriptorsWithStats; #endif size_t selectorsPerJob = numSelectors / cpuCount / 2; for (size_t beginSelectorIndex : boost::irange(selectorsPerJob, numSelectors, selectorsPerJob)) { size_t endSelectorIndex = std::min(beginSelectorIndex + selectorsPerJob, numSelectors); #ifdef _MSC_VER auto future = std::async(std::launch::deferred, calcRowStats, bigTable, filledSelectors, numClasses, numSelectors, beginSelectorIndex, endSelectorIndex); #else auto future = boost::async(pool, calcRowStats, bigTable, filledSelectors, numClasses, numSelectors, beginSelectorIndex, endSelectorIndex); #endif columnDescriptorsWithStats.push_back(std::move(future)); } calcRowStats(bigTable, filledSelectors, numClasses, numSelectors, 0, std::min(selectorsPerJob, numSelectors)); for (auto& future : columnDescriptorsWithStats) { #ifdef _MSC_VER future.wait(); #else while (!future.is_ready()) pool.schedule_one_or_yield(); #endif } // post("qsort\n"); // sort rows by largest chunk, then by width, then by chunk offset #if 0 // not yet __gnu_parallel::sort(sels, sels + numSelectors, [](ColumnDescriptor const & rhs, ColumnDescriptor const & lhs) { return compareColDescs(&rhs, &lhs) < 0; }); #else std::sort(sels, sels + numSelectors, [](ColumnDescriptor const& rhs, ColumnDescriptor const& lhs) { return compareColDescs(&rhs, &lhs) < 0; }); #endif // bin sort the class rows to the new ordering // post("reorder rows\n"); #ifdef _MSC_VER std::vector<std::future<void>> binsortedClassRowFuture; #else std::vector<boost::future<void>> binsortedClassRowFuture; #endif size_t classesPerJob = numClasses / cpuCount / 2; for (size_t beginClassIndex : boost::irange(classesPerJob, numClasses, classesPerJob)) { size_t endClassIndex = std::min(beginClassIndex + classesPerJob, numClasses); #ifdef _MSC_VER auto future = std::async(std::launch::deferred, binsortClassRows, (PyrMethod const**)bigTable, sels, numSelectors, beginClassIndex, endClassIndex); #else auto future = boost::async(pool, binsortClassRows, (PyrMethod const**)bigTable, sels, numSelectors, beginClassIndex, endClassIndex); #endif binsortedClassRowFuture.push_back(std::move(future)); } binsortClassRows((PyrMethod const**)bigTable, sels, numSelectors, 0, std::min(classesPerJob, numClasses)); for (auto& future : binsortedClassRowFuture) { #ifdef _MSC_VER future.wait(); #else while (!future.is_ready()) pool.schedule_one_or_yield(); #endif } // post("calc row offsets %d\n", numSelectors); widthSum = 0; popSum = 0; freeIndex = 0; rowOffset = -1; for (int i = 0; i < numSelectors; ++i) { widthSum += sels[i].rowWidth; popSum += sels[i].population; rowOffset = sc_max(rowOffset + 1, freeIndex - sels[i].minClassIndex); freeIndex = rowOffset + sels[i].maxClassIndex + 1; sels[i].rowOffset = rowOffset; sels[i].selector->u.index = rowOffset; // post("%3d %24s %3d %5d %5d\n", i, sels[i].selector->name, // sels[i].rowWidth, rowOffset, freeIndex); } // post("alloc row table %d\n", freeIndex); rowTableSize = (freeIndex + numClasses) * sizeof(PyrMethod*); gRowTable = (PyrMethod**)pyr_pool_runtime->Alloc(rowTableSize); MEMFAIL(gRowTable); // having the method ptr always be valid saves a branch in SendMessage() for (int i = 0; i < freeIndex + numClasses; ++i) gRowTable[i] = gNullMethod; // post("fill compressed table\n"); //{ FILE* fp; // newPyrMethod // fp = fopen("meth table", "w"); for (int i = 0; i < numSelectors; ++i) { int offset, maxwidth; offset = sels[i].rowOffset + sels[i].minClassIndex; maxwidth = offset + sels[i].rowWidth; row = bigTable + sels[i].minClassIndex * numSelectors + i; PyrMethod** table = gRowTable; for (j = offset, k = 0; j < maxwidth; ++j, k += numSelectors) { if (row[k]) table[j] = row[k]; } } // fclose(fp); //} for (int i = 0; i < freeIndex + numClasses; ++i) assert(gRowTable[i]); // post("freeIndex %d\n", freeIndex); // post("widthSum %d\n", widthSum); // post("popSum %d\n", popSum); #if CHECK_METHOD_LOOKUP_TABLE_BUILD_TIME post("building table took %.3g seconds\n", elapsedTime() - t0); { int numFilled = 0; for (int i = 0; i < rowTableSize / sizeof(PyrMethod*); ++i) { if (gRowTable[i] != gNullMethod) numFilled++; } post("Filled %d of %d = %f percent\n", numFilled, rowTableSize / sizeof(PyrMethod*), 100. * (double)numFilled / (rowTableSize / sizeof(PyrMethod*))); } #endif post("\t%d method selectors, %d classes\n", numSelectors, numClasses); post("\tmethod table size %d bytes, ", rowTableSize); post("big table size %d\n", numSelectors * numClasses * sizeof(PyrMethod*)); // postfl("%p %p %p\n", classes, bigTable, sels); /* // not necessary since the entire pool will be freed.. pyr_pool_compile->Free(classes); pyr_pool_compile->Free(bigTable); pyr_pool_compile->Free(sels); */ } #ifdef _MSC_VER static size_t fillClassRow(const PyrClass* classobj, PyrMethod** bigTable) #else static size_t fillClassRow(const PyrClass* classobj, PyrMethod** bigTable, boost::basic_thread_pool& pool) #endif { size_t count = 0; PyrMethod** myrow = bigTable + slotRawInt(&classobj->classIndex) * gNumSelectors; PyrClass* superclassobj = slotRawSymbol(&classobj->superclass)->u.classobj; if (superclassobj) { PyrMethod** superrow = bigTable + slotRawInt(&superclassobj->classIndex) * gNumSelectors; #pragma GCC ivdep for (int i = 0; i != gNumSelectors; ++i) { myrow[i] = superrow[i]; if (superrow[i]) ++count; } } else { memset(myrow, 0, gNumSelectors * sizeof(PyrMethod*)); } if (IsObj(&classobj->methods)) { PyrObject* methods = const_cast<PyrObject*>(slotRawObject(&classobj->methods)); // postfl(" %d\n", methods->size); for (int i = 0; i < methods->size; ++i) { PyrMethod* method = slotRawMethod(&methods->slots[i]); int selectorIndex = slotRawSymbol(&method->name)->u.index; if (myrow[selectorIndex] == nullptr) ++count; myrow[selectorIndex] = method; } } size_t result = count; if (IsObj(&classobj->subclasses)) { const PyrObject* subclasses = slotRawObject(&classobj->subclasses); int numSubclasses = subclasses->size; if (numSubclasses) { #ifdef _MSC_VER if (numSubclasses <= 2) { for (int subClassIndex : boost::irange(0, numSubclasses)) result += fillClassRow(slotRawClass(&subclasses->slots[subClassIndex]), bigTable); } else { typedef std::vector<std::future<size_t>> VectorOfFutures; VectorOfFutures subclassResults; for (int subClassIndex : boost::irange(1, numSubclasses)) { auto subclassResult = std::async(std::launch::deferred, fillClassRow, slotRawClass(&subclasses->slots[subClassIndex]), bigTable); subclassResults.emplace_back(std::move(subclassResult)); } result += fillClassRow(slotRawClass(&subclasses->slots[0]), bigTable); for (auto& subclassResult : subclassResults) { result += subclassResult.get(); } } #else if (numSubclasses <= 2) { for (int subClassIndex : boost::irange(0, numSubclasses)) result += fillClassRow(slotRawClass(&subclasses->slots[subClassIndex]), bigTable, pool); } else { typedef std::vector<boost::future<size_t>> VectorOfFutures; VectorOfFutures subclassResults; for (int subClassIndex : boost::irange(1, numSubclasses)) { auto subclassResult = boost::async(pool, fillClassRow, slotRawClass(&subclasses->slots[subClassIndex]), bigTable, boost::ref(pool)); subclassResults.emplace_back(std::move(subclassResult)); } result += fillClassRow(slotRawClass(&subclasses->slots[0]), bigTable, pool); for (auto& subclassResult : subclassResults) { while (!subclassResult.is_ready()) pool.schedule_one_or_yield(); result += subclassResult.get(); } } #endif } } return result; } #ifdef _MSC_VER static size_t fillClassRows(const PyrClass* classobj, PyrMethod** bigTable) { return fillClassRow(classobj, bigTable); } #else static size_t fillClassRows(const PyrClass* classobj, PyrMethod** bigTable, boost::basic_thread_pool& pool) { return fillClassRow(classobj, bigTable, pool); } #endif bool funcFindArg(PyrBlock* func, PyrSymbol* name, int* index) { int i; for (i = 0; i < slotRawSymbolArray(&func->argNames)->size; ++i) { if (slotRawSymbolArray(&func->argNames)->symbols[i] == name) { *index = i; return true; } } return false; } bool funcFindVar(PyrBlock* func, PyrSymbol* name, int* index) { int i; for (i = 0; i < slotRawSymbolArray(&func->varNames)->size; ++i) { if (slotRawSymbolArray(&func->varNames)->symbols[i] == name) { *index = i; return true; } } return false; } PyrClass* makeIntrinsicClass(PyrSymbol* className, PyrSymbol* superClassName, int numInstVars, int numClassVars) { PyrClass* superClass = nullptr; PyrClass* metaSuperClass = nullptr; PyrSymbol* metaClassName = nullptr; PyrSymbol* metaSuperClassName = nullptr; PyrClass* classobj = nullptr; PyrClass* metaclassobj = nullptr; int superInstVars; // postfl("makeIntrinsicClass '%s'\n", className->name); if (superClassName) { superClass = superClassName->u.classobj; if (!superClass) { error("Can't find superclass '%s' of '%s'\n", superClassName->name, className->name); return nullptr; } metaSuperClassName = getmetasym(superClassName->name); metaSuperClass = metaSuperClassName->u.classobj; superInstVars = numSuperInstVars(superClass); } else { // else it must be Object and so has no superclass metaSuperClassName = nullptr; superInstVars = 0; } metaClassName = getmetasym(className->name); metaClassName->flags |= sym_MetaClass; metaclassobj = newClassObj(class_class, metaClassName, metaSuperClassName, classClassNumInstVars, 0, 0, 0, obj_notindexed, 0); SetInt(&metaclassobj->classFlags, slotRawInt(&metaclassobj->classFlags) | classIsIntrinsic); if (metaSuperClassName && classClassNumInstVars) { memcpy(slotRawObject(&metaclassobj->iprototype)->slots, slotRawObject(&metaSuperClass->iprototype)->slots, sizeof(PyrSlot) * classClassNumInstVars); memcpy(slotRawSymbolArray(&metaclassobj->instVarNames)->symbols, slotRawSymbolArray(&metaSuperClass->instVarNames)->symbols, sizeof(PyrSymbol*) * classClassNumInstVars); slotRawObject(&metaclassobj->iprototype)->size = classClassNumInstVars; slotRawObject(&metaclassobj->instVarNames)->size = classClassNumInstVars; // dumpObject((PyrObject*)metaclassobj); } classobj = newClassObj(metaclassobj, className, superClassName, numInstVars + superInstVars, numClassVars, 0, 0, obj_notindexed, 0); SetInt(&classobj->classFlags, slotRawInt(&classobj->classFlags) | classIsIntrinsic); // postfl("%s:%s : %d\n", className->name, superClassName->name, superInstVars); if (superClass && superInstVars) { memcpy(slotRawObject(&classobj->iprototype)->slots, slotRawObject(&superClass->iprototype)->slots, sizeof(PyrSlot) * superInstVars); memcpy(slotRawSymbolArray(&classobj->instVarNames)->symbols, slotRawSymbolArray(&superClass->instVarNames)->symbols, sizeof(PyrSymbol*) * superInstVars); slotRawObject(&classobj->iprototype)->size = superInstVars; slotRawObject(&classobj->instVarNames)->size = superInstVars; } return classobj; } void addIntrinsicVar(PyrClass* classobj, const char* varName, PyrSlot* slot) { // postfl("%s %s %d\n", slotRawSymbol(&classobj->name)->name, varName, // slotRawObject(&classobj->instVarNames)->size); objAddIndexedSymbol(slotRawSymbolArray(&classobj->instVarNames), getsym(varName)); objAddIndexedSlot(slotRawObject(&classobj->iprototype), slot); } void addIntrinsicClassVar(PyrClass* classobj, const char* varName, PyrSlot* slot); void addIntrinsicClassVar(PyrClass* classobj, const char* varName, PyrSlot* slot) { // postfl("%s %s %d\n", slotRawSymbol(&classobj->name)->name, varName, // slotRawObject(&classobj->instVarNames)->size); objAddIndexedSymbol(slotRawSymbolArray(&classobj->classVarNames), getsym(varName)); objAddIndexedSlot(slotRawObject(&classobj->cprototype), slot); } void initClasses() { PyrClass* class_object_meta; PyrMethodRaw* methraw; // BOOTSTRAP THE OBJECT HIERARCHY gNumClassVars = 0; gClassList = nullptr; gNullMethod = newPyrMethod(); SetSymbol(&gNullMethod->name, (PyrSymbol*)nullptr); methraw = METHRAW(gNullMethod); methraw->methType = methNormal; // build intrinsic classes class_class = nullptr; class_object = makeIntrinsicClass(s_object, nullptr, 0, 4); class_class = makeIntrinsicClass(s_class, s_object, classClassNumInstVars, 1); // now fix class_class ptrs that were just previously installed erroneously class_object->classptr->classptr = class_class; class_class->classptr->classptr = class_class; class_object_meta = class_object->classptr; class_object_meta->superclass = class_class->name; addIntrinsicClassVar(class_object, "dependantsDictionary", &o_nil); addIntrinsicClassVar(class_object, "currentEnvironment", &o_nil); addIntrinsicClassVar(class_object, "topEnvironment", &o_nil); addIntrinsicClassVar(class_object, "uniqueMethods", &o_nil); // declare varNames for Class addIntrinsicVar(class_class, "name", &o_nil); addIntrinsicVar(class_class, "nextclass", &o_nil); addIntrinsicVar(class_class, "superclass", &o_nil); addIntrinsicVar(class_class, "subclasses", &o_nil); addIntrinsicVar(class_class, "methods", &o_nil); addIntrinsicVar(class_class, "instVarNames", &o_nil); addIntrinsicVar(class_class, "classVarNames", &o_nil); addIntrinsicVar(class_class, "iprototype", &o_nil); addIntrinsicVar(class_class, "cprototype", &o_nil); addIntrinsicVar(class_class, "constNames", &o_nil); addIntrinsicVar(class_class, "constValues", &o_nil); addIntrinsicVar(class_class, "instanceFormat", &o_nil); addIntrinsicVar(class_class, "instanceFlags", &o_zero); addIntrinsicVar(class_class, "classIndex", &o_zero); addIntrinsicVar(class_class, "classFlags", &o_zero); addIntrinsicVar(class_class, "maxSubclassIndex", &o_zero); addIntrinsicVar(class_class, "filenameSymbol", &o_nil); addIntrinsicVar(class_class, "charPos", &o_zero); addIntrinsicVar(class_class, "classVarIndex", &o_zero); addIntrinsicClassVar(class_class, "classesInited", &o_nil); // class_object_meta's inst var names need to be copied from class_class // because class_class didn't exist when it was created memcpy(slotRawObject(&class_object_meta->iprototype)->slots, slotRawObject(&class_class->iprototype)->slots, sizeof(PyrSlot) * classClassNumInstVars); memcpy(slotRawSymbolArray(&class_object_meta->instVarNames)->symbols, slotRawSymbolArray(&class_class->instVarNames)->symbols, sizeof(PyrSymbol*) * classClassNumInstVars); memcpy(slotRawObject(&class_class->classptr->iprototype)->slots, slotRawObject(&class_class->iprototype)->slots, sizeof(PyrSlot) * classClassNumInstVars); memcpy(slotRawSymbolArray(&class_class->classptr->instVarNames)->symbols, slotRawSymbolArray(&class_class->instVarNames)->symbols, sizeof(PyrSymbol*) * classClassNumInstVars); // OK the next thing I need is arrays.. class_collection = makeIntrinsicClass(s_collection, s_object, 0, 0); class_sequenceable_collection = makeIntrinsicClass(s_sequenceable_collection, s_collection, 0, 0); class_arrayed_collection = makeIntrinsicClass(s_arrayed_collection, s_sequenceable_collection, 0, 0); class_array = makeIntrinsicClass(s_array, s_arrayed_collection, 0, 0); SetInt(&class_array->instanceFormat, obj_slot); SetInt(&class_array->classFlags, slotRawInt(&class_array->classFlags) | classHasIndexableInstances); // now fix array classptrs in already created classes fixClassArrays(class_class); fixClassArrays(class_class->classptr); fixClassArrays(class_object_meta); fixClassArrays(class_collection); fixClassArrays(class_sequenceable_collection); fixClassArrays(class_arrayed_collection); fixClassArrays(class_array); class_fundef = makeIntrinsicClass(s_fundef, s_object, 10, 0); // declare varNames for Block addIntrinsicVar(class_fundef, "raw1", &o_nil); addIntrinsicVar(class_fundef, "raw2", &o_nil); addIntrinsicVar(class_fundef, "code", &o_nil); addIntrinsicVar(class_fundef, "selectors", &o_nil); addIntrinsicVar(class_fundef, "constants", &o_nil); addIntrinsicVar(class_fundef, "prototypeFrame", &o_nil); addIntrinsicVar(class_fundef, "context", &o_nil); addIntrinsicVar(class_fundef, "argNames", &o_nil); addIntrinsicVar(class_fundef, "varNames", &o_nil); addIntrinsicVar(class_fundef, "sourceCode", &o_nil); class_method = makeIntrinsicClass(s_method, s_fundef, 5, 0); addIntrinsicVar(class_method, "ownerClass", &o_nil); addIntrinsicVar(class_method, "name", &o_nil); addIntrinsicVar(class_method, "primitiveName", &o_nil); addIntrinsicVar(class_method, "filenameSymbol", &o_nil); addIntrinsicVar(class_method, "charPos", &o_zero); // addIntrinsicVar(class_method, "byteMeter", &o_zero); // addIntrinsicVar(class_method, "callMeter", &o_zero); class_frame = makeIntrinsicClass(s_frame, s_object, 0, 0); SetInt(&class_frame->classFlags, slotRawInt(&class_frame->classFlags) | classHasIndexableInstances); // addIntrinsicVar(class_frame, "method", &o_nil); // addIntrinsicVar(class_frame, "caller", &o_nil); // addIntrinsicVar(class_frame, "context", &o_nil); // addIntrinsicVar(class_frame, "homeContext", &o_nil); // addIntrinsicVar(class_frame, "ip", &o_nil); class_process = makeIntrinsicClass(s_process, s_object, 6, 0); addIntrinsicVar(class_process, "classVars", &o_nil); addIntrinsicVar(class_process, "interpreter", &o_nil); addIntrinsicVar(class_process, "curThread", &o_nil); addIntrinsicVar(class_process, "mainThread", &o_nil); addIntrinsicVar(class_process, "schedulerQueue", &o_nil); addIntrinsicVar(class_process, "nowExecutingPath", &o_nil); class_interpreter = makeIntrinsicClass(s_interpreter, s_object, 29, 0); addIntrinsicVar(class_interpreter, "cmdLine", &o_nil); addIntrinsicVar(class_interpreter, "context", &o_nil); for (int i = 0; i < 26; ++i) { char name[2]; name[0] = 'a' + i; name[1] = 0; addIntrinsicVar(class_interpreter, name, &o_nil); } addIntrinsicVar(class_interpreter, "codeDump", &o_nil); addIntrinsicVar(class_interpreter, "preProcessor", &o_nil); class_absfunc = makeIntrinsicClass(s_absfunc, s_object, 0, 0); class_stream = makeIntrinsicClass(s_stream, s_absfunc, 0, 0); class_thread = makeIntrinsicClass(s_thread, s_stream, 27, 0); addIntrinsicVar(class_thread, "state", &o_nil); addIntrinsicVar(class_thread, "func", &o_nil); addIntrinsicVar(class_thread, "stack", &o_nil); addIntrinsicVar(class_thread, "method", &o_nil); addIntrinsicVar(class_thread, "block", &o_nil); addIntrinsicVar(class_thread, "frame", &o_nil); addIntrinsicVar(class_thread, "ip", &o_zero); addIntrinsicVar(class_thread, "sp", &o_zero); addIntrinsicVar(class_thread, "numpop", &o_zero); addIntrinsicVar(class_thread, "receiver", &o_nil); addIntrinsicVar(class_thread, "numArgsPushed", &o_zero); addIntrinsicVar(class_thread, "parent", &o_nil); addIntrinsicVar(class_thread, "terminalValue", &o_nil); addIntrinsicVar(class_thread, "primitiveError", &o_zero); addIntrinsicVar(class_thread, "primitiveIndex", &o_zero); addIntrinsicVar(class_thread, "randData", &o_zero); addIntrinsicVar(class_thread, "beats", &o_fzero); addIntrinsicVar(class_thread, "seconds", &o_fzero); addIntrinsicVar(class_thread, "clock", &o_nil); addIntrinsicVar(class_thread, "nextBeat", &o_nil); addIntrinsicVar(class_thread, "endBeat", &o_nil); addIntrinsicVar(class_thread, "endValue", &o_nil); addIntrinsicVar(class_thread, "environment", &o_nil); addIntrinsicVar(class_thread, "exceptionHandler", &o_nil); addIntrinsicVar(class_thread, "threadPlayer", &o_nil); addIntrinsicVar(class_thread, "executingPath", &o_nil); addIntrinsicVar(class_thread, "oldExecutingPath", &o_nil); addIntrinsicVar(class_thread, "rescheduledTime", &o_nil); class_finalizer = makeIntrinsicClass(s_finalizer, s_object, 2, 0); addIntrinsicVar(class_finalizer, "cFunction", &o_nil); addIntrinsicVar(class_finalizer, "object", &o_nil); class_routine = makeIntrinsicClass(s_routine, s_thread, 0, 0); class_symbol = makeIntrinsicClass(s_symbol, s_object, 0, 0); class_nil = makeIntrinsicClass(s_nil, s_object, 0, 0); class_boolean = makeIntrinsicClass(s_boolean, s_object, 0, 0); class_true = makeIntrinsicClass(s_true, s_boolean, 0, 0); class_false = makeIntrinsicClass(s_false, s_boolean, 0, 0); class_magnitude = makeIntrinsicClass(s_magnitude, s_object, 0, 0); class_char = makeIntrinsicClass(s_char, s_magnitude, 0, 0); class_number = makeIntrinsicClass(s_number, s_magnitude, 0, 0); class_simple_number = makeIntrinsicClass(s_simple_number, s_number, 0, 0); class_int = makeIntrinsicClass(s_int, s_simple_number, 0, 0); class_float = makeIntrinsicClass(s_float, s_simple_number, 0, 0); class_rawptr = makeIntrinsicClass(s_rawptr, s_object, 0, 0); /* class_complex = makeIntrinsicClass(s_complex, s_number, 2, 0); addIntrinsicVar(class_complex, "real", &o_nil); addIntrinsicVar(class_complex, "imag", &o_nil); */ class_rawarray = makeIntrinsicClass(s_rawarray, s_arrayed_collection, 0, 0); // SetInt(&class_rawarray->instanceFormat, obj_int8); // slotRawInt(&class_rawarray->classFlags) |= classHasIndexableInstances; class_int8array = makeIntrinsicClass(s_int8array, s_rawarray, 0, 0); SetInt(&class_int8array->instanceFormat, obj_int8); SetInt(&class_int8array->classFlags, slotRawInt(&class_int8array->classFlags) | classHasIndexableInstances); class_int16array = makeIntrinsicClass(s_int16array, s_rawarray, 0, 0); SetInt(&class_int16array->instanceFormat, obj_int16); SetInt(&class_int16array->classFlags, slotRawInt(&class_int16array->classFlags) | classHasIndexableInstances); class_int32array = makeIntrinsicClass(s_int32array, s_rawarray, 0, 0); SetInt(&class_int32array->instanceFormat, obj_int32); SetInt(&class_int32array->classFlags, slotRawInt(&class_int32array->classFlags) | classHasIndexableInstances); class_symbolarray = makeIntrinsicClass(s_symbolarray, s_rawarray, 0, 0); SetInt(&class_symbolarray->instanceFormat, obj_symbol); SetInt(&class_symbolarray->classFlags, slotRawInt(&class_symbolarray->classFlags) | classHasIndexableInstances); class_string = makeIntrinsicClass(s_string, s_rawarray, 0, 1); addIntrinsicClassVar(class_string, "unixCmdActions", &o_nil); SetInt(&class_string->instanceFormat, obj_char); SetInt(&class_string->classFlags, slotRawInt(&class_string->classFlags) | classHasIndexableInstances); class_floatarray = makeIntrinsicClass(s_floatarray, s_rawarray, 0, 0); SetInt(&class_floatarray->instanceFormat, obj_float); SetInt(&class_floatarray->classFlags, slotRawInt(&class_floatarray->classFlags) | classHasIndexableInstances); class_signal = makeIntrinsicClass(s_signal, s_floatarray, 0, 0); SetInt(&class_signal->instanceFormat, obj_float); SetInt(&class_signal->classFlags, slotRawInt(&class_signal->classFlags) | classHasIndexableInstances); class_wavetable = makeIntrinsicClass(s_wavetable, s_floatarray, 0, 0); SetInt(&class_wavetable->instanceFormat, obj_float); SetInt(&class_wavetable->classFlags, slotRawInt(&class_wavetable->classFlags) | classHasIndexableInstances); // addIntrinsicVar(class_signal, "rate", &o_nil); class_doublearray = makeIntrinsicClass(s_doublearray, s_rawarray, 0, 0); SetInt(&class_doublearray->instanceFormat, obj_double); SetInt(&class_doublearray->classFlags, slotRawInt(&class_doublearray->classFlags) | classHasIndexableInstances); class_list = makeIntrinsicClass(s_list, s_sequenceable_collection, 1, 0); addIntrinsicVar(class_list, "array", &o_nil); // addIntrinsicVar(class_list, "size", &o_zero); class_func = makeIntrinsicClass(s_func, s_absfunc, 2, 0); addIntrinsicVar(class_func, "def", &o_nil); addIntrinsicVar(class_func, "context", &o_nil); class_server_shm_interface = makeIntrinsicClass(s_server_shm_interface, s_object, 2, 0); addIntrinsicVar(class_server_shm_interface, "ptr", &o_nil); addIntrinsicVar(class_server_shm_interface, "finalizer", &o_nil); gTagClassTable[0] = nullptr; gTagClassTable[1] = nullptr; gTagClassTable[2] = class_int; gTagClassTable[3] = class_symbol; gTagClassTable[4] = class_char; gTagClassTable[5] = class_nil; gTagClassTable[6] = class_false; gTagClassTable[7] = class_true; gTagClassTable[8] = class_rawptr; gTagClassTable[9] = class_float; gTagClassTable[10] = class_float; gTagClassTable[11] = class_float; gTagClassTable[12] = class_float; SetObject(&o_emptyarray, newPyrArray(nullptr, 0, obj_permanent | obj_immutable, false)); SetObject(&o_onenilarray, newPyrArray(nullptr, 1, obj_permanent | obj_immutable, false)); slotRawObject(&o_onenilarray)->size = 1; SetNil(slotRawObject(&o_onenilarray)->slots); SetObject(&o_argnamethis, newPyrSymbolArray(nullptr, 1, obj_permanent | obj_immutable, false)); slotRawSymbolArray(&o_argnamethis)->size = 1; slotRawSymbolArray(&o_argnamethis)->symbols[0] = s_this; /* post("array %p '%s'\n", class_array, class_array->name.us->name); post("o_emptyarray %p '%s'\n", slotRawObject(&o_emptyarray)->classptr, slotRawObject(&o_emptyarray)->classptr->name.us->name); post("o_argnamethis %p '%s'\n", slotRawObject(&o_argnamethis)->classptr, slotRawObject(&o_argnamethis)->classptr->name.us->name); post("o_onenilarray %p '%s'\n", slotRawObject(&o_onenilarray)->classptr, slotRawObject(&o_onenilarray)->classptr->name.us->name); dumpObjectSlot(&o_emptyarray); dumpObjectSlot(&o_argnamethis); dumpObjectSlot(&o_onenilarray); */ } PyrObject* instantiateObject(class PyrGC* gc, PyrClass* classobj, int size, bool fill, bool runGC) { PyrObject *newobj, *proto; int numbytes, format, flags; format = slotRawInt(&classobj->instanceFormat); flags = slotRawInt(&classobj->instanceFlags); if (slotRawInt(&classobj->classFlags) & classHasIndexableInstances) { // create an indexable object numbytes = size * gFormatElemSize[format]; newobj = gc->New(numbytes, flags, format, runGC); if (fill) { newobj->size = size; if (format == obj_slot) { nilSlots(newobj->slots, size); } else { memset(newobj->slots, format == obj_char ? ' ' : 0, size * gFormatElemSize[format]); } } else { newobj->size = 0; } } else { if (IsObj(&classobj->iprototype)) { proto = slotRawObject(&classobj->iprototype); size = proto->size; numbytes = size * sizeof(PyrSlot); newobj = gc->New(numbytes, flags, format, runGC); newobj->size = size; if (size) { memcpy(newobj->slots, proto->slots, numbytes); } } else { numbytes = 0; newobj = gc->New(numbytes, flags, format, runGC); newobj->size = 0; } } newobj->classptr = classobj; return newobj; } PyrObject* instantiateObjectLight(class PyrGC* gc, PyrClass* classobj, int size, bool runGC); PyrObject* instantiateObjectLight(class PyrGC* gc, PyrClass* classobj, int size, bool runGC) { PyrObject *newobj, *proto; int numbytes, format, flags; format = slotRawInt(&classobj->instanceFormat); flags = slotRawInt(&classobj->instanceFlags); if (slotRawInt(&classobj->classFlags) & classHasIndexableInstances) { numbytes = size * gFormatElemSize[format]; } else { if (IsObj(&classobj->iprototype)) { proto = slotRawObject(&classobj->iprototype); size = proto->size; numbytes = size * sizeof(PyrSlot); } else { size = 0; numbytes = 0; } } newobj = gc->New(numbytes, flags, format, runGC); newobj->size = size; newobj->classptr = classobj; return newobj; } PyrObject* copyObject(class PyrGC* gc, PyrObject* inobj, bool runGC) { PyrObject* newobj; // copies are neither immutable not permanent int flags = ~(obj_immutable)&inobj->obj_flags; flags = ~(obj_permanent)&flags; int elemsize = gFormatElemSize[inobj->obj_format]; int numbytes = inobj->size * elemsize; newobj = gc->New(numbytes, flags, inobj->obj_format, runGC); newobj->size = inobj->size; newobj->classptr = inobj->classptr; memcpy(newobj->slots, inobj->slots, inobj->size * elemsize); return newobj; } PyrObject* copyObjectRange(class PyrGC* gc, PyrObject* inobj, int start, int end, bool runGC) { PyrObject* newobj; if (start < 0) start = 0; if (end >= inobj->size) end = inobj->size - 1; int length = end - start + 1; if (length < 0) length = 0; int elemsize = gFormatElemSize[inobj->obj_format]; int numbytes = length * elemsize; // copies are neither immutable not permanent int flags = ~(obj_immutable)&inobj->obj_flags; flags = ~(obj_permanent)&flags; newobj = gc->New(numbytes, flags, inobj->obj_format, runGC); newobj->size = length; newobj->classptr = inobj->classptr; if (length > 0) { memcpy(newobj->slots, (char*)(inobj->slots) + start * elemsize, length * elemsize); } return newobj; } void dumpObject(PyrObject* obj) { char str[256]; PyrClass* classobj; int i; if (obj == nullptr) { postfl("NULL object pointer\n"); return; } classobj = obj->classptr; if (isKindOf(obj, class_class)) { post("class %s (%p) {\n", slotRawSymbol(&((PyrClass*)obj)->name)->name, obj); } else { // post("Instance of %s (%p) {\n", slotRawSymbol(&classobj->name)->name, obj); post("Instance of %s { (%p, gc=%02X, fmt=%02X, flg=%02X, set=%02X)\n", slotRawSymbol(&classobj->name)->name, obj, obj->gc_color, obj->obj_format, obj->obj_flags, obj->obj_sizeclass); } // flushPostBuf(); if (obj->obj_format == obj_notindexed) { post(" instance variables [%d]\n", obj->size); for (i = 0; i < obj->size; ++i) { slotString(obj->slots + i, str); post(" %s : %s\n", slotRawSymbolArray(&classobj->instVarNames)->symbols[i]->name, str); } } else { int maxsize; post(" indexed slots [%d]\n", obj->size); maxsize = sc_min(32, obj->size); switch (obj->obj_format) { case obj_slot: for (i = 0; i < maxsize; ++i) { slotString(obj->slots + i, str); post(" %3d : %s\n", i, str); } break; case obj_double: for (i = 0; i < maxsize; ++i) { post(" %3d : %f\n", i, slotRawFloat(&obj->slots[i])); } break; case obj_float: for (i = 0; i < maxsize; ++i) { float val; val = ((float*)(obj->slots))[i]; post(" %3d : %g\n", i, val); } break; case obj_int32: for (i = 0; i < maxsize; ++i) { int32 val; val = ((int32*)(obj->slots))[i]; post(" %3d : %d\n", i, val); } break; case obj_int16: for (i = 0; i < maxsize; ++i) { int16 val; val = ((int16*)(obj->slots))[i]; post(" %3d : %d\n", i, val); } break; case obj_int8: for (i = 0; i < maxsize; ++i) { int8 val; val = ((int8*)(obj->slots))[i]; post(" %3d : %4d %4u 0x%02X\n", i, val, val & 255, val & 255); } break; case obj_char: for (i = 0; i < maxsize; ++i) { char val; val = ((char*)(obj->slots))[i]; post(" %3d : %c\n", i, val); } break; case obj_symbol: for (i = 0; i < maxsize; ++i) { PyrSymbol* sym; sym = ((PyrSymbol**)(obj->slots))[i]; post(" %3d : '%s'\n", i, sym->name); } break; default: post("unknown obj_format %X\n", obj->obj_format); } if (obj->size > maxsize) { post(" ...\n"); } } post("}\n"); } void dumpBadObject(PyrObject* obj) { char str[128]; PyrClass* classobj; int i; if (obj == nullptr) { postfl("NULL object pointer\n"); return; } classobj = obj->classptr; if (isKindOf(obj, class_class)) { postfl("class %s (%p) {\n", slotRawSymbol(&((PyrClass*)obj)->name)->name, obj); } else { // postfl("Instance of %s (%p) {\n", slotRawSymbol(&classobj->name)->name, obj); postfl("Instance of %s { (%p, gc=%02X, fmt=%02X, flg=%02X, set=%02X)\n", slotRawSymbol(&classobj->name)->name, obj, obj->gc_color, obj->obj_format, obj->obj_flags, obj->obj_sizeclass); } if (obj->obj_format == obj_notindexed) { postfl(" instance variables [%d]\n", obj->size); for (i = 0; i < obj->size; ++i) { slotString(obj->slots + i, str); postfl(" %s : %s\n", slotRawSymbolArray(&classobj->instVarNames)->symbols[i]->name, str); } } else { int maxsize; postfl(" indexed slots [%d]\n", obj->size); maxsize = obj->size; maxsize = sc_min(32, maxsize); switch (obj->obj_format) { case obj_slot: for (i = 0; i < maxsize; ++i) { slotString(obj->slots + i, str); postfl(" %3d : %s\n", i, str); } break; case obj_double: for (i = 0; i < maxsize; ++i) { postfl(" %3d : %f\n", i, slotRawFloat(&obj->slots[i])); } break; case obj_float: for (i = 0; i < maxsize; ++i) { float val; val = ((float*)(obj->slots))[i]; postfl(" %3d : %g\n", i, val); } break; case obj_int32: for (i = 0; i < maxsize; ++i) { int32 val; val = ((int32*)(obj->slots))[i]; postfl(" %3d : %d\n", i, val); } break; case obj_int16: for (i = 0; i < maxsize; ++i) { int16 val; val = ((int16*)(obj->slots))[i]; postfl(" %3d : %d\n", i, val); } break; case obj_int8: for (i = 0; i < maxsize; ++i) { int8 val; val = ((int8*)(obj->slots))[i]; postfl(" %3d : %4d %4u 0x%02X\n", i, val, val & 255, val & 255); } break; case obj_char: for (i = 0; i < maxsize; ++i) { char val; val = ((char*)(obj->slots))[i]; postfl(" %3d : %c\n", i, val); } break; case obj_symbol: for (i = 0; i < maxsize; ++i) { PyrSymbol* sym; sym = ((PyrSymbol**)(obj->slots))[i]; post(" %3d : '%s'\n", i, sym->name); } break; default: postfl("unknown obj_format %X\n", obj->obj_format); } if (obj->size > maxsize) { postfl(" ...\n"); } } postfl("}\n"); } void dumpObjectSlot(PyrSlot* slot) { if (IsObj(slot)) { dumpObject(slotRawObject(slot)); } else { dumpPyrSlot(slot); } } void dumpSlotOneWord(const char* tagstr, PyrSlot* slot) { char str[256]; slotOneWord(slot, str); post("%s %s\n", tagstr, str); } void CallStackSanity(VMGlobals* g, const char* tagstr); void CallStackSanity(VMGlobals* g, const char* tagstr) { PyrFrame* frame; frame = g->frame; while (frame) { if (FrameSanity(frame, tagstr)) { DumpBackTrace(g); // Debugger(); break; } frame = slotRawFrame(&frame->caller); } } bool FrameSanity(PyrFrame* frame, const char* tagstr); bool FrameSanity(PyrFrame* frame, const char* tagstr) { bool failed = false; if (frame == nullptr) return false; if (NotObj(&frame->method)) { postfl("Frame %p method tag wrong %p\n", frame, GetTag(&frame->method)); failed = true; //} else if (!isKindOf((PyrObject*)slotRawObject(&frame->method)->classptr, class_fundef)) { } else if (slotRawObject(&frame->method)->classptr != class_method && slotRawObject(&frame->method)->classptr != class_fundef) { postfl("Frame %p method class wrong %p\n", frame, slotRawObject(&frame->method)->classptr); failed = true; // if (slotRawObject(&frame->method)->classptr->classptr == class_class) { postfl("class: '%s'\n", slotRawSymbol(&slotRawObject(&frame->method)->classptr->name)->name); ///} else { // postfl("not even a class\n"); //} } else if (NotObj(&slotRawBlock(&frame->method)->code)) { postfl("Method %p code tag wrong %p\n", slotRawBlock(&frame->method), GetTag(&slotRawBlock(&frame->method)->code)); failed = true; } else if (slotRawObject(&slotRawBlock(&frame->method)->code)->classptr != class_int8array) { postfl("Code %p class wrong %p\n", slotRawObject(&slotRawBlock(&frame->method)->code), slotRawObject(&slotRawBlock(&frame->method)->code)->classptr); postfl("class: '%s'\n", slotRawSymbol(&slotRawObject(&slotRawBlock(&frame->method)->code)->classptr->name)->name); failed = true; } /* if (frame->caller.utag != tagHFrame && frame->caller.utag != tagNil) { postfl("Frame %p caller tag wrong %p\n", frame, frame->caller.utag); failed = true; } if (frame->context.utag != tagHFrame && frame->context.utag != tagNil) { postfl("Frame %p context tag wrong %p\n", frame, frame->context.utag); failed = true; } if (frame->homeContext.utag != tagHFrame && frame->homeContext.utag != tagNil) { postfl("Frame %p homeContext tag wrong %p\n", frame, frame->homeContext.utag); failed = true; } */ if (!IsPtr(&frame->ip)) { postfl("Frame %p ip tag wrong %p\n", frame, GetTag(&frame->ip)); failed = true; } return failed; } void DumpFrame(PyrFrame* frame) { char str[256]; int i, numargs; PyrMethod* meth; PyrMethodRaw* methraw; if (FrameSanity(frame, "DumpFrame")) { post("FRAME CORRUPTED\n"); return; } slotOneWord(&frame->method, str); // slotString(&frame->method, str); meth = slotRawMethod(&frame->method); methraw = METHRAW(meth); if (methraw->numtemps) { post("\t%s\n", str); numargs = methraw->numargs + methraw->varargs; for (i = 0; i < methraw->numtemps; ++i) { slotOneWord(frame->vars + i, str); // slotString(frame->vars + i, str); if (i < numargs) { post("\t\targ %s = %s\n", slotRawSymbolArray(&meth->argNames)->symbols[i]->name, str); } else { post("\t\tvar %s = %s\n", slotRawSymbolArray(&meth->varNames)->symbols[i - numargs]->name, str); } } } else { post("\t%s (no arguments or variables)\n", str); } } void dumpByteCodes(PyrBlock* theBlock); void DumpDetailedFrame(PyrFrame* frame); void DumpDetailedFrame(PyrFrame* frame) { char mstr[256]; char str[256]; int i, numargs; PyrMethod* meth; PyrMethodRaw* methraw; if (FrameSanity(frame, "DumpDetailedFrame")) { post("FRAME CORRUPTED\n"); return; } slotOneWord(&frame->method, mstr); // slotString(&frame->method, str); meth = slotRawMethod(&frame->method); methraw = METHRAW(meth); if (methraw->numtemps) { post("\t%s\n", mstr); numargs = methraw->numargs + methraw->varargs; for (i = 0; i < methraw->numtemps; ++i) { slotOneWord(frame->vars + i, str); // slotString(frame->vars + i, str); if (i < numargs) { post("\t\targ %s = %s\n", slotRawSymbolArray(&meth->argNames)->symbols[i]->name, str); } else { post("\t\tvar %s = %s\n", slotRawSymbolArray(&meth->varNames)->symbols[i - numargs]->name, str); } } } else { post("\t%s (no arguments or variables)\n", mstr); } post("\t....%s details:\n", mstr); post("\t\tneedsHeapContext = %d\n", methraw->needsHeapContext); post("\t\tnumtemps = %d\n", methraw->numtemps); post("\t\tpopSize = %d\n", methraw->popSize); slotString(&frame->method, str); post("\t\tmethod = %s\n", str); slotString(&frame->caller, str); post("\t\tcaller = %s\n", str); slotString(&frame->context, str); post("\t\tcontext = %s\n", str); slotString(&frame->homeContext, str); post("\t\thomeCtx = %s\n", str); slotString(&frame->ip, str); post("\t\tip = %s\n", str); if (IsPtr(&frame->ip)) { post("ipoffset = %d\n", (char*)slotRawPtr(&frame->ip) - (char*)slotRawInt8Array(&meth->code)->b); dumpByteCodes(meth); } } bool respondsTo(PyrSlot* slot, PyrSymbol* selector) { PyrClass* classobj; PyrMethod* meth; int index; classobj = classOfSlot(slot); index = slotRawInt(&classobj->classIndex) + selector->u.index; meth = gRowTable[index]; return slotRawSymbol(&meth->name) == selector; } PyrMethod* methodLookup(PyrSlot* slot, PyrSymbol* selector); PyrMethod* methodLookup(PyrSlot* slot, PyrSymbol* selector) { PyrClass* classobj; PyrMethod* meth; int index; classobj = classOfSlot(slot); index = slotRawInt(&classobj->classIndex) + selector->u.index; meth = gRowTable[index]; return meth; } bool isSubclassOf(PyrClass* classobj, PyrClass* testclass) { while (classobj) { if (classobj == testclass) { return true; } classobj = slotRawSymbol(&classobj->superclass)->u.classobj; } return false; } /*bool isKindOf(PyrObjectHdr *obj, PyrClass *testclass) { int objClassIndex = slotRawInt(&obj->classptr->classIndex); return objClassIndex >= slotRawInt(&testclass->classIndex) && objClassIndex <= slotRawInt(&testclass->maxSubclassIndex); }*/ bool objAddIndexedSlot(PyrObject* obj, PyrSlot* slot) { if (obj->size < ARRAYMAXINDEXSIZE(obj)) { slotCopy(&obj->slots[obj->size++], slot); return true; } else { return false; } } bool objAddIndexedSymbol(PyrSymbolArray* obj, PyrSymbol* symbol) { if (obj->size < MAXINDEXSIZE((PyrObject*)obj)) { obj->symbols[obj->size++] = symbol; return true; } else { return false; } } bool objAddIndexedObject(PyrObject* obj, PyrObject* obj2) { if (obj->size < ARRAYMAXINDEXSIZE(obj)) { SetObject(obj->slots + obj->size, obj2); obj->size++; return true; } else { return false; } } void fillSlots(PyrSlot* slot, int size, PyrSlot* fillslot) { for (int i = 0; i != size; ++i) slotCopy(&slot[i], fillslot); } void nilSlots(PyrSlot* slot, int size) { fillSlots(slot, size, &o_nil); } void zeroSlots(PyrSlot* slot, int size) { PyrSlot zero; SetTagRaw(&zero, 0); SetRaw(&zero, 0.0); fillSlots(slot, size, &zero); } PyrObject* newPyrObject(class PyrGC* gc, size_t inNumBytes, int inFlags, int inFormat, bool inRunGC) { return gc->New(inNumBytes, inFlags, inFormat, inRunGC); } PyrObject* newPyrArray(class PyrGC* gc, int size, int flags, bool runGC) { PyrObject* array; int numbytes = size * sizeof(PyrSlot); if (!gc) array = PyrGC::NewPermanent(numbytes, flags, obj_slot); else array = gc->New(numbytes, flags, obj_slot, runGC); array->classptr = class_array; return array; } PyrSymbolArray* newPyrSymbolArray(class PyrGC* gc, int size, int flags, bool runGC) { PyrSymbolArray* array; int numbytes = size * sizeof(PyrSymbol*); if (!gc) array = (PyrSymbolArray*)PyrGC::NewPermanent(numbytes, flags, obj_symbol); else array = (PyrSymbolArray*)gc->New(numbytes, flags, obj_symbol, runGC); array->classptr = class_symbolarray; return array; } PyrInt8Array* newPyrInt8Array(class PyrGC* gc, int size, int flags, bool runGC) { PyrInt8Array* array; if (!gc) array = (PyrInt8Array*)PyrGC::NewPermanent(size, flags, obj_int8); else array = (PyrInt8Array*)gc->New(size, flags, obj_int8, runGC); array->classptr = class_int8array; return array; } PyrInt32Array* newPyrInt32Array(class PyrGC* gc, int size, int flags, bool runGC) { PyrInt32Array* array; int numbytes = size * sizeof(int32); if (!gc) array = (PyrInt32Array*)PyrGC::NewPermanent(numbytes, flags, obj_int32); else array = (PyrInt32Array*)gc->New(numbytes, flags, obj_int32, runGC); array->classptr = class_int32array; return array; } PyrDoubleArray* newPyrDoubleArray(class PyrGC* gc, int size, int flags, bool runGC) { PyrDoubleArray* array; int numbytes = size * sizeof(double); if (!gc) array = (PyrDoubleArray*)PyrGC::NewPermanent(numbytes, flags, obj_double); else array = (PyrDoubleArray*)gc->New(size, flags, obj_double, runGC); array->classptr = class_doublearray; return array; } PyrString* newPyrString(class PyrGC* gc, const char* s, int flags, bool runGC) { PyrString* string; int length = strlen(s); if (!gc) string = (PyrString*)PyrGC::NewPermanent(length, flags, obj_char); else string = (PyrString*)gc->New(length, flags, obj_char, runGC); string->classptr = class_string; string->size = length; memcpy(string->s, s, length); return string; } PyrString* newPyrStringN(class PyrGC* gc, int length, int flags, bool runGC) { PyrString* string; if (!gc) string = (PyrString*)PyrGC::NewPermanent(length, flags, obj_char); else string = (PyrString*)gc->New(length, flags, obj_char, runGC); string->classptr = class_string; string->size = length; // filled with garbage! return string; } PyrBlock* newPyrBlock(int flags) { PyrBlock* block; PyrMethodRaw* methraw; int32 numbytes = sizeof(PyrBlock) - sizeof(PyrObjectHdr); int32 numSlots = numbytes / sizeof(PyrSlot); if (!compilingCmdLine) block = (PyrBlock*)PyrGC::NewPermanent(numbytes, flags, obj_notindexed); else block = (PyrBlock*)gMainVMGlobals->gc->New(numbytes, flags, obj_notindexed, false); block->classptr = class_fundef; block->size = numSlots; // clear out raw area methraw = METHRAW(block); methraw->specialIndex = 0; methraw->methType = methBlock; methraw->needsHeapContext = 0; methraw->frameSize = 0; methraw->varargs = 0; methraw->numargs = 0; methraw->numvars = 0; methraw->numtemps = 0; methraw->popSize = 0; nilSlots(&block->rawData1, numSlots); return block; } SCLANG_DLLEXPORT_C struct VMGlobals* scGlobals() { return gMainVMGlobals; } PyrMethod* initPyrMethod(PyrMethod* method) { int32 numbytes = sizeof(PyrMethod) - sizeof(PyrObjectHdr); int32 numSlots = numbytes / sizeof(PyrSlot); method->classptr = class_method; method->size = 0; method->size = numSlots; SetFloat(&method->rawData1, 0.0); SetFloat(&method->rawData2, 0.0); nilSlots(&method->code, numSlots - 2); // slotCopy(&method->byteMeter, &o_zero); // slotCopy(&method->callMeter, &o_zero); // post("<- newPyrMethod %p %p\n", method, methraw); return method; } PyrMethod* newPyrMethod() { int32 numbytes = sizeof(PyrMethod) - sizeof(PyrObjectHdr); PyrMethod* method = (PyrMethod*)PyrGC::NewPermanent(numbytes, obj_permanent | obj_immutable, obj_notindexed); return initPyrMethod(method); } void freePyrSlot(PyrSlot* slot) { if (IsObj(slot)) { PyrObject* obj = slotRawObject(slot); if (obj && obj->IsPermanent()) { // don't deallocate these if (obj != slotRawObject(&o_emptyarray) && obj != slotRawObject(&o_onenilarray) && obj != slotRawObject(&o_argnamethis)) pyr_pool_runtime->Free((void*)obj); SetNil(slot); } } } void freePyrObject(PyrObject* obj) { if (obj->IsPermanent()) { pyr_pool_runtime->Free((void*)obj); } } int getIndexedInt(PyrObject* obj, int index, int* value) { PyrSlot* slot; int err = errNone; if (index < 0 || index >= obj->size) return errIndexOutOfRange; switch (obj->obj_format) { case obj_slot: slot = obj->slots + index; if (IsFloat(slot)) { *value = (int)slotRawFloat(slot); } else if (IsInt(slot)) { *value = slotRawInt(slot); } else { err = errWrongType; } break; case obj_double: *value = (int)((double*)(obj->slots))[index]; break; case obj_float: *value = (int)((float*)(obj->slots))[index]; break; case obj_int32: *value = ((int32*)(obj->slots))[index]; break; case obj_int16: *value = ((int16*)(obj->slots))[index]; break; case obj_int8: *value = ((int8*)(obj->slots))[index]; break; default: err = errWrongType; } return err; } int getIndexedFloat(PyrObject* obj, int index, float* value) { PyrSlot* slot; int err = errNone; if (index < 0 || index >= obj->size) return errIndexOutOfRange; switch (obj->obj_format) { case obj_slot: slot = obj->slots + index; if (IsFloat(slot)) { *value = slotRawFloat(slot); } else if (IsInt(slot)) { *value = slotRawInt(slot); } else { err = errWrongType; } break; case obj_double: *value = ((double*)(obj->slots))[index]; break; case obj_float: *value = ((float*)(obj->slots))[index]; break; case obj_int32: *value = ((int32*)(obj->slots))[index]; break; case obj_int16: *value = ((int16*)(obj->slots))[index]; break; case obj_int8: *value = ((int8*)(obj->slots))[index]; break; default: err = errWrongType; } return err; } int getIndexedDouble(PyrObject* obj, int index, double* value) { PyrSlot* slot; int err = errNone; if (index < 0 || index >= obj->size) return errIndexOutOfRange; switch (obj->obj_format) { case obj_slot: slot = obj->slots + index; if (IsFloat(slot)) { *value = slotRawFloat(slot); } else if (IsInt(slot)) { *value = slotRawInt(slot); } else { err = errWrongType; } break; case obj_double: *value = ((double*)(obj->slots))[index]; break; case obj_float: *value = ((float*)(obj->slots))[index]; break; case obj_int32: *value = ((int32*)(obj->slots))[index]; break; case obj_int16: *value = ((int16*)(obj->slots))[index]; break; case obj_int8: *value = ((int8*)(obj->slots))[index]; break; default: err = errWrongType; } return err; } void getIndexedSlot(PyrObject* obj, PyrSlot* a, int index) { // postfl("getIndexedSlot %s %X %d\n", slotRawSymbol(&obj->classptr->name)->name, // obj, index); switch (obj->obj_format) { case obj_slot: slotCopy(a, &obj->slots[index]); break; case obj_double: SetFloat(a, ((double*)(obj->slots))[index]); break; case obj_float: SetFloat(a, ((float*)(obj->slots))[index]); break; case obj_int32: SetInt(a, ((int32*)(obj->slots))[index]); break; case obj_int16: SetInt(a, ((int16*)(obj->slots))[index]); break; case obj_int8: SetInt(a, ((int8*)(obj->slots))[index]); break; case obj_symbol: SetSymbol(a, (PyrSymbol*)((int**)(obj->slots))[index]); break; case obj_char: SetChar(a, ((unsigned char*)(obj->slots))[index]); break; } } int putIndexedSlot(VMGlobals* g, PyrObject* obj, PyrSlot* c, int index) { PyrSlot* slot; switch (obj->obj_format) { case obj_slot: if (obj->IsImmutable()) return errImmutableObject; slot = obj->slots + index; slotCopy(slot, c); g->gc->GCWrite(obj, slot); break; case obj_double: if (NotFloat(c)) { if (NotInt(c)) return errWrongType; else { ((double*)(obj->slots))[index] = slotRawInt(c); } } else ((double*)(obj->slots))[index] = slotRawFloat(c); break; case obj_float: if (NotFloat(c)) { if (NotInt(c)) return errWrongType; else { ((float*)(obj->slots))[index] = slotRawInt(c); } } else ((float*)(obj->slots))[index] = slotRawFloat(c); break; case obj_int32: if (NotInt(c)) return errWrongType; ((int32*)(obj->slots))[index] = slotRawInt(c); break; case obj_int16: if (NotInt(c)) return errWrongType; ((int16*)(obj->slots))[index] = slotRawInt(c); break; case obj_int8: if (NotInt(c)) return errWrongType; ((int8*)(obj->slots))[index] = slotRawInt(c); break; case obj_symbol: if (NotSym(c)) return errWrongType; ((PyrSymbol**)(obj->slots))[index] = slotRawSymbol(c); break; case obj_char: if (NotChar(c)) return errWrongType; ((unsigned char*)(obj->slots))[index] = slotRawChar(c); break; } return errNone; } int putIndexedFloat(PyrObject* obj, double val, int index) { PyrSlot* slot; switch (obj->obj_format) { case obj_slot: if (obj->IsImmutable()) return errImmutableObject; slot = obj->slots + index; SetFloat(slot, val); break; case obj_double: ((double*)(obj->slots))[index] = val; break; case obj_float: ((float*)(obj->slots))[index] = (float)val; break; case obj_int32: ((int32*)(obj->slots))[index] = (int32)val; break; case obj_int16: ((int16*)(obj->slots))[index] = (int16)val; break; case obj_int8: ((int8*)(obj->slots))[index] = (int8)val; break; } return errNone; } /** * @brief obtain a vector of strings from an sclang collection of sclang strings. * @param coll The sclang collection containing strings * @return a tuple containing an int (the error code) and a vector of std:string's. * If an error occurs an empty vector is returned. */ std::tuple<int, std::vector<std::string>> PyrCollToVectorStdString(PyrObject* coll) { std::vector<std::string> strings; for (int i = 0; i < coll->size; ++i) { PyrSlot argSlot; getIndexedSlot(coll, &argSlot, i); int error; std::string string; std::tie(error, string) = slotStrStdStrVal(&argSlot); if (error != errNone) { strings.clear(); return std::make_tuple(error, strings); } strings.push_back(std::move(string)); } return make_tuple(errNone, std::move(strings)); } static int hashPtr(void* ptr) { int32 hashed_part = int32((size_t)ptr & 0xffffffff); return Hash(hashed_part); } int calcHash(PyrSlot* a); int calcHash(PyrSlot* a) { int hash; switch (GetTag(a)) { case tagObj: hash = hashPtr(slotRawObject(a)); break; case tagInt: hash = Hash(slotRawInt(a)); break; case tagChar: hash = Hash(slotRawChar(a) & 255); break; case tagSym: hash = slotRawSymbol(a)->hash; break; case tagNil: hash = 0xA5A5A5A5; break; case tagFalse: hash = 0x55AA55AA; break; case tagTrue: hash = 0x69696969; break; case tagPtr: hash = hashPtr(slotRawPtr(a)); break; default: // hash for a double union { int32 i[2]; double d; } u; u.d = slotRawFloat(a); hash = Hash(u.i[0] + Hash(u.i[1])); } return hash; } void InstallFinalizer(VMGlobals* g, PyrObject* inObj, int slotIndex, ObjFuncPtr inFunc) { PyrObject* finalizer = g->gc->NewFinalizer(inFunc, inObj, false); SetObject(inObj->slots + slotIndex, finalizer); g->gc->GCWriteNew(inObj, finalizer); // we know finalizer is white so we can use GCWriteNew }
99,463
C++
.cpp
2,509
32.626544
120
0.633178
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
29,859
lang11d_tab.cpp
supercollider_supercollider/lang/LangSource/Bison/lang11d_tab.cpp
/* A Bison parser, made by GNU Bison 3.8.2. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2021 Free Software Foundation, Inc. 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 3 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 <https://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, especially those whose name start with YY_ or yy_. They are private implementation details that can be changed or removed. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output, and Bison version. */ #define YYBISON 30802 /* Bison version string. */ #define YYBISON_VERSION "3.8.2" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #line 16 "lang11d" #include <stdlib.h> #include <string.h> #include "PyrLexer.h" #include "PyrParseNode.h" #include "SC_Constants.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "InitAlloc.h" #include "PredefinedSymbols.h" #include "SimpleStack.h" void bcopy(void *src, void *dst, size_t size) ; int yyparse(); extern bool compilingCmdLine; extern LongStack generatorStack; #line 92 "lang11d_tab.cpp" # ifndef YY_CAST # ifdef __cplusplus # define YY_CAST(Type, Val) static_cast<Type> (Val) # define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val) # else # define YY_CAST(Type, Val) ((Type) (Val)) # define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) # endif # endif # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif #include "lang11d_tab.h" /* Symbol kind. */ enum yysymbol_kind_t { YYSYMBOL_YYEMPTY = -2, YYSYMBOL_YYEOF = 0, /* "end of file" */ YYSYMBOL_YYerror = 1, /* error */ YYSYMBOL_YYUNDEF = 2, /* "invalid token" */ YYSYMBOL_NAME = 3, /* NAME */ YYSYMBOL_INTEGER = 4, /* INTEGER */ YYSYMBOL_SC_FLOAT = 5, /* SC_FLOAT */ YYSYMBOL_ACCIDENTAL = 6, /* ACCIDENTAL */ YYSYMBOL_SYMBOL = 7, /* SYMBOL */ YYSYMBOL_STRING = 8, /* STRING */ YYSYMBOL_ASCII = 9, /* ASCII */ YYSYMBOL_PRIMITIVENAME = 10, /* PRIMITIVENAME */ YYSYMBOL_CLASSNAME = 11, /* CLASSNAME */ YYSYMBOL_CURRYARG = 12, /* CURRYARG */ YYSYMBOL_VAR = 13, /* VAR */ YYSYMBOL_ARG = 14, /* ARG */ YYSYMBOL_CLASSVAR = 15, /* CLASSVAR */ YYSYMBOL_SC_CONST = 16, /* SC_CONST */ YYSYMBOL_NILOBJ = 17, /* NILOBJ */ YYSYMBOL_TRUEOBJ = 18, /* TRUEOBJ */ YYSYMBOL_FALSEOBJ = 19, /* FALSEOBJ */ YYSYMBOL_PSEUDOVAR = 20, /* PSEUDOVAR */ YYSYMBOL_ELLIPSIS = 21, /* ELLIPSIS */ YYSYMBOL_DOTDOT = 22, /* DOTDOT */ YYSYMBOL_PIE = 23, /* PIE */ YYSYMBOL_BEGINCLOSEDFUNC = 24, /* BEGINCLOSEDFUNC */ YYSYMBOL_BADTOKEN = 25, /* BADTOKEN */ YYSYMBOL_INTERPRET = 26, /* INTERPRET */ YYSYMBOL_BEGINGENERATOR = 27, /* BEGINGENERATOR */ YYSYMBOL_LEFTARROW = 28, /* LEFTARROW */ YYSYMBOL_WHILE = 29, /* WHILE */ YYSYMBOL_30_ = 30, /* ':' */ YYSYMBOL_31_ = 31, /* '=' */ YYSYMBOL_BINOP = 32, /* BINOP */ YYSYMBOL_KEYBINOP = 33, /* KEYBINOP */ YYSYMBOL_34_ = 34, /* '-' */ YYSYMBOL_35_ = 35, /* '<' */ YYSYMBOL_36_ = 36, /* '>' */ YYSYMBOL_37_ = 37, /* '*' */ YYSYMBOL_38_ = 38, /* '+' */ YYSYMBOL_39_ = 39, /* '|' */ YYSYMBOL_READWRITEVAR = 40, /* READWRITEVAR */ YYSYMBOL_41_ = 41, /* '.' */ YYSYMBOL_42_ = 42, /* '`' */ YYSYMBOL_UMINUS = 43, /* UMINUS */ YYSYMBOL_44_ = 44, /* '{' */ YYSYMBOL_45_ = 45, /* '}' */ YYSYMBOL_46_ = 46, /* '[' */ YYSYMBOL_47_ = 47, /* ']' */ YYSYMBOL_48_ = 48, /* ';' */ YYSYMBOL_49_ = 49, /* ',' */ YYSYMBOL_50_ = 50, /* '(' */ YYSYMBOL_51_ = 51, /* ')' */ YYSYMBOL_52_ = 52, /* '^' */ YYSYMBOL_53_ = 53, /* '~' */ YYSYMBOL_54_ = 54, /* '#' */ YYSYMBOL_YYACCEPT = 55, /* $accept */ YYSYMBOL_root = 56, /* root */ YYSYMBOL_classes = 57, /* classes */ YYSYMBOL_classextensions = 58, /* classextensions */ YYSYMBOL_classdef = 59, /* classdef */ YYSYMBOL_classextension = 60, /* classextension */ YYSYMBOL_optname = 61, /* optname */ YYSYMBOL_superclass = 62, /* superclass */ YYSYMBOL_classvardecls = 63, /* classvardecls */ YYSYMBOL_classvardecl = 64, /* classvardecl */ YYSYMBOL_methods = 65, /* methods */ YYSYMBOL_methoddef = 66, /* methoddef */ YYSYMBOL_optsemi = 67, /* optsemi */ YYSYMBOL_optcomma = 68, /* optcomma */ YYSYMBOL_optequal = 69, /* optequal */ YYSYMBOL_funcbody = 70, /* funcbody */ YYSYMBOL_cmdlinecode = 71, /* cmdlinecode */ YYSYMBOL_methbody = 72, /* methbody */ YYSYMBOL_primitive = 73, /* primitive */ YYSYMBOL_retval = 74, /* retval */ YYSYMBOL_funretval = 75, /* funretval */ YYSYMBOL_blocklist1 = 76, /* blocklist1 */ YYSYMBOL_blocklistitem = 77, /* blocklistitem */ YYSYMBOL_blocklist = 78, /* blocklist */ YYSYMBOL_msgsend = 79, /* msgsend */ YYSYMBOL_generator = 80, /* generator */ YYSYMBOL_81_1 = 81, /* $@1 */ YYSYMBOL_82_2 = 82, /* $@2 */ YYSYMBOL_nextqual = 83, /* nextqual */ YYSYMBOL_qual = 84, /* qual */ YYSYMBOL_expr1 = 85, /* expr1 */ YYSYMBOL_valrangex1 = 86, /* valrangex1 */ YYSYMBOL_valrangeassign = 87, /* valrangeassign */ YYSYMBOL_valrangexd = 88, /* valrangexd */ YYSYMBOL_valrange2 = 89, /* valrange2 */ YYSYMBOL_valrange3 = 90, /* valrange3 */ YYSYMBOL_expr = 91, /* expr */ YYSYMBOL_adverb = 92, /* adverb */ YYSYMBOL_exprn = 93, /* exprn */ YYSYMBOL_exprseq = 94, /* exprseq */ YYSYMBOL_arrayelems = 95, /* arrayelems */ YYSYMBOL_arrayelems1 = 96, /* arrayelems1 */ YYSYMBOL_arglist1 = 97, /* arglist1 */ YYSYMBOL_arglistv1 = 98, /* arglistv1 */ YYSYMBOL_keyarglist1 = 99, /* keyarglist1 */ YYSYMBOL_keyarg = 100, /* keyarg */ YYSYMBOL_optkeyarglist = 101, /* optkeyarglist */ YYSYMBOL_mavars = 102, /* mavars */ YYSYMBOL_mavarlist = 103, /* mavarlist */ YYSYMBOL_slotliteral = 104, /* slotliteral */ YYSYMBOL_blockliteral = 105, /* blockliteral */ YYSYMBOL_pushname = 106, /* pushname */ YYSYMBOL_pushliteral = 107, /* pushliteral */ YYSYMBOL_listliteral = 108, /* listliteral */ YYSYMBOL_block = 109, /* block */ YYSYMBOL_funcvardecls = 110, /* funcvardecls */ YYSYMBOL_funcvardecls1 = 111, /* funcvardecls1 */ YYSYMBOL_funcvardecl = 112, /* funcvardecl */ YYSYMBOL_argdecls = 113, /* argdecls */ YYSYMBOL_argdecls1 = 114, /* argdecls1 */ YYSYMBOL_constdeflist = 115, /* constdeflist */ YYSYMBOL_constdef = 116, /* constdef */ YYSYMBOL_slotdeflist0 = 117, /* slotdeflist0 */ YYSYMBOL_slotdeflist = 118, /* slotdeflist */ YYSYMBOL_slotdef = 119, /* slotdef */ YYSYMBOL_vardeflist0 = 120, /* vardeflist0 */ YYSYMBOL_vardeflist = 121, /* vardeflist */ YYSYMBOL_vardef = 122, /* vardef */ YYSYMBOL_dictslotdef = 123, /* dictslotdef */ YYSYMBOL_dictslotlist1 = 124, /* dictslotlist1 */ YYSYMBOL_dictslotlist = 125, /* dictslotlist */ YYSYMBOL_rwslotdeflist = 126, /* rwslotdeflist */ YYSYMBOL_rwslotdef = 127, /* rwslotdef */ YYSYMBOL_dictlit2 = 128, /* dictlit2 */ YYSYMBOL_litdictslotdef = 129, /* litdictslotdef */ YYSYMBOL_litdictslotlist1 = 130, /* litdictslotlist1 */ YYSYMBOL_litdictslotlist = 131, /* litdictslotlist */ YYSYMBOL_listlit = 132, /* listlit */ YYSYMBOL_listlit2 = 133, /* listlit2 */ YYSYMBOL_literallistc = 134, /* literallistc */ YYSYMBOL_literallist1 = 135, /* literallist1 */ YYSYMBOL_rwspec = 136, /* rwspec */ YYSYMBOL_rspec = 137, /* rspec */ YYSYMBOL_integer = 138, /* integer */ YYSYMBOL_floatr = 139, /* floatr */ YYSYMBOL_accidental = 140, /* accidental */ YYSYMBOL_pie = 141, /* pie */ YYSYMBOL_floatp = 142, /* floatp */ YYSYMBOL_name = 143, /* name */ YYSYMBOL_classname = 144, /* classname */ YYSYMBOL_primname = 145, /* primname */ YYSYMBOL_trueobj = 146, /* trueobj */ YYSYMBOL_falseobj = 147, /* falseobj */ YYSYMBOL_nilobj = 148, /* nilobj */ YYSYMBOL_ascii = 149, /* ascii */ YYSYMBOL_symbol = 150, /* symbol */ YYSYMBOL_string = 151, /* string */ YYSYMBOL_pseudovar = 152, /* pseudovar */ YYSYMBOL_binop = 153, /* binop */ YYSYMBOL_keybinop = 154, /* keybinop */ YYSYMBOL_binop2 = 155, /* binop2 */ YYSYMBOL_curryarg = 156 /* curryarg */ }; typedef enum yysymbol_kind_t yysymbol_kind_t; #ifdef short # undef short #endif /* On compilers that do not define __PTRDIFF_MAX__ etc., make sure <limits.h> and (if available) <stdint.h> are included so that the code can choose integer types of a good width. */ #ifndef __PTRDIFF_MAX__ # include <limits.h> /* INFRINGES ON USER NAME SPACE */ # if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stdint.h> /* INFRINGES ON USER NAME SPACE */ # define YY_STDINT_H # endif #endif /* Narrow types that promote to a signed type and that can represent a signed or unsigned integer of at least N bits. In tables they can save space and decrease cache pressure. Promoting to a signed type helps avoid bugs in integer arithmetic. */ #ifdef __INT_LEAST8_MAX__ typedef __INT_LEAST8_TYPE__ yytype_int8; #elif defined YY_STDINT_H typedef int_least8_t yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef __INT_LEAST16_MAX__ typedef __INT_LEAST16_TYPE__ yytype_int16; #elif defined YY_STDINT_H typedef int_least16_t yytype_int16; #else typedef short yytype_int16; #endif /* Work around bug in HP-UX 11.23, which defines these macros incorrectly for preprocessor constants. This workaround can likely be removed in 2023, as HPE has promised support for HP-UX 11.23 (aka HP-UX 11i v2) only through the end of 2022; see Table 2 of <https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */ #ifdef __hpux # undef UINT_LEAST8_MAX # undef UINT_LEAST16_MAX # define UINT_LEAST8_MAX 255 # define UINT_LEAST16_MAX 65535 #endif #if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__ typedef __UINT_LEAST8_TYPE__ yytype_uint8; #elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \ && UINT_LEAST8_MAX <= INT_MAX) typedef uint_least8_t yytype_uint8; #elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX typedef unsigned char yytype_uint8; #else typedef short yytype_uint8; #endif #if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__ typedef __UINT_LEAST16_TYPE__ yytype_uint16; #elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \ && UINT_LEAST16_MAX <= INT_MAX) typedef uint_least16_t yytype_uint16; #elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX typedef unsigned short yytype_uint16; #else typedef int yytype_uint16; #endif #ifndef YYPTRDIFF_T # if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__ # define YYPTRDIFF_T __PTRDIFF_TYPE__ # define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__ # elif defined PTRDIFF_MAX # ifndef ptrdiff_t # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # endif # define YYPTRDIFF_T ptrdiff_t # define YYPTRDIFF_MAXIMUM PTRDIFF_MAX # else # define YYPTRDIFF_T long # define YYPTRDIFF_MAXIMUM LONG_MAX # endif #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__ # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM \ YY_CAST (YYPTRDIFF_T, \ (YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \ ? YYPTRDIFF_MAXIMUM \ : YY_CAST (YYSIZE_T, -1))) #define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X)) /* Stored state numbers (used for stacks). */ typedef yytype_int16 yy_state_t; /* State numbers in computations. */ typedef int yy_state_fast_t; #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE_PURE # if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) # else # define YY_ATTRIBUTE_PURE # endif #endif #ifndef YY_ATTRIBUTE_UNUSED # if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) # define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # else # define YY_ATTRIBUTE_UNUSED # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YY_USE(E) ((void) (E)) #else # define YY_USE(E) /* empty */ #endif /* Suppress an incorrect diagnostic about yylval being uninitialized. */ #if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ # if __GNUC__ * 100 + __GNUC_MINOR__ < 407 # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") # else # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # endif # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ # define YY_IGNORE_USELESS_CAST_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") # define YY_IGNORE_USELESS_CAST_END \ _Pragma ("GCC diagnostic pop") #endif #ifndef YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_BEGIN # define YY_IGNORE_USELESS_CAST_END #endif #define YY_ASSERT(E) ((void) (0 && (E))) #if 1 /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* 1 */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yy_state_t yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYPTRDIFF_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / YYSIZEOF (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYPTRDIFF_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 70 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 1965 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 55 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 102 /* YYNRULES -- Number of rules. */ #define YYNRULES 303 /* YYNSTATES -- Number of states. */ #define YYNSTATES 571 /* YYMAXUTOK -- Last valid token kind. */ #define YYMAXUTOK 288 /* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM as returned by yylex, with out-of-bounds checking. */ #define YYTRANSLATE(YYX) \ (0 <= (YYX) && (YYX) <= YYMAXUTOK \ ? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \ : YYSYMBOL_YYUNDEF) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex. */ static const yytype_int8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 54, 2, 2, 2, 2, 50, 51, 37, 38, 49, 34, 41, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 30, 48, 35, 31, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 46, 2, 47, 52, 2, 42, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 44, 39, 45, 53, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 40, 43 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_int16 yyrline[] = { 0, 39, 39, 41, 43, 47, 48, 52, 53, 57, 61, 68, 74, 75, 78, 79, 83, 84, 88, 90, 92, 96, 97, 101, 104, 107, 110, 115, 116, 119, 120, 123, 124, 127, 128, 132, 134, 136, 138, 140, 142, 144, 148, 149, 153, 154, 159, 160, 165, 166, 170, 171, 177, 178, 181, 182, 185, 189, 193, 197, 202, 206, 211, 229, 242, 244, 255, 266, 277, 290, 311, 320, 329, 334, 348, 363, 385, 389, 395, 413, 419, 419, 429, 429, 436, 457, 461, 495, 533, 547, 558, 562, 587, 588, 589, 590, 591, 592, 593, 599, 609, 611, 613, 615, 617, 619, 632, 635, 662, 680, 707, 735, 754, 782, 809, 827, 852, 880, 899, 927, 946, 965, 982, 996, 1017, 1036, 1054, 1071, 1087, 1103, 1104, 1105, 1106, 1107, 1120, 1134, 1139, 1143, 1154, 1159, 1169, 1174, 1188, 1204, 1205, 1206, 1207, 1210, 1211, 1217, 1220, 1221, 1225, 1226, 1228, 1233, 1235, 1242, 1250, 1251, 1255, 1257, 1261, 1262, 1266, 1270, 1271, 1274, 1276, 1280, 1281, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1297, 1300, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1327, 1330, 1335, 1336, 1340, 1341, 1345, 1349, 1350, 1354, 1358, 1362, 1366, 1372, 1376, 1380, 1384, 1388, 1395, 1396, 1400, 1404, 1405, 1408, 1409, 1413, 1415, 1417, 1425, 1426, 1429, 1430, 1434, 1436, 1438, 1446, 1448, 1455, 1456, 1460, 1461, 1464, 1465, 1469, 1471, 1475, 1479, 1481, 1488, 1489, 1493, 1494, 1499, 1501, 1505, 1507, 1511, 1512, 1515, 1516, 1520, 1521, 1523, 1525, 1529, 1530, 1534, 1535, 1544, 1545, 1554, 1555, 1566, 1569, 1570, 1571, 1577, 1585, 1592, 1601, 1602, 1605, 1608, 1611, 1614, 1617, 1620, 1623, 1626, 1629, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1642, 1645, 1646, 1649 }; #endif /** Accessing symbol of state STATE. */ #define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State]) #if 1 /* The user-facing name of the symbol whose (internal) number is YYSYMBOL. No bounds checking. */ static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED; /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "\"end of file\"", "error", "\"invalid token\"", "NAME", "INTEGER", "SC_FLOAT", "ACCIDENTAL", "SYMBOL", "STRING", "ASCII", "PRIMITIVENAME", "CLASSNAME", "CURRYARG", "VAR", "ARG", "CLASSVAR", "SC_CONST", "NILOBJ", "TRUEOBJ", "FALSEOBJ", "PSEUDOVAR", "ELLIPSIS", "DOTDOT", "PIE", "BEGINCLOSEDFUNC", "BADTOKEN", "INTERPRET", "BEGINGENERATOR", "LEFTARROW", "WHILE", "':'", "'='", "BINOP", "KEYBINOP", "'-'", "'<'", "'>'", "'*'", "'+'", "'|'", "READWRITEVAR", "'.'", "'`'", "UMINUS", "'{'", "'}'", "'['", "']'", "';'", "','", "'('", "')'", "'^'", "'~'", "'#'", "$accept", "root", "classes", "classextensions", "classdef", "classextension", "optname", "superclass", "classvardecls", "classvardecl", "methods", "methoddef", "optsemi", "optcomma", "optequal", "funcbody", "cmdlinecode", "methbody", "primitive", "retval", "funretval", "blocklist1", "blocklistitem", "blocklist", "msgsend", "generator", "$@1", "$@2", "nextqual", "qual", "expr1", "valrangex1", "valrangeassign", "valrangexd", "valrange2", "valrange3", "expr", "adverb", "exprn", "exprseq", "arrayelems", "arrayelems1", "arglist1", "arglistv1", "keyarglist1", "keyarg", "optkeyarglist", "mavars", "mavarlist", "slotliteral", "blockliteral", "pushname", "pushliteral", "listliteral", "block", "funcvardecls", "funcvardecls1", "funcvardecl", "argdecls", "argdecls1", "constdeflist", "constdef", "slotdeflist0", "slotdeflist", "slotdef", "vardeflist0", "vardeflist", "vardef", "dictslotdef", "dictslotlist1", "dictslotlist", "rwslotdeflist", "rwslotdef", "dictlit2", "litdictslotdef", "litdictslotlist1", "litdictslotlist", "listlit", "listlit2", "literallistc", "literallist1", "rwspec", "rspec", "integer", "floatr", "accidental", "pie", "floatp", "name", "classname", "primname", "trueobj", "falseobj", "nilobj", "ascii", "symbol", "string", "pseudovar", "binop", "keybinop", "binop2", "curryarg", YY_NULLPTR }; static const char * yysymbol_name (yysymbol_kind_t yysymbol) { return yytname[yysymbol]; } #endif #define YYPACT_NINF (-477) #define yypact_value_is_default(Yyn) \ ((Yyn) == YYPACT_NINF) #define YYTABLE_NINF (-300) #define yytable_value_is_error(Yyn) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 23, 983, 60, 58, 60, 35, -477, -477, -477, -477, -477, -477, -477, -477, -477, -477, 53, 53, -477, -477, -477, -477, -477, 127, -477, 339, 53, 1815, 198, 1451, 879, 1815, 53, 43, -477, -477, -477, -477, -477, 40, -477, -477, -477, 1904, 59, 66, -477, -477, -477, -477, 1191, -477, 1191, -477, 108, 108, -477, -477, -477, 271, 103, -477, -477, -477, -477, -477, -477, -477, -477, 102, -477, -477, 67, -477, -23, -477, 109, 131, 182, 53, 53, -477, -477, -477, -477, -477, 150, 42, -477, 205, 931, -477, 1815, 1815, -477, -477, 159, 163, 164, 1815, 1815, 1503, -477, 339, -477, -477, -477, -477, 16, -477, 196, 99, 1191, 1191, -477, 176, 212, -477, 1815, 217, 813, 243, 1901, 247, 21, -477, 236, 1555, -477, -477, 82, -477, 249, 1815, -477, -477, -477, -477, -477, 1191, -477, -477, 1815, 1243, 174, -477, -477, -477, 1451, 1035, 174, -477, 60, 53, 240, -477, 53, 1815, 1815, 53, -477, 278, 276, 280, 54, 1191, 53, -477, -477, 53, -477, 661, -477, -477, 1191, 1815, -477, 1451, -477, -477, -477, 1815, 241, 47, -477, 1815, 1815, 1815, -477, 252, 255, 1191, 1451, -477, -477, -477, 183, -477, -477, 1815, 1901, 1867, -477, -477, -477, 261, 265, 108, -477, -477, 272, -477, -477, -477, -477, -477, -477, 1815, 53, 53, 1901, 1815, -477, 86, 282, 1607, 1087, 273, 28, 1815, 1904, -477, 1904, 1815, 174, 279, 306, -477, 275, 174, 279, 306, 308, -477, 1815, 745, -477, 303, -477, -477, -477, 1904, 309, 317, 53, -477, 53, -477, 321, -477, 162, -477, 1815, 13, -477, -477, 108, -477, -477, -477, -477, -477, -477, -477, 319, 323, 322, -477, 351, 1815, -477, -477, 1815, 1815, -477, -477, 363, -477, -477, 335, 357, -477, 1815, 1295, 174, 1904, 350, 358, -477, 349, 348, 1901, -477, 1901, -477, 1901, 1904, -477, -477, 355, 356, 1659, 373, 1815, 1815, 1815, 147, 174, 279, 306, 308, 1815, 1139, 174, -477, 401, 1815, -477, -477, 365, -477, 174, 1347, -477, 364, 374, 370, -477, -477, 371, 376, 374, 377, -477, 604, -477, -477, 372, 381, 384, 237, -477, -477, 383, 199, -477, -477, 53, 390, 1399, 1399, -477, 1815, -477, -477, 410, 1815, -477, 174, 279, 306, -477, 1901, 1867, -477, -477, -477, -477, 388, -477, 411, 414, 399, 1815, -477, 403, 408, 1711, 419, -477, 406, 409, 413, 1904, 174, 279, 306, 308, 430, 1815, 308, 185, -477, 174, -477, -477, 174, 439, 440, 127, 127, 442, 251, 251, 453, -477, 783, -477, -477, 53, 451, -477, 53, 301, 447, 444, 24, 454, -477, 1815, -477, 174, 449, 450, -477, -477, -477, 1815, 1815, 467, 1904, 1815, 472, 473, 458, 1815, 174, -477, 174, -477, 455, 456, 457, -477, -477, -477, 1815, -477, -477, -477, 127, 127, -477, -477, -477, -477, -477, -477, 286, -477, 53, 292, -477, 298, -477, 53, -477, 470, -477, 479, 1815, 1815, -477, 1399, -477, 1815, 484, -477, -477, 174, -477, 1904, 1904, 1815, 462, 1815, 1815, 483, 1904, -477, -477, 174, -477, 174, 1904, -477, -477, 154, 154, 237, -477, 251, 486, -477, -477, 453, 490, -477, 1815, 444, 444, -477, 444, 1815, -477, 1904, -477, 1904, 1904, 1815, -477, -477, 154, 154, -477, 1763, 477, 1763, 1920, -477, 699, -477, 699, 444, -477, -477, -477, 444, 1904, 1763, 1763, 1815, 482, -477, 476, -477, 491, -477, -477, -477, -477, -477, 495, 496, 813, -477, -477, -477, -477, -477, -477 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_int16 yydefact[] = { 5, 48, 0, 0, 2, 3, 7, 281, 268, 270, 272, 289, 290, 288, 283, 303, 0, 230, 287, 285, 286, 291, 274, 209, 282, 0, 223, 0, 209, 150, 241, 0, 0, 0, 41, 4, 33, 97, 94, 129, 106, 131, 130, 147, 27, 48, 93, 95, 92, 180, 48, 206, 48, 190, 182, 275, 276, 279, 183, 181, 132, 187, 188, 189, 184, 186, 185, 104, 96, 0, 1, 6, 14, 8, 0, 232, 234, 0, 231, 230, 223, 204, 269, 271, 273, 280, 0, 29, 225, 31, 241, 134, 0, 0, 204, 300, 152, 0, 29, 0, 0, 0, 292, 296, 294, 295, 297, 298, 223, 293, 0, 0, 48, 48, 239, 29, 0, 301, 302, 0, 27, 99, 258, 0, 167, 169, 0, 0, 296, 299, 0, 302, 143, 28, 149, 34, 40, 207, 39, 48, 278, 277, 0, 0, 56, 50, 53, 52, 150, 0, 65, 21, 0, 12, 0, 208, 0, 0, 0, 0, 215, 0, 231, 0, 29, 48, 0, 217, 30, 0, 32, 0, 80, 82, 48, 0, 100, 30, 151, 154, 120, 0, 0, 0, 101, 119, 0, 0, 98, 0, 0, 48, 30, 242, 103, 238, 0, 28, 49, 0, 258, 252, 260, 201, 200, 0, 29, 191, 192, 196, 0, 197, 198, 199, 193, 195, 194, 0, 0, 0, 258, 0, 158, 0, 0, 0, 0, 54, 0, 0, 148, 38, 136, 0, 0, 29, 29, 51, 0, 54, 29, 29, 29, 162, 0, 0, 15, 0, 13, 16, 233, 235, 0, 0, 0, 210, 0, 212, 0, 205, 0, 226, 0, 0, 228, 179, 171, 172, 176, 177, 178, 173, 175, 174, 0, 0, 0, 153, 155, 0, 124, 102, 125, 0, 121, 237, 0, 37, 36, 0, 0, 240, 0, 0, 57, 137, 0, 0, 250, 29, 0, 0, 254, 30, 259, 258, 140, 168, 170, 0, 0, 0, 105, 0, 0, 0, 0, 54, 29, 29, 29, 0, 0, 55, 79, 0, 0, 145, 144, 135, 160, 58, 30, 165, 0, 30, 0, 64, 66, 0, 0, 30, 0, 164, 297, 11, 22, 0, 0, 14, 21, 236, 216, 0, 0, 203, 218, 0, 0, 0, 0, 202, 0, 156, 126, 0, 123, 35, 0, 29, 29, 256, 0, 30, 253, 247, 249, 261, 0, 255, 108, 107, 0, 0, 159, 0, 0, 0, 133, 70, 0, 0, 0, 138, 54, 29, 29, 29, 0, 0, 29, 54, 62, 54, 69, 163, 54, 0, 0, 209, 209, 0, 262, 262, 266, 17, 0, 211, 213, 0, 0, 229, 0, 0, 0, 84, 181, 0, 157, 127, 122, 60, 0, 0, 248, 251, 257, 0, 0, 109, 141, 0, 114, 113, 0, 0, 54, 75, 54, 76, 0, 0, 0, 146, 161, 166, 0, 59, 68, 67, 209, 209, 204, 204, 16, 263, 265, 264, 0, 243, 0, 0, 267, 29, 220, 0, 9, 0, 219, 0, 0, 0, 81, 0, 89, 0, 0, 83, 128, 54, 63, 111, 110, 0, 0, 0, 0, 115, 142, 73, 71, 54, 78, 54, 139, 204, 204, 44, 44, 21, 19, 262, 245, 18, 20, 266, 0, 214, 0, 84, 84, 85, 84, 0, 61, 112, 74, 117, 116, 0, 77, 72, 44, 44, 284, 46, 27, 46, 0, 244, 0, 221, 0, 84, 91, 90, 86, 84, 118, 46, 46, 0, 0, 42, 46, 45, 0, 10, 246, 222, 88, 87, 0, 0, 27, 23, 43, 25, 24, 26, 47 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -477, -477, -477, -477, -477, 524, -477, 186, 79, -477, -341, -477, -117, -64, -477, 420, -477, -273, -263, -10, 500, -31, -138, 145, -477, -52, -477, -477, -247, -346, -477, -477, -477, -477, -477, -477, -27, -477, -477, 290, 402, -477, -102, -116, -136, 206, -57, -477, -477, -476, 341, -477, -477, -158, -477, -93, -8, 49, -17, 519, -477, 38, 475, 480, 392, 478, 1, 407, 378, -477, -477, 149, 63, -477, 191, -477, -477, -169, -477, -185, -477, -477, -477, -106, -477, -477, -15, -84, 4, 493, -477, -62, -46, -20, 158, 253, 318, -477, -240, 537, -13, -477 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { 0, 3, 4, 5, 71, 6, 247, 154, 350, 415, 245, 346, 134, 333, 171, 34, 35, 552, 535, 553, 36, 323, 145, 324, 37, 38, 274, 275, 484, 424, 39, 40, 41, 42, 110, 182, 43, 229, 44, 45, 97, 98, 223, 236, 400, 243, 334, 123, 124, 264, 46, 47, 48, 202, 49, 165, 50, 259, 81, 52, 473, 474, 86, 87, 88, 77, 74, 75, 114, 115, 116, 468, 469, 203, 298, 299, 300, 53, 204, 205, 206, 470, 475, 54, 55, 56, 57, 58, 59, 60, 536, 61, 62, 63, 64, 65, 66, 67, 117, 131, 132, 68 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 91, 174, 265, 198, 120, 348, 237, 146, 146, 416, 85, 94, 237, 242, 427, 296, 207, 119, 78, 7, 76, 76, 112, 169, 14, 155, 156, 7, 144, 150, 89, 7, 8, 241, 178, 309, 121, 125, 208, 140, 141, 235, 218, 297, 139, 24, 7, 240, 23, 1, 51, 193, 485, 24, 14, 142, 7, 24, 70, 122, 211, 2, 325, -224, 558, 266, 559, -299, 28, 282, 219, 14, 24, 2, 143, -224, 212, 119, 326, 51, 162, 167, 24, 76, 89, 7, 127, 267, 85, 122, 320, 168, 146, 257, 207, 207, 283, 152, 146, 137, 169, 51, 213, 168, 408, 191, 230, 133, 311, 268, 319, 24, 89, 153, 207, 232, 208, 208, 31, 224, 378, 185, 327, 316, 318, 269, 209, 23, 225, 186, 251, 22, 226, 312, 227, 313, 208, 521, 211, 211, 157, 79, 304, 376, 146, 377, 151, 28, 187, 148, 188, 270, 159, 149, 212, 212, 237, 248, 211, 158, 76, 137, 51, 253, 534, 294, 80, 16, 538, 387, 260, 166, 295, 89, 212, 146, 348, 370, 342, 336, 213, 213, 146, 339, 340, 237, 397, 146, 137, 175, 306, 369, 140, 237, 388, 207, 313, 207, 23, 207, 213, 356, 329, 331, 209, 209, 396, 23, -227, 23, 176, 357, 79, 177, 434, 297, 456, 208, 28, 208, 395, 208, 307, 308, 209, 192, -227, 28, 92, 28, 160, 156, 328, 293, -227, 374, 170, 80, 418, 211, 137, 211, 146, 211, -227, 537, 93, 184, 419, 347, 412, 140, 413, 414, -227, 212, 392, 212, 353, 212, 354, 390, 391, 194, 556, 146, 207, 207, 196, 549, 550, 146, 544, 545, 199, 546, 562, 563, 217, 146, 214, 213, 220, 213, 249, 213, 465, 466, 208, 208, 228, 467, 281, 237, 393, 23, 560, 23, 348, 254, 561, 256, 142, 287, 321, 209, 288, 209, 302, 209, 211, 211, 432, 433, 303, 28, 146, 28, 305, 96, 111, 143, 337, 322, 255, 156, 212, 212, 332, 271, 480, 481, 314, 452, 510, 511, 455, 431, 450, 451, 513, 511, 146, 82, 83, 84, 514, 168, 407, 146, 349, 146, 213, 213, 146, 335, 440, 341, 214, 214, 351, 420, 22, 426, 426, 352, 355, 361, 359, 507, 508, 265, 360, 265, 146, 215, 209, 209, 214, 146, 111, 362, 172, 173, 338, 366, 367, 186, 372, 179, 180, 183, 462, 463, 146, 144, 146, 371, 373, 375, 147, 147, 379, 380, 383, 82, 130, 95, 195, 515, 491, 492, 532, 533, 152, 401, 409, 222, 498, 555, 347, 402, 403, 477, 272, 410, 479, 404, 406, 504, 486, 417, 429, 222, 266, 436, 266, 146, 96, 222, 216, 421, 437, 505, 506, 438, 439, 570, 252, 146, 445, 146, 441, 215, 215, 442, 267, 446, 267, 214, 447, 214, 389, 214, 448, 277, 525, 278, 527, 528, 136, 280, 138, 215, 512, 284, 285, 286, 268, 516, 268, 453, 290, 460, 461, 147, 464, 426, 472, 273, 478, 147, 482, 483, 269, 69, 269, 72, 493, 487, 489, 490, 548, 495, 496, 497, 501, 502, 503, 517, 518, 310, 523, 526, 529, 222, 222, 540, 216, 216, 270, 542, 270, 330, 564, 197, 126, 565, 551, 73, 214, 214, 189, 190, 343, 411, 567, 147, 216, 449, 568, 569, 347, 509, 566, 135, 457, 405, 458, 113, 238, 459, 358, 541, 215, 163, 215, 161, 215, 231, 164, 261, 471, 250, 435, 0, 99, 118, 147, 363, 291, 0, 364, 365, 539, 147, 0, 0, 0, 0, 147, 0, 195, 222, 0, 258, 0, 0, 0, 0, 0, 499, 0, 500, 276, 0, 0, 0, 0, 0, 0, 382, 0, 384, 385, 386, 0, 7, 0, 0, 0, 289, 222, 0, 0, 210, 398, 0, 0, 216, 0, 216, 384, 216, 0, 215, 215, 118, 0, 0, 0, 0, 0, 24, 524, 147, 102, 0, 128, 104, 105, 106, 107, 129, 109, 246, 530, 0, 531, 425, 425, 0, 428, 0, 0, 0, 430, 0, 147, 0, 0, 0, 0, 0, 147, 8, 9, 10, 11, 12, 13, 0, 147, 0, 0, 0, 0, 444, 18, 19, 20, 0, 0, 0, 22, 99, 244, 0, 0, 454, 216, 216, 0, 210, 210, 25, 0, 0, 271, 0, 271, 0, 0, 8, 9, 10, 11, 12, 13, 147, 0, 262, 0, 210, 279, 263, 18, 19, 20, 488, 0, 0, 22, 0, 0, 0, 0, 0, 0, 292, 0, 494, 0, 25, 0, 147, 0, 0, 301, 0, 0, 0, 147, 0, 147, 0, 0, 147, 7, 0, 0, 0, 0, 263, 0, 0, 126, 0, 0, 0, 0, 0, 0, 244, 0, 0, 0, 147, 0, 0, 519, 520, 147, 425, 24, 522, 0, 102, 0, 128, 104, 105, 344, 107, 129, 109, 7, 147, 0, 147, 345, 0, 0, 272, 210, 272, 210, 0, 210, 0, 0, 0, 0, 0, 0, 0, 0, 0, 543, 0, 0, 0, 24, 547, 0, 102, 0, 128, 104, 105, 344, 107, 129, 109, 0, 554, 0, 554, 476, 0, 147, 0, 0, 0, 0, 0, 0, 0, 0, 554, 554, 0, 147, 0, 147, 102, 95, 128, 104, 105, 106, 107, 129, 109, 130, 0, 0, 0, 273, 244, 273, 197, 0, 0, 0, 210, 210, 0, 0, 244, 0, 0, 244, 0, 0, 0, 0, 0, 244, 0, 0, 0, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 16, 17, 0, 0, 18, 19, 20, 21, 0, 100, 22, 23, 0, 0, 0, 0, 24, 101, 301, 102, 95, 103, 104, 105, 106, 107, 108, 109, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 100, 22, 23, 0, 0, 0, 0, 24, 101, 0, 102, 95, 103, 104, 105, 106, 107, 129, 109, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 16, 17, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 26, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 30, 0, 31, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 233, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 239, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 233, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 317, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 233, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 394, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 16, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 31, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 233, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 234, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 233, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 368, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 399, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 422, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 423, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 181, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 221, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 315, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 381, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 443, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 551, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 15, 0, 0, 0, 0, 18, 19, 20, 21, 0, 0, 22, 23, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 0, 29, 0, 0, 0, 90, 0, 0, 32, 33, 7, 8, 9, 10, 11, 12, 13, 0, 14, 0, 0, 0, 0, 0, 18, 19, 20, 0, 0, 0, 22, 0, 0, 0, 0, 0, 24, 0, 0, 0, 95, 25, 0, 0, 7, 8, 9, 10, 11, 12, 13, 0, 14, 200, 0, 0, 0, 201, 18, 19, 20, 0, 0, 7, 22, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 25, 102, 95, 128, 104, 105, 106, 107, 129, 109, 130, 0, 200, 0, 24, 0, 201, 102, 0, 128, 104, 105, 344, 107, 129, 109, 0, 0, 0, 0, 557 }; static const yytype_int16 yycheck[] = { 27, 94, 171, 120, 31, 245, 144, 59, 60, 350, 25, 28, 150, 149, 360, 200, 122, 30, 17, 3, 16, 17, 30, 87, 11, 48, 49, 3, 59, 60, 26, 3, 4, 149, 98, 220, 32, 33, 122, 54, 55, 143, 21, 201, 52, 29, 3, 149, 24, 26, 1, 115, 28, 29, 11, 31, 3, 29, 0, 46, 122, 38, 34, 21, 540, 171, 542, 51, 44, 22, 49, 11, 29, 38, 50, 21, 122, 90, 50, 30, 79, 39, 29, 79, 80, 3, 46, 171, 103, 46, 226, 49, 144, 39, 200, 201, 49, 30, 150, 50, 164, 52, 122, 49, 344, 113, 133, 48, 22, 171, 226, 29, 108, 46, 220, 142, 200, 201, 52, 37, 305, 22, 228, 225, 226, 171, 122, 24, 46, 30, 157, 23, 50, 47, 130, 49, 220, 483, 200, 201, 31, 14, 206, 301, 196, 303, 44, 44, 49, 46, 51, 171, 21, 50, 200, 201, 294, 153, 220, 50, 156, 112, 113, 159, 10, 196, 39, 13, 509, 22, 166, 21, 199, 169, 220, 227, 416, 293, 242, 236, 200, 201, 234, 240, 241, 323, 322, 239, 139, 30, 217, 293, 207, 331, 47, 301, 49, 303, 24, 305, 220, 39, 229, 234, 200, 201, 322, 24, 3, 24, 47, 49, 14, 49, 372, 373, 31, 301, 44, 303, 322, 305, 218, 219, 220, 49, 21, 44, 30, 44, 48, 49, 228, 50, 29, 299, 31, 39, 39, 301, 191, 303, 294, 305, 39, 508, 48, 51, 49, 245, 13, 266, 15, 16, 49, 301, 320, 303, 254, 305, 256, 318, 319, 51, 537, 317, 372, 373, 51, 532, 533, 323, 519, 520, 31, 522, 549, 550, 31, 331, 122, 301, 46, 303, 44, 305, 35, 36, 372, 373, 41, 40, 51, 431, 321, 24, 543, 24, 538, 21, 547, 21, 31, 51, 31, 301, 51, 303, 47, 305, 372, 373, 369, 370, 49, 44, 368, 44, 46, 29, 30, 50, 47, 50, 48, 49, 372, 373, 49, 171, 29, 30, 50, 397, 48, 49, 400, 368, 395, 396, 48, 49, 394, 4, 5, 6, 48, 49, 344, 401, 47, 403, 372, 373, 406, 49, 383, 49, 200, 201, 51, 357, 23, 359, 360, 48, 45, 45, 49, 462, 463, 540, 49, 542, 426, 122, 372, 373, 220, 431, 90, 30, 92, 93, 239, 22, 51, 30, 30, 99, 100, 101, 409, 410, 446, 426, 448, 47, 49, 51, 59, 60, 47, 47, 31, 4, 41, 33, 118, 473, 437, 438, 505, 506, 30, 51, 44, 127, 445, 536, 416, 51, 51, 419, 171, 44, 422, 51, 51, 456, 426, 48, 22, 143, 540, 47, 542, 489, 148, 149, 122, 51, 31, 460, 461, 31, 47, 564, 158, 501, 31, 503, 49, 200, 201, 47, 540, 51, 542, 301, 51, 303, 317, 305, 51, 175, 493, 177, 495, 496, 50, 181, 52, 220, 470, 185, 186, 187, 540, 475, 542, 51, 192, 44, 44, 144, 44, 483, 35, 171, 39, 150, 45, 49, 540, 2, 542, 4, 31, 45, 51, 51, 529, 31, 31, 47, 51, 51, 51, 39, 31, 221, 28, 51, 31, 225, 226, 31, 200, 201, 540, 31, 542, 233, 551, 48, 33, 45, 52, 5, 372, 373, 112, 113, 244, 349, 45, 196, 220, 394, 45, 45, 538, 464, 554, 45, 401, 341, 403, 30, 148, 406, 262, 515, 301, 80, 303, 79, 305, 139, 80, 169, 413, 156, 373, -1, 29, 30, 227, 279, 192, -1, 282, 283, 511, 234, -1, -1, -1, -1, 239, -1, 292, 293, -1, 165, -1, -1, -1, -1, -1, 446, -1, 448, 174, -1, -1, -1, -1, -1, -1, 311, -1, 313, 314, 315, -1, 3, -1, -1, -1, 191, 322, -1, -1, 122, 326, -1, -1, 301, -1, 303, 332, 305, -1, 372, 373, 90, -1, -1, -1, -1, -1, 29, 489, 294, 32, -1, 34, 35, 36, 37, 38, 39, 40, 152, 501, -1, 503, 359, 360, -1, 362, -1, -1, -1, 366, -1, 317, -1, -1, -1, -1, -1, 323, 4, 5, 6, 7, 8, 9, -1, 331, -1, -1, -1, -1, 387, 17, 18, 19, -1, -1, -1, 23, 148, 149, -1, -1, 399, 372, 373, -1, 200, 201, 34, -1, -1, 540, -1, 542, -1, -1, 4, 5, 6, 7, 8, 9, 368, -1, 50, -1, 220, 177, 54, 17, 18, 19, 429, -1, -1, 23, -1, -1, -1, -1, -1, -1, 192, -1, 441, -1, 34, -1, 394, -1, -1, 201, -1, -1, -1, 401, -1, 403, -1, -1, 406, 3, -1, -1, -1, -1, 54, -1, -1, 263, -1, -1, -1, -1, -1, -1, 226, -1, -1, -1, 426, -1, -1, 480, 481, 431, 483, 29, 485, -1, 32, -1, 34, 35, 36, 37, 38, 39, 40, 3, 446, -1, 448, 45, -1, -1, 540, 301, 542, 303, -1, 305, -1, -1, -1, -1, -1, -1, -1, -1, -1, 518, -1, -1, -1, 29, 523, -1, 32, -1, 34, 35, 36, 37, 38, 39, 40, -1, 535, -1, 537, 45, -1, 489, -1, -1, -1, -1, -1, -1, -1, -1, 549, 550, -1, 501, -1, 503, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, -1, -1, -1, 540, 322, 542, 48, -1, -1, -1, 372, 373, -1, -1, 332, -1, -1, 335, -1, -1, -1, -1, -1, 341, -1, -1, -1, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, 13, 14, -1, -1, 17, 18, 19, 20, -1, 22, 23, 24, -1, -1, -1, -1, 29, 30, 373, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, 22, 23, 24, -1, -1, -1, -1, 29, 30, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, 13, 14, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, 39, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, 52, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, 51, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, 51, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, 51, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, 13, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, 52, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, 51, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, 51, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, 37, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, 13, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, 30, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, 22, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, 22, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, 22, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, 47, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, 47, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, 52, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, 12, -1, -1, -1, -1, 17, 18, 19, 20, -1, -1, 23, 24, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, 42, -1, 44, -1, 46, -1, -1, -1, 50, -1, -1, 53, 54, 3, 4, 5, 6, 7, 8, 9, -1, 11, -1, -1, -1, -1, -1, 17, 18, 19, -1, -1, -1, 23, -1, -1, -1, -1, -1, 29, -1, -1, -1, 33, 34, -1, -1, 3, 4, 5, 6, 7, 8, 9, -1, 11, 46, -1, -1, -1, 50, 17, 18, 19, -1, -1, 3, 23, -1, -1, -1, -1, -1, 29, -1, -1, -1, -1, 34, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, -1, 46, -1, 29, -1, 50, 32, -1, 34, 35, 36, 37, 38, 39, 40, -1, -1, -1, -1, 45 }; /* YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 26, 38, 56, 57, 58, 60, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 17, 18, 19, 20, 23, 24, 29, 34, 39, 42, 44, 46, 50, 52, 53, 54, 70, 71, 75, 79, 80, 85, 86, 87, 88, 91, 93, 94, 105, 106, 107, 109, 111, 112, 114, 132, 138, 139, 140, 141, 142, 143, 144, 146, 147, 148, 149, 150, 151, 152, 156, 144, 0, 59, 144, 60, 121, 122, 143, 120, 121, 14, 39, 113, 4, 5, 6, 141, 117, 118, 119, 143, 50, 91, 30, 48, 113, 33, 94, 95, 96, 154, 22, 30, 32, 34, 35, 36, 37, 38, 39, 40, 89, 94, 111, 114, 123, 124, 125, 153, 154, 155, 91, 143, 46, 102, 103, 143, 144, 46, 34, 39, 41, 154, 155, 48, 67, 75, 70, 112, 70, 111, 141, 141, 31, 50, 76, 77, 80, 105, 46, 50, 76, 44, 30, 46, 62, 48, 49, 31, 50, 21, 48, 120, 121, 117, 118, 110, 21, 39, 49, 68, 31, 69, 94, 94, 110, 30, 47, 49, 68, 94, 94, 22, 90, 94, 51, 22, 30, 49, 51, 70, 70, 111, 49, 68, 51, 94, 51, 48, 67, 31, 46, 50, 108, 128, 133, 134, 135, 138, 142, 143, 144, 146, 147, 148, 149, 150, 151, 31, 21, 49, 46, 22, 94, 97, 37, 46, 50, 143, 41, 92, 91, 70, 91, 37, 51, 97, 98, 77, 95, 51, 97, 98, 99, 100, 154, 65, 144, 61, 143, 44, 122, 91, 94, 143, 21, 48, 21, 39, 70, 112, 143, 119, 50, 54, 104, 132, 138, 142, 146, 147, 148, 149, 150, 151, 81, 82, 70, 94, 94, 154, 94, 51, 22, 49, 94, 94, 94, 51, 51, 70, 94, 123, 154, 50, 76, 91, 134, 108, 129, 130, 131, 154, 47, 49, 68, 46, 91, 143, 143, 134, 94, 22, 47, 49, 50, 22, 97, 51, 97, 98, 99, 31, 50, 76, 78, 34, 50, 138, 143, 91, 94, 76, 49, 68, 101, 49, 101, 47, 78, 101, 101, 49, 68, 94, 37, 45, 66, 143, 153, 47, 63, 51, 48, 143, 143, 45, 39, 49, 94, 49, 49, 45, 30, 94, 94, 94, 22, 51, 51, 97, 98, 47, 30, 49, 68, 51, 108, 108, 134, 47, 47, 47, 94, 31, 94, 94, 94, 22, 47, 78, 101, 101, 68, 91, 51, 97, 98, 99, 94, 37, 99, 51, 51, 51, 51, 100, 51, 143, 153, 44, 44, 62, 13, 15, 16, 64, 65, 48, 39, 49, 143, 51, 13, 30, 84, 94, 143, 84, 94, 22, 94, 76, 101, 101, 108, 129, 47, 31, 31, 47, 91, 49, 47, 47, 94, 31, 51, 51, 51, 78, 101, 101, 68, 51, 94, 68, 31, 78, 78, 78, 44, 44, 113, 113, 44, 35, 36, 40, 126, 127, 136, 126, 35, 115, 116, 137, 45, 143, 39, 143, 29, 30, 45, 49, 83, 28, 143, 45, 94, 51, 51, 91, 91, 31, 94, 31, 31, 47, 91, 78, 78, 51, 51, 51, 91, 113, 113, 110, 110, 63, 48, 49, 143, 48, 48, 68, 143, 39, 31, 94, 94, 84, 94, 28, 78, 91, 51, 91, 91, 31, 78, 78, 110, 110, 10, 73, 145, 73, 65, 127, 31, 116, 31, 94, 83, 83, 83, 94, 91, 73, 73, 52, 72, 74, 94, 67, 72, 45, 104, 104, 83, 83, 72, 72, 91, 45, 74, 45, 45, 45, 67 }; /* YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. */ static const yytype_uint8 yyr1[] = { 0, 55, 56, 56, 56, 57, 57, 58, 58, 59, 59, 60, 61, 61, 62, 62, 63, 63, 64, 64, 64, 65, 65, 66, 66, 66, 66, 67, 67, 68, 68, 69, 69, 70, 70, 71, 71, 71, 71, 71, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76, 76, 77, 77, 78, 78, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 81, 80, 82, 80, 83, 83, 84, 84, 84, 84, 84, 84, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 87, 87, 87, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 92, 92, 92, 92, 93, 93, 94, 95, 95, 96, 96, 96, 96, 96, 96, 97, 97, 98, 98, 99, 99, 100, 101, 101, 102, 102, 103, 103, 104, 104, 104, 104, 104, 104, 104, 104, 104, 105, 106, 107, 107, 107, 107, 107, 107, 107, 107, 107, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 109, 109, 110, 110, 111, 111, 112, 113, 113, 113, 113, 113, 113, 114, 114, 114, 114, 114, 115, 115, 116, 117, 117, 118, 118, 119, 119, 119, 120, 120, 121, 121, 122, 122, 122, 123, 123, 124, 124, 125, 125, 126, 126, 127, 127, 128, 129, 129, 130, 130, 131, 131, 132, 132, 133, 133, 134, 134, 135, 135, 136, 136, 136, 136, 137, 137, 138, 138, 139, 139, 140, 140, 141, 142, 142, 142, 142, 142, 142, 143, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 153, 153, 153, 153, 153, 153, 153, 154, 155, 155, 156 }; /* YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. */ static const yytype_int8 yyr2[] = { 0, 2, 1, 1, 2, 0, 2, 1, 2, 6, 9, 5, 0, 1, 0, 2, 0, 2, 3, 3, 3, 0, 2, 7, 8, 7, 8, 0, 1, 0, 1, 0, 1, 1, 2, 5, 4, 4, 3, 2, 2, 1, 1, 2, 0, 2, 0, 3, 0, 3, 1, 2, 1, 1, 0, 1, 2, 4, 4, 6, 6, 8, 5, 7, 4, 2, 4, 6, 6, 5, 5, 7, 8, 7, 8, 6, 6, 8, 7, 4, 0, 7, 0, 7, 0, 2, 4, 5, 5, 2, 4, 4, 1, 1, 1, 1, 1, 1, 3, 2, 3, 3, 4, 3, 1, 4, 1, 5, 5, 6, 7, 7, 8, 6, 6, 7, 8, 8, 9, 2, 2, 3, 5, 4, 2, 2, 3, 4, 5, 1, 1, 1, 1, 5, 2, 4, 3, 4, 5, 7, 4, 6, 7, 0, 2, 2, 4, 1, 3, 2, 0, 2, 1, 3, 2, 3, 4, 5, 1, 3, 2, 4, 1, 3, 2, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 0, 2, 1, 2, 3, 0, 3, 5, 3, 5, 7, 3, 5, 3, 5, 7, 1, 3, 4, 0, 1, 1, 3, 1, 3, 5, 0, 1, 1, 3, 1, 3, 4, 3, 2, 1, 3, 0, 2, 1, 3, 2, 4, 3, 3, 2, 1, 3, 0, 2, 4, 5, 3, 4, 0, 2, 1, 3, 0, 1, 1, 1, 0, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; enum { YYENOMEM = -2 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYNOMEM goto yyexhaustedlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Backward compatibility with an undocumented macro. Use YYerror or YYUNDEF. */ #define YYERRCODE YYUNDEF /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Kind, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) { FILE *yyoutput = yyo; YY_USE (yyoutput); if (!yyvaluep) return; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep) { YYFPRINTF (yyo, "%s %s (", yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind)); yy_symbol_value_print (yyo, yykind, yyvaluep); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp, int yyrule) { int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]), &yyvsp[(yyi + 1) - (yynrhs)]); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) ((void) 0) # define YY_SYMBOL_PRINT(Title, Kind, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif /* Context of a parse error. */ typedef struct { yy_state_t *yyssp; yysymbol_kind_t yytoken; } yypcontext_t; /* Put in YYARG at most YYARGN of the expected tokens given the current YYCTX, and return the number of tokens stored in YYARG. If YYARG is null, return the number of expected tokens (guaranteed to be less than YYNTOKENS). Return YYENOMEM on memory exhaustion. Return 0 if there are more than YYARGN expected tokens, yet fill YYARG up to YYARGN. */ static int yypcontext_expected_tokens (const yypcontext_t *yyctx, yysymbol_kind_t yyarg[], int yyargn) { /* Actual size of YYARG. */ int yycount = 0; int yyn = yypact[+*yyctx->yyssp]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYSYMBOL_YYerror && !yytable_value_is_error (yytable[yyx + yyn])) { if (!yyarg) ++yycount; else if (yycount == yyargn) return 0; else yyarg[yycount++] = YY_CAST (yysymbol_kind_t, yyx); } } if (yyarg && yycount == 0 && 0 < yyargn) yyarg[0] = YYSYMBOL_YYEMPTY; return yycount; } #ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen(S) (YY_CAST (YYPTRDIFF_T, strlen (S))) # else /* Return the length of YYSTR. */ static YYPTRDIFF_T yystrlen (const char *yystr) { YYPTRDIFF_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif #endif #ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif #endif #ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYPTRDIFF_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYPTRDIFF_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; else goto append; append: default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (yyres) return yystpcpy (yyres, yystr) - yyres; else return yystrlen (yystr); } #endif static int yy_syntax_error_arguments (const yypcontext_t *yyctx, yysymbol_kind_t yyarg[], int yyargn) { /* Actual size of YYARG. */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yyctx->yytoken != YYSYMBOL_YYEMPTY) { int yyn; if (yyarg) yyarg[yycount] = yyctx->yytoken; ++yycount; yyn = yypcontext_expected_tokens (yyctx, yyarg ? yyarg + 1 : yyarg, yyargn - 1); if (yyn == YYENOMEM) return YYENOMEM; else yycount += yyn; } return yycount; } /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return -1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return YYENOMEM if the required number of bytes is too large to store. */ static int yysyntax_error (YYPTRDIFF_T *yymsg_alloc, char **yymsg, const yypcontext_t *yyctx) { enum { YYARGS_MAX = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat: reported tokens (one for the "unexpected", one per "expected"). */ yysymbol_kind_t yyarg[YYARGS_MAX]; /* Cumulated lengths of YYARG. */ YYPTRDIFF_T yysize = 0; /* Actual size of YYARG. */ int yycount = yy_syntax_error_arguments (yyctx, yyarg, YYARGS_MAX); if (yycount == YYENOMEM) return YYENOMEM; switch (yycount) { #define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); #undef YYCASE_ } /* Compute error message size. Don't count the "%s"s, but reserve room for the terminator. */ yysize = yystrlen (yyformat) - 2 * yycount + 1; { int yyi; for (yyi = 0; yyi < yycount; ++yyi) { YYPTRDIFF_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyarg[yyi]]); if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM) yysize = yysize1; else return YYENOMEM; } } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return -1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yytname[yyarg[yyi++]]); yyformat += 2; } else { ++yyp; ++yyformat; } } return 0; } /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, yysymbol_kind_t yykind, YYSTYPE *yyvaluep) { YY_USE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YY_USE (yykind); YY_IGNORE_MAYBE_UNINITIALIZED_END } /* Lookahead token kind. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (void) { yy_state_fast_t yystate = 0; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus = 0; /* Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* Their size. */ YYPTRDIFF_T yystacksize = YYINITDEPTH; /* The state stack: array, bottom, top. */ yy_state_t yyssa[YYINITDEPTH]; yy_state_t *yyss = yyssa; yy_state_t *yyssp = yyss; /* The semantic value stack: array, bottom, top. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp = yyvs; int yyn; /* The return value of yyparse. */ int yyresult; /* Lookahead symbol kind. */ yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYPTRDIFF_T yymsg_alloc = sizeof yymsgbuf; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; /*--------------------------------------------------------------------. | yysetstate -- set current state (the top of the stack) to yystate. | `--------------------------------------------------------------------*/ yysetstate: YYDPRINTF ((stderr, "Entering state %d\n", yystate)); YY_ASSERT (0 <= yystate && yystate < YYNSTATES); YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END YY_STACK_PRINT (yyss, yyssp); if (yyss + yystacksize - 1 <= yyssp) #if !defined yyoverflow && !defined YYSTACK_RELOCATE YYNOMEM; #else { /* Get the current used size of the three stacks, in elements. */ YYPTRDIFF_T yysize = yyssp - yyss + 1; # if defined yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ yy_state_t *yyss1 = yyss; YYSTYPE *yyvs1 = yyvs; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * YYSIZEOF (*yyssp), &yyvs1, yysize * YYSIZEOF (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } # else /* defined YYSTACK_RELOCATE */ /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) YYNOMEM; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yy_state_t *yyss1 = yyss; union yyalloc *yyptr = YY_CAST (union yyalloc *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize)))); if (! yyptr) YYNOMEM; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YY_IGNORE_USELESS_CAST_BEGIN YYDPRINTF ((stderr, "Stack size increased to %ld\n", YY_CAST (long, yystacksize))); YY_IGNORE_USELESS_CAST_END if (yyss + yystacksize - 1 <= yyssp) YYABORT; } #endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */ if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either empty, or end-of-input, or a valid lookahead. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token\n")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = YYEOF; yytoken = YYSYMBOL_YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else if (yychar == YYerror) { /* The scanner already issued an error message, process directly to error recovery. But do not keep the error token as lookahead, it is too special and may lead us to an endless loop in error recovery. */ yychar = YYUNDEF; yytoken = YYSYMBOL_YYerror; goto yyerrlab1; } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Discard the shifted token. */ yychar = YYEMPTY; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* root: classes */ #line 40 "lang11d" { gRootParseNode = (PyrParseNode*)yyvsp[0]; gParserResult = 1; } #line 2193 "lang11d_tab.cpp" break; case 3: /* root: classextensions */ #line 42 "lang11d" { gRootParseNode = (PyrParseNode*)yyvsp[0]; gParserResult = 1; } #line 2199 "lang11d_tab.cpp" break; case 4: /* root: INTERPRET cmdlinecode */ #line 44 "lang11d" { gRootParseNode = (PyrParseNode*)yyvsp[0]; gParserResult = 2; } #line 2205 "lang11d_tab.cpp" break; case 5: /* classes: %empty */ #line 47 "lang11d" { yyval = 0; } #line 2211 "lang11d_tab.cpp" break; case 6: /* classes: classes classdef */ #line 49 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2217 "lang11d_tab.cpp" break; case 8: /* classextensions: classextensions classextension */ #line 54 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2223 "lang11d_tab.cpp" break; case 9: /* classdef: classname superclass '{' classvardecls methods '}' */ #line 58 "lang11d" { yyval = (intptr_t)newPyrClassNode((PyrSlotNode*)yyvsp[-5], (PyrSlotNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-2], (PyrMethodNode*)yyvsp[-1], 0); } #line 2231 "lang11d_tab.cpp" break; case 10: /* classdef: classname '[' optname ']' superclass '{' classvardecls methods '}' */ #line 62 "lang11d" { yyval = (intptr_t)newPyrClassNode((PyrSlotNode*)yyvsp[-8], (PyrSlotNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-2], (PyrMethodNode*)yyvsp[-1], (PyrSlotNode*)yyvsp[-6]); } #line 2240 "lang11d_tab.cpp" break; case 11: /* classextension: '+' classname '{' methods '}' */ #line 69 "lang11d" { yyval = (intptr_t)newPyrClassExtNode((PyrSlotNode*)yyvsp[-3], (PyrMethodNode*)yyvsp[-1]); } #line 2248 "lang11d_tab.cpp" break; case 12: /* optname: %empty */ #line 74 "lang11d" { yyval = 0; } #line 2254 "lang11d_tab.cpp" break; case 14: /* superclass: %empty */ #line 78 "lang11d" { yyval = 0; } #line 2260 "lang11d_tab.cpp" break; case 15: /* superclass: ':' classname */ #line 80 "lang11d" { yyval = yyvsp[0]; } #line 2266 "lang11d_tab.cpp" break; case 16: /* classvardecls: %empty */ #line 83 "lang11d" { yyval = 0; } #line 2272 "lang11d_tab.cpp" break; case 17: /* classvardecls: classvardecls classvardecl */ #line 85 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2278 "lang11d_tab.cpp" break; case 18: /* classvardecl: CLASSVAR rwslotdeflist ';' */ #line 89 "lang11d" { yyval = (intptr_t)newPyrVarListNode((PyrVarDefNode*)yyvsp[-1], varClass); } #line 2284 "lang11d_tab.cpp" break; case 19: /* classvardecl: VAR rwslotdeflist ';' */ #line 91 "lang11d" { yyval = (intptr_t)newPyrVarListNode((PyrVarDefNode*)yyvsp[-1], varInst); } #line 2290 "lang11d_tab.cpp" break; case 20: /* classvardecl: SC_CONST constdeflist ';' */ #line 93 "lang11d" { yyval = (intptr_t)newPyrVarListNode((PyrVarDefNode*)yyvsp[-1], varConst); } #line 2296 "lang11d_tab.cpp" break; case 21: /* methods: %empty */ #line 96 "lang11d" { yyval = 0; } #line 2302 "lang11d_tab.cpp" break; case 22: /* methods: methods methoddef */ #line 98 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2308 "lang11d_tab.cpp" break; case 23: /* methoddef: name '{' argdecls funcvardecls primitive methbody '}' */ #line 102 "lang11d" { yyval = (intptr_t)newPyrMethodNode((PyrSlotNode*)yyvsp[-6], (PyrSlotNode*)yyvsp[-2], (PyrArgListNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1], 0); } #line 2315 "lang11d_tab.cpp" break; case 24: /* methoddef: '*' name '{' argdecls funcvardecls primitive methbody '}' */ #line 105 "lang11d" { yyval = (intptr_t)newPyrMethodNode((PyrSlotNode*)yyvsp[-6], (PyrSlotNode*)yyvsp[-2], (PyrArgListNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1], 1); } #line 2322 "lang11d_tab.cpp" break; case 25: /* methoddef: binop '{' argdecls funcvardecls primitive methbody '}' */ #line 108 "lang11d" { yyval = (intptr_t)newPyrMethodNode((PyrSlotNode*)yyvsp[-6], (PyrSlotNode*)yyvsp[-2], (PyrArgListNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1], 0); } #line 2329 "lang11d_tab.cpp" break; case 26: /* methoddef: '*' binop '{' argdecls funcvardecls primitive methbody '}' */ #line 111 "lang11d" { yyval = (intptr_t)newPyrMethodNode((PyrSlotNode*)yyvsp[-6], (PyrSlotNode*)yyvsp[-2], (PyrArgListNode*)yyvsp[-4], (PyrVarListNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1], 1); } #line 2336 "lang11d_tab.cpp" break; case 34: /* funcbody: exprseq funretval */ #line 129 "lang11d" { yyval = (intptr_t)newPyrDropNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2342 "lang11d_tab.cpp" break; case 35: /* cmdlinecode: '(' argdecls1 funcvardecls1 funcbody ')' */ #line 133 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-3], (PyrVarListNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-1], false); } #line 2348 "lang11d_tab.cpp" break; case 36: /* cmdlinecode: '(' argdecls1 funcbody ')' */ #line 135 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-2], NULL, (PyrParseNode*)yyvsp[-1], false); } #line 2354 "lang11d_tab.cpp" break; case 37: /* cmdlinecode: '(' funcvardecls1 funcbody ')' */ #line 137 "lang11d" { yyval = (intptr_t)newPyrBlockNode(NULL, (PyrVarListNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-1], false); } #line 2360 "lang11d_tab.cpp" break; case 38: /* cmdlinecode: argdecls1 funcvardecls1 funcbody */ #line 139 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-2], (PyrVarListNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0], false); } #line 2366 "lang11d_tab.cpp" break; case 39: /* cmdlinecode: argdecls1 funcbody */ #line 141 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-1], NULL, (PyrParseNode*)yyvsp[0], false); } #line 2372 "lang11d_tab.cpp" break; case 40: /* cmdlinecode: funcvardecls1 funcbody */ #line 143 "lang11d" { yyval = (intptr_t)newPyrBlockNode(NULL, (PyrVarListNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0], false); } #line 2378 "lang11d_tab.cpp" break; case 41: /* cmdlinecode: funcbody */ #line 145 "lang11d" { yyval = (intptr_t)newPyrBlockNode(NULL, NULL, (PyrParseNode*)yyvsp[0], false); } #line 2384 "lang11d_tab.cpp" break; case 43: /* methbody: exprseq retval */ #line 150 "lang11d" { yyval = (intptr_t)newPyrDropNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2390 "lang11d_tab.cpp" break; case 44: /* primitive: %empty */ #line 153 "lang11d" { yyval = 0; } #line 2396 "lang11d_tab.cpp" break; case 45: /* primitive: primname optsemi */ #line 155 "lang11d" { yyval = yyvsp[-1]; } #line 2402 "lang11d_tab.cpp" break; case 46: /* retval: %empty */ #line 159 "lang11d" { yyval = (intptr_t)newPyrReturnNode(NULL); } #line 2408 "lang11d_tab.cpp" break; case 47: /* retval: '^' expr optsemi */ #line 161 "lang11d" { yyval = (intptr_t)newPyrReturnNode((PyrParseNode*)yyvsp[-1]); } #line 2414 "lang11d_tab.cpp" break; case 48: /* funretval: %empty */ #line 165 "lang11d" { yyval = (intptr_t)newPyrBlockReturnNode(); } #line 2420 "lang11d_tab.cpp" break; case 49: /* funretval: '^' expr optsemi */ #line 167 "lang11d" { yyval = (intptr_t)newPyrReturnNode((PyrParseNode*)yyvsp[-1]); } #line 2426 "lang11d_tab.cpp" break; case 51: /* blocklist1: blocklist1 blocklistitem */ #line 172 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2434 "lang11d_tab.cpp" break; case 54: /* blocklist: %empty */ #line 181 "lang11d" { yyval = 0; } #line 2440 "lang11d_tab.cpp" break; case 56: /* msgsend: name blocklist1 */ #line 186 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0], 0, 0); } #line 2448 "lang11d_tab.cpp" break; case 57: /* msgsend: '(' binop2 ')' blocklist1 */ #line 190 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], 0, 0); } #line 2456 "lang11d_tab.cpp" break; case 58: /* msgsend: name '(' ')' blocklist1 */ #line 194 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-3], NULL, NULL, (PyrParseNode*)yyvsp[0]); } #line 2464 "lang11d_tab.cpp" break; case 59: /* msgsend: name '(' arglist1 optkeyarglist ')' blocklist */ #line 198 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-5], (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 2473 "lang11d_tab.cpp" break; case 60: /* msgsend: '(' binop2 ')' '(' ')' blocklist1 */ #line 203 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-4], NULL, NULL, (PyrParseNode*)yyvsp[0]); } #line 2481 "lang11d_tab.cpp" break; case 61: /* msgsend: '(' binop2 ')' '(' arglist1 optkeyarglist ')' blocklist */ #line 207 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 2490 "lang11d_tab.cpp" break; case 62: /* msgsend: name '(' arglistv1 optkeyarglist ')' */ #line 212 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; if (isSuperObjNode((PyrParseNode*)yyvsp[-2])) { SetRaw(&((PyrPushNameNode*)yyvsp[-2])->mSlot, s_this); SetSymbol(&slot, s_superPerformList); } else { SetSymbol(&slot, s_performList); } selectornode = newPyrSlotNode(&slot); args = linkAfterHead( (PyrParseNode*)yyvsp[-2], newPyrPushLitNode((PyrSlotNode*)yyvsp[-4], NULL)); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-1], 0); } #line 2512 "lang11d_tab.cpp" break; case 63: /* msgsend: '(' binop2 ')' '(' arglistv1 optkeyarglist ')' */ #line 230 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_performList); selectornode = newPyrSlotNode(&slot); args = linkAfterHead( (PyrParseNode*)yyvsp[-2], newPyrPushLitNode((PyrSlotNode*)yyvsp[-5], NULL)); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-1], 0); } #line 2529 "lang11d_tab.cpp" break; case 64: /* msgsend: classname '[' arrayelems ']' */ #line 243 "lang11d" { yyval = (intptr_t)newPyrDynListNode((PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); } #line 2535 "lang11d_tab.cpp" break; case 65: /* msgsend: classname blocklist1 */ #line 245 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_new); selectornode = newPyrSlotNode(&slot); args = (PyrParseNode*)newPyrPushNameNode((PyrSlotNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, (PyrParseNode*)yyvsp[0]); } #line 2550 "lang11d_tab.cpp" break; case 66: /* msgsend: classname '(' ')' blocklist */ #line 256 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_new); selectornode = newPyrSlotNode(&slot); args = (PyrParseNode*)newPyrPushNameNode((PyrSlotNode*)yyvsp[-3]); yyval = (intptr_t)newPyrCallNode(selectornode, args, NULL, (PyrParseNode*)yyvsp[0]); } #line 2565 "lang11d_tab.cpp" break; case 67: /* msgsend: classname '(' keyarglist1 optcomma ')' blocklist */ #line 267 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_new); selectornode = newPyrSlotNode(&slot); args = (PyrParseNode*)newPyrPushNameNode((PyrSlotNode*)yyvsp[-5]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[0]); } #line 2580 "lang11d_tab.cpp" break; case 68: /* msgsend: classname '(' arglist1 optkeyarglist ')' blocklist */ #line 278 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_new); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)newPyrPushNameNode((PyrSlotNode*)yyvsp[-5]), (PyrParseNode*)yyvsp[-3]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 2597 "lang11d_tab.cpp" break; case 69: /* msgsend: classname '(' arglistv1 optkeyarglist ')' */ #line 291 "lang11d" { PyrSlotNode *selectornode, *selectornode2; PyrSlot slot, slot2; PyrParseNode* args; if (isSuperObjNode((PyrParseNode*)yyvsp[-4])) { SetRaw(&((PyrPushNameNode*)yyvsp[-4])->mSlot, s_this); SetSymbol(&slot, s_superPerformList); } else { SetSymbol(&slot, s_performList); } SetSymbol(&slot2, s_new); selectornode = newPyrSlotNode(&slot); selectornode2 = newPyrSlotNode(&slot2); args = linkNextNode( (PyrParseNode*)newPyrPushNameNode((PyrSlotNode*)yyvsp[-4]), newPyrPushLitNode(selectornode2, NULL)); args = linkNextNode(args, (PyrParseNode*)yyvsp[-2]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[0], 0); } #line 2622 "lang11d_tab.cpp" break; case 70: /* msgsend: expr '.' '(' ')' blocklist */ #line 312 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; SetSymbol(&slot, s_value); selectornode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(selectornode, (PyrParseNode*)yyvsp[-4], NULL, (PyrParseNode*)yyvsp[0]); } #line 2635 "lang11d_tab.cpp" break; case 71: /* msgsend: expr '.' '(' keyarglist1 optcomma ')' blocklist */ #line 321 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; SetSymbol(&slot, s_value); selectornode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(selectornode, (PyrParseNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[0]); } #line 2648 "lang11d_tab.cpp" break; case 72: /* msgsend: expr '.' name '(' keyarglist1 optcomma ')' blocklist */ #line 330 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-5], (PyrParseNode*)yyvsp[-7], (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[0]); } #line 2657 "lang11d_tab.cpp" break; case 73: /* msgsend: expr '.' '(' arglist1 optkeyarglist ')' blocklist */ #line 335 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_value); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-3]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 2674 "lang11d_tab.cpp" break; case 74: /* msgsend: expr '.' '*' '(' exprseq ',' exprseq ')' */ #line 349 "lang11d" { PyrSlot slot, slot2; SetSymbol(&slot, s_performArgs); SetSymbol(&slot2, s_value); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrParseNode* args = linkNextNode( (PyrParseNode*)yyvsp[-7], newPyrPushLitNode(newPyrSlotNode(&slot2), NULL) ); args = linkNextNode(args, (PyrParseNode*)yyvsp[-3]); args = linkNextNode(args, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, NULL, 0); } #line 2692 "lang11d_tab.cpp" break; case 75: /* msgsend: expr '.' '(' arglistv1 optkeyarglist ')' */ #line 364 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot, slot2; PyrParseNode* args; if (isSuperObjNode((PyrParseNode*)yyvsp[-5])) { SetRaw(&((PyrPushNameNode*)yyvsp[-5])->mSlot, s_this); SetSymbol(&slot, s_superPerformList); } else { SetSymbol(&slot, s_performList); } SetSymbol(&slot2, s_value); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-5], newPyrPushLitNode(newPyrSlotNode(&slot2), NULL)); args = linkNextNode(args, (PyrParseNode*)yyvsp[-2]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-1], 0); } #line 2716 "lang11d_tab.cpp" break; case 76: /* msgsend: expr '.' name '(' ')' blocklist */ #line 386 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-5], NULL, (PyrParseNode*)yyvsp[0]); } #line 2724 "lang11d_tab.cpp" break; case 77: /* msgsend: expr '.' name '(' arglist1 optkeyarglist ')' blocklist */ #line 390 "lang11d" { PyrParseNode* args; args = linkNextNode((PyrParseNode*)yyvsp[-7], (PyrParseNode*)yyvsp[-3]); yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-5], args, (PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 2734 "lang11d_tab.cpp" break; case 78: /* msgsend: expr '.' name '(' arglistv1 optkeyarglist ')' */ #line 396 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; if (isSuperObjNode((PyrParseNode*)yyvsp[-6])) { SetRaw(&((PyrPushNameNode*)yyvsp[-6])->mSlot, s_this); SetSymbol(&slot, s_superPerformList); } else { SetSymbol(&slot, s_performList); } selectornode = newPyrSlotNode(&slot); args = linkNextNode((PyrParseNode*)yyvsp[-6], newPyrPushLitNode((PyrSlotNode*)yyvsp[-4], NULL)); args = linkNextNode(args, (PyrParseNode*)yyvsp[-2]); yyval = (intptr_t)newPyrCallNode(selectornode, args, (PyrParseNode*)yyvsp[-1], 0); } #line 2756 "lang11d_tab.cpp" break; case 79: /* msgsend: expr '.' name blocklist */ #line 414 "lang11d" { yyval = (intptr_t)newPyrCallNode((PyrSlotNode*)yyvsp[-1], (PyrParseNode*)yyvsp[-3], 0, (PyrParseNode*)yyvsp[0]); } #line 2764 "lang11d_tab.cpp" break; case 80: /* $@1: %empty */ #line 419 "lang11d" { pushls(&generatorStack, yyvsp[0]); pushls(&generatorStack, 1); } #line 2770 "lang11d_tab.cpp" break; case 81: /* generator: '{' ':' exprseq $@1 ',' qual '}' */ #line 420 "lang11d" { PyrSlot slot; SetSymbol(&slot, getsym("r")); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(0, 0, (PyrParseNode*)yyvsp[-1], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); yyval = (intptr_t)newPyrCallNode(selectornode, (PyrParseNode*)blocklit, 0, 0); } #line 2784 "lang11d_tab.cpp" break; case 82: /* $@2: %empty */ #line 429 "lang11d" { pushls(&generatorStack, yyvsp[0]); pushls(&generatorStack, 2); } #line 2790 "lang11d_tab.cpp" break; case 83: /* generator: '{' ';' exprseq $@2 ',' qual '}' */ #line 430 "lang11d" { yyval = yyvsp[-1]; } #line 2798 "lang11d_tab.cpp" break; case 84: /* nextqual: %empty */ #line 436 "lang11d" { // innermost part int action = popls(&generatorStack); PyrParseNode* expr = (PyrParseNode*)popls(&generatorStack); switch (action) { case 1 : { PyrSlot slot; SetSymbol(&slot, getsym("yield")); PyrSlotNode* selectornode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(selectornode, expr, 0, 0); } break; case 2 : { yyval = (intptr_t)expr; } break; } } #line 2824 "lang11d_tab.cpp" break; case 85: /* nextqual: ',' qual */ #line 458 "lang11d" { yyval = yyvsp[0]; } #line 2830 "lang11d_tab.cpp" break; case 86: /* qual: name LEFTARROW exprseq nextqual */ #line 462 "lang11d" { // later should check if exprseq is a series and optimize it to for loop PyrParseNode *exprseq = (PyrParseNode*)yyvsp[-1]; if (exprseq->mClassno == pn_CallNode) { PyrCallNode *callnode = (PyrCallNode*)exprseq; if (slotRawSymbol(&callnode->mSelector->mSlot) == s_series) { SetSymbol(&callnode->mSelector->mSlot, getsym("forSeries")); PyrVarDefNode* var = newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], NULL, 0); PyrArgListNode* args = newPyrArgListNode(var, NULL, NULL); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(args, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); callnode->mArglist = linkNextNode(callnode->mArglist, blocklit); yyval = (intptr_t)callnode; } else goto notoptimized1; } else { notoptimized1: PyrSlot slot; SetSymbol(&slot, getsym("do")); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrVarDefNode* var = newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], NULL, 0); PyrArgListNode* args = newPyrArgListNode(var, NULL, NULL); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(args, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); PyrParseNode* args2 = linkNextNode(exprseq, blocklit); yyval = (intptr_t)newPyrCallNode(selectornode, args2, 0, 0); } } #line 2868 "lang11d_tab.cpp" break; case 87: /* qual: name name LEFTARROW exprseq nextqual */ #line 496 "lang11d" { // later should check if exprseq is a series and optimize it to for loop PyrParseNode *exprseq = (PyrParseNode*)yyvsp[-1]; if (exprseq->mClassno == pn_CallNode) { PyrCallNode *callnode = (PyrCallNode*)exprseq; if (slotRawSymbol(&callnode->mSelector->mSlot) == s_series) { SetSymbol(&callnode->mSelector->mSlot, getsym("forSeries")); PyrVarDefNode* var1 = newPyrVarDefNode((PyrSlotNode*)yyvsp[-4], NULL, 0); PyrVarDefNode* var2 = newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], NULL, 0); PyrVarDefNode* vars = (PyrVarDefNode*)linkNextNode(var1, var2); PyrArgListNode* args = newPyrArgListNode(vars, NULL, NULL); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(args, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); callnode->mArglist = linkNextNode(callnode->mArglist, blocklit); yyval = (intptr_t)callnode; } else goto notoptimized2; } else { notoptimized2: PyrSlot slot; SetSymbol(&slot, getsym("do")); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrVarDefNode* var1 = newPyrVarDefNode((PyrSlotNode*)yyvsp[-4], NULL, 0); PyrVarDefNode* var2 = newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], NULL, 0); PyrVarDefNode* vars = (PyrVarDefNode*)linkNextNode(var1, var2); PyrArgListNode* args = newPyrArgListNode(vars, NULL, NULL); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(args, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); PyrParseNode* args2 = linkNextNode(exprseq, blocklit); yyval = (intptr_t)newPyrCallNode(selectornode, args2, 0, 0); } } #line 2910 "lang11d_tab.cpp" break; case 88: /* qual: VAR name '=' exprseq nextqual */ #line 534 "lang11d" { PyrSlot slot; SetSymbol(&slot, s_value); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrVarDefNode* var = newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], NULL, 0); PyrArgListNode* args = newPyrArgListNode(var, NULL, NULL); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(args, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); PyrParseNode* args2 = (PyrParseNode*)linkNextNode(blocklit, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args2, 0, 0); } #line 2928 "lang11d_tab.cpp" break; case 89: /* qual: exprseq nextqual */ #line 548 "lang11d" { PyrSlot slot; SetSymbol(&slot, getsym("if")); PyrSlotNode* selectornode = newPyrSlotNode(&slot); PyrParseNode *block = (PyrParseNode*)newPyrBlockNode(0, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit = (PyrParseNode*)newPyrPushLitNode(NULL, block); PyrParseNode* args2 = (PyrParseNode*)linkNextNode((PyrParseNode*)yyvsp[-1], blocklit); yyval = (intptr_t)newPyrCallNode(selectornode, args2, 0, 0); } #line 2943 "lang11d_tab.cpp" break; case 90: /* qual: ':' ':' exprseq nextqual */ #line 559 "lang11d" { yyval = (intptr_t)newPyrDropNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 2951 "lang11d_tab.cpp" break; case 91: /* qual: ':' WHILE exprseq nextqual */ #line 563 "lang11d" { PyrSlot slot; SetSymbol(&slot, getsym("alwaysYield")); PyrSlotNode* selectornode1 = newPyrSlotNode(&slot); SetSymbol(&slot, getsym("if")); PyrSlotNode* selectornode2 = newPyrSlotNode(&slot); SetNil(&slot); PyrParseNode *pushnil = (PyrParseNode*)newPyrPushLitNode(newPyrSlotNode(&slot), NULL); PyrParseNode *yieldNil = (PyrParseNode*)newPyrCallNode(selectornode1, pushnil, 0, 0); PyrParseNode *block1 = (PyrParseNode*)newPyrBlockNode(0, 0, yieldNil, false); PyrParseNode *blocklit1 = (PyrParseNode*)newPyrPushLitNode(NULL, block1); PyrParseNode *block2 = (PyrParseNode*)newPyrBlockNode(0, 0, (PyrParseNode*)yyvsp[0], false); PyrParseNode *blocklit2 = (PyrParseNode*)newPyrPushLitNode(NULL, block2); PyrParseNode* args2 = (PyrParseNode*)linkNextNode((PyrParseNode*)yyvsp[-1], blocklit2); PyrParseNode* args3 = (PyrParseNode*)linkNextNode(args2, blocklit1); yyval = (intptr_t)newPyrCallNode(selectornode2, args3, 0, 0); } #line 2978 "lang11d_tab.cpp" break; case 98: /* expr1: '(' exprseq ')' */ #line 594 "lang11d" { PyrParseNode* node = (PyrParseNode*)yyvsp[-1]; node->mParens = 1; yyval = yyvsp[-1]; } #line 2988 "lang11d_tab.cpp" break; case 99: /* expr1: '~' name */ #line 600 "lang11d" { PyrParseNode* argnode; PyrSlotNode* selectornode; PyrSlot slot; argnode = (PyrParseNode*)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); SetSymbol(&slot, s_envirGet); selectornode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(selectornode, argnode, 0, 0); } #line 3002 "lang11d_tab.cpp" break; case 100: /* expr1: '[' arrayelems ']' */ #line 610 "lang11d" { yyval = (intptr_t)newPyrDynListNode(0, (PyrParseNode*)yyvsp[-1]); } #line 3008 "lang11d_tab.cpp" break; case 101: /* expr1: '(' valrange2 ')' */ #line 612 "lang11d" { yyval = yyvsp[-1]; } #line 3014 "lang11d_tab.cpp" break; case 102: /* expr1: '(' ':' valrange3 ')' */ #line 614 "lang11d" { yyval = yyvsp[-1]; } #line 3020 "lang11d_tab.cpp" break; case 103: /* expr1: '(' dictslotlist ')' */ #line 616 "lang11d" { yyval = (intptr_t)newPyrDynDictNode((PyrParseNode*)yyvsp[-1]); } #line 3026 "lang11d_tab.cpp" break; case 104: /* expr1: pseudovar */ #line 618 "lang11d" { yyval = (intptr_t)newPyrPushNameNode((PyrSlotNode*)yyvsp[0]); } #line 3032 "lang11d_tab.cpp" break; case 105: /* expr1: expr1 '[' arglist1 ']' */ #line 620 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_at); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3049 "lang11d_tab.cpp" break; case 107: /* valrangex1: expr1 '[' arglist1 DOTDOT ']' */ #line 636 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-2]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-2]); compileErrors++; } SetNil(&nilSlot); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[-2]); if (arglen < 2) { nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, nilnode2); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3080 "lang11d_tab.cpp" break; case 108: /* valrangex1: expr1 '[' DOTDOT exprseq ']' */ #line 663 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-4], nilnode1); args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3102 "lang11d_tab.cpp" break; case 109: /* valrangex1: expr1 '[' arglist1 DOTDOT exprseq ']' */ #line 681 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-3]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-3]); compileErrors++; } SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-5], (PyrParseNode*)yyvsp[-3]); if (arglen < 2) { SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3131 "lang11d_tab.cpp" break; case 110: /* valrangeassign: expr1 '[' arglist1 DOTDOT ']' '=' expr */ #line 708 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-4]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-4]); compileErrors++; } SetNil(&nilSlot); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-4]); if (arglen < 2) { nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3163 "lang11d_tab.cpp" break; case 111: /* valrangeassign: expr1 '[' DOTDOT exprseq ']' '=' expr */ #line 736 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-6], nilnode1); args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[-3]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3186 "lang11d_tab.cpp" break; case 112: /* valrangeassign: expr1 '[' arglist1 DOTDOT exprseq ']' '=' expr */ #line 755 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-5]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-5]); compileErrors++; } SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-7], (PyrParseNode*)yyvsp[-5]); if (arglen < 2) { SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, (PyrParseNode*)yyvsp[-3]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3216 "lang11d_tab.cpp" break; case 113: /* valrangexd: expr '.' '[' arglist1 DOTDOT ']' */ #line 783 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-2]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-3]); compileErrors++; } SetNil(&nilSlot); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-5], (PyrParseNode*)yyvsp[-2]); if (arglen < 2) { nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, nilnode2); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3247 "lang11d_tab.cpp" break; case 114: /* valrangexd: expr '.' '[' DOTDOT exprseq ']' */ #line 810 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-5], nilnode1); args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3269 "lang11d_tab.cpp" break; case 115: /* valrangexd: expr '.' '[' arglist1 DOTDOT exprseq ']' */ #line 828 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-3]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-4]); compileErrors++; } SetSymbol(&selectorSlot, s_copyseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-3]); if (arglen < 2) { SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3298 "lang11d_tab.cpp" break; case 116: /* valrangexd: expr '.' '[' arglist1 DOTDOT ']' '=' expr */ #line 853 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-4]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-5]); compileErrors++; } SetNil(&nilSlot); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-7], (PyrParseNode*)yyvsp[-4]); if (arglen < 2) { nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3330 "lang11d_tab.cpp" break; case 117: /* valrangexd: expr '.' '[' DOTDOT exprseq ']' '=' expr */ #line 881 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-7], nilnode1); args = linkNextNode(args, nilnode2); args = linkNextNode(args, (PyrParseNode*)yyvsp[-3]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3353 "lang11d_tab.cpp" break; case 118: /* valrangexd: expr '.' '[' arglist1 DOTDOT exprseq ']' '=' expr */ #line 900 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode1; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; int arglen = nodeListLength((PyrParseNode*)yyvsp[-5]); if (arglen > 2) { error("ArrayedCollection subrange has too many arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-6]); compileErrors++; } SetSymbol(&selectorSlot, s_putseries); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-8], (PyrParseNode*)yyvsp[-5]); if (arglen < 2) { SetNil(&nilSlot); nilnode1 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); args = linkNextNode(args, nilnode1); } args = linkNextNode(args, (PyrParseNode*)yyvsp[-3]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3383 "lang11d_tab.cpp" break; case 119: /* valrange2: exprseq DOTDOT */ #line 928 "lang11d" { // if this is not used in a 'do' or list comprehension, then should return an error. PyrSlotNode *selectornode; PyrPushLitNode *nilnode, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_series); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-1], nilnode); args = linkNextNode(args, nilnode2); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3405 "lang11d_tab.cpp" break; case 120: /* valrange2: DOTDOT exprseq */ #line 947 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode, *zeronode; PyrSlot selectorSlot, nilSlot, zeroSlot; PyrParseNode* args; SetInt(&zeroSlot, 0); SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); zeronode = newPyrPushLitNode(newPyrSlotNode(&zeroSlot), NULL); SetSymbol(&selectorSlot, s_series); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode(zeronode, nilnode); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3427 "lang11d_tab.cpp" break; case 121: /* valrange2: exprseq DOTDOT exprseq */ #line 966 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_series); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-2], nilnode); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3447 "lang11d_tab.cpp" break; case 122: /* valrange2: exprseq ',' exprseq DOTDOT exprseq */ #line 983 "lang11d" { PyrSlotNode *selectornode; PyrSlot selectorSlot; PyrParseNode* args; SetSymbol(&selectorSlot, s_series); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode( (PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[-2]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3465 "lang11d_tab.cpp" break; case 123: /* valrange2: exprseq ',' exprseq DOTDOT */ #line 997 "lang11d" { // if this is not used in a 'do' or list comprehension, then should return an error. PyrSlotNode *selectornode; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; PyrPushLitNode *nilnode; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, s_series); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode( (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); args = linkNextNode(args, nilnode); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3488 "lang11d_tab.cpp" break; case 124: /* valrange3: DOTDOT exprseq */ #line 1018 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode, *zeronode; PyrSlot selectorSlot, nilSlot, zeroSlot; PyrParseNode* args; SetInt(&zeroSlot, 0); SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); zeronode = newPyrPushLitNode(newPyrSlotNode(&zeroSlot), NULL); SetSymbol(&selectorSlot, getsym("seriesIter")); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode(zeronode, nilnode); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3510 "lang11d_tab.cpp" break; case 125: /* valrange3: exprseq DOTDOT */ #line 1037 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode, *nilnode2; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); nilnode2 = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, getsym("seriesIter")); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-1], nilnode); args = linkNextNode(args, nilnode2); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3531 "lang11d_tab.cpp" break; case 126: /* valrange3: exprseq DOTDOT exprseq */ #line 1055 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, getsym("seriesIter")); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-2], nilnode); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3551 "lang11d_tab.cpp" break; case 127: /* valrange3: exprseq ',' exprseq DOTDOT */ #line 1072 "lang11d" { PyrSlotNode *selectornode; PyrPushLitNode *nilnode; PyrSlot selectorSlot, nilSlot; PyrParseNode* args; SetNil(&nilSlot); nilnode = newPyrPushLitNode(newPyrSlotNode(&nilSlot), NULL); SetSymbol(&selectorSlot, getsym("seriesIter")); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode((PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); args = linkNextNode(args, nilnode); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3571 "lang11d_tab.cpp" break; case 128: /* valrange3: exprseq ',' exprseq DOTDOT exprseq */ #line 1088 "lang11d" { PyrSlotNode *selectornode; PyrSlot selectorSlot; PyrParseNode* args; SetSymbol(&selectorSlot, getsym("seriesIter")); selectornode = newPyrSlotNode(&selectorSlot); args = linkNextNode( (PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[-2]); args = linkNextNode(args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3589 "lang11d_tab.cpp" break; case 132: /* expr: classname */ #line 1106 "lang11d" { yyval = (intptr_t)newPyrPushNameNode((PyrSlotNode*)yyvsp[0]); } #line 3595 "lang11d_tab.cpp" break; case 133: /* expr: expr '.' '[' arglist1 ']' */ #line 1108 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_at); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[-1]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3612 "lang11d_tab.cpp" break; case 134: /* expr: '`' expr */ #line 1121 "lang11d" { PyrParseNode *node, *args; PyrSlotNode *slotnode; PyrSlot slot; SetSymbol(&slot, s_ref); slotnode = newPyrSlotNode(&slot); node = (PyrParseNode*)newPyrPushNameNode(slotnode); args = linkNextNode(node, (PyrParseNode*)yyvsp[0]); SetSymbol(&slot, s_new); slotnode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(slotnode, args, 0, 0); } #line 3630 "lang11d_tab.cpp" break; case 135: /* expr: expr binop2 adverb expr */ #line 1135 "lang11d" { yyval = (intptr_t)newPyrBinopCallNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[0], (PyrParseNode*)yyvsp[-1]); } #line 3639 "lang11d_tab.cpp" break; case 136: /* expr: name '=' expr */ #line 1140 "lang11d" { yyval = (intptr_t)newPyrAssignNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], 0); } #line 3647 "lang11d_tab.cpp" break; case 137: /* expr: '~' name '=' expr */ #line 1144 "lang11d" { PyrParseNode *argnode, *args; PyrSlotNode* selectornode; PyrSlot slot; argnode = (PyrParseNode*)newPyrPushLitNode((PyrSlotNode*)yyvsp[-2], NULL); args = linkNextNode(argnode, (PyrParseNode*)yyvsp[0]); SetSymbol(&slot, s_envirPut); selectornode = newPyrSlotNode(&slot); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3662 "lang11d_tab.cpp" break; case 138: /* expr: expr '.' name '=' expr */ #line 1155 "lang11d" { yyval = (intptr_t)newPyrSetterNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[0]); } #line 3671 "lang11d_tab.cpp" break; case 139: /* expr: name '(' arglist1 optkeyarglist ')' '=' expr */ #line 1160 "lang11d" { if (yyvsp[-3] != 0) { error("Setter method called with keyword arguments.\n"); nodePostErrorLine((PyrParseNode*)yyvsp[-3]); compileErrors++; } yyval = (intptr_t)newPyrSetterNode((PyrSlotNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-4], (PyrParseNode*)yyvsp[0]); } #line 3685 "lang11d_tab.cpp" break; case 140: /* expr: '#' mavars '=' expr */ #line 1170 "lang11d" { yyval = (intptr_t)newPyrMultiAssignNode((PyrMultiAssignVarListNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], 0); } #line 3694 "lang11d_tab.cpp" break; case 141: /* expr: expr1 '[' arglist1 ']' '=' expr */ #line 1175 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_put); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-5], (PyrParseNode*)yyvsp[-3]); args = linkNextNode( args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3712 "lang11d_tab.cpp" break; case 142: /* expr: expr '.' '[' arglist1 ']' '=' expr */ #line 1189 "lang11d" { PyrSlotNode *selectornode; PyrSlot slot; PyrParseNode* args; SetSymbol(&slot, s_put); selectornode = newPyrSlotNode(&slot); args = linkNextNode( (PyrParseNode*)yyvsp[-6], (PyrParseNode*)yyvsp[-3]); args = linkNextNode( args, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)newPyrCallNode(selectornode, args, 0, 0); } #line 3730 "lang11d_tab.cpp" break; case 143: /* adverb: %empty */ #line 1204 "lang11d" { yyval = 0; } #line 3736 "lang11d_tab.cpp" break; case 144: /* adverb: '.' name */ #line 1205 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3742 "lang11d_tab.cpp" break; case 145: /* adverb: '.' integer */ #line 1206 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3748 "lang11d_tab.cpp" break; case 146: /* adverb: '.' '(' exprseq ')' */ #line 1207 "lang11d" { yyval = yyvsp[-1]; } #line 3754 "lang11d_tab.cpp" break; case 148: /* exprn: exprn ';' expr */ #line 1212 "lang11d" { yyval = (intptr_t)newPyrDropNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3762 "lang11d_tab.cpp" break; case 150: /* arrayelems: %empty */ #line 1220 "lang11d" { yyval = 0; } #line 3768 "lang11d_tab.cpp" break; case 151: /* arrayelems: arrayelems1 optcomma */ #line 1222 "lang11d" { yyval = yyvsp[-1]; } #line 3774 "lang11d_tab.cpp" break; case 153: /* arrayelems1: exprseq ':' exprseq */ #line 1227 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3780 "lang11d_tab.cpp" break; case 154: /* arrayelems1: keybinop exprseq */ #line 1229 "lang11d" { PyrParseNode* key = newPyrPushLitNode((PyrSlotNode*)yyvsp[-1], NULL); yyval = (intptr_t)linkNextNode(key, (PyrParseNode*)yyvsp[0]); } #line 3789 "lang11d_tab.cpp" break; case 155: /* arrayelems1: arrayelems1 ',' exprseq */ #line 1234 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3795 "lang11d_tab.cpp" break; case 156: /* arrayelems1: arrayelems1 ',' keybinop exprseq */ #line 1236 "lang11d" { PyrParseNode* elems; PyrParseNode* key = newPyrPushLitNode((PyrSlotNode*)yyvsp[-1], NULL); elems = (PyrParseNode*)linkNextNode(key, (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-3], elems); } #line 3806 "lang11d_tab.cpp" break; case 157: /* arrayelems1: arrayelems1 ',' exprseq ':' exprseq */ #line 1243 "lang11d" { PyrParseNode* elems; elems = (PyrParseNode*)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-4], elems); } #line 3816 "lang11d_tab.cpp" break; case 159: /* arglist1: arglist1 ',' exprseq */ #line 1252 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3822 "lang11d_tab.cpp" break; case 160: /* arglistv1: '*' exprseq */ #line 1256 "lang11d" { yyval = yyvsp[0]; } #line 3828 "lang11d_tab.cpp" break; case 161: /* arglistv1: arglist1 ',' '*' exprseq */ #line 1258 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[0]); } #line 3834 "lang11d_tab.cpp" break; case 163: /* keyarglist1: keyarglist1 ',' keyarg */ #line 1263 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3840 "lang11d_tab.cpp" break; case 164: /* keyarg: keybinop exprseq */ #line 1267 "lang11d" { yyval = (intptr_t)newPyrPushKeyArgNode((PyrSlotNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 3846 "lang11d_tab.cpp" break; case 165: /* optkeyarglist: optcomma */ #line 1270 "lang11d" { yyval = 0; } #line 3852 "lang11d_tab.cpp" break; case 166: /* optkeyarglist: ',' keyarglist1 optcomma */ #line 1271 "lang11d" { yyval = yyvsp[-1]; } #line 3858 "lang11d_tab.cpp" break; case 167: /* mavars: mavarlist */ #line 1275 "lang11d" { yyval = (intptr_t)newPyrMultiAssignVarListNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3864 "lang11d_tab.cpp" break; case 168: /* mavars: mavarlist ELLIPSIS name */ #line 1277 "lang11d" { yyval = (intptr_t)newPyrMultiAssignVarListNode((PyrSlotNode*)yyvsp[-2], (PyrSlotNode*)yyvsp[0]); } #line 3870 "lang11d_tab.cpp" break; case 170: /* mavarlist: mavarlist ',' name */ #line 1282 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 3876 "lang11d_tab.cpp" break; case 171: /* slotliteral: integer */ #line 1286 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3882 "lang11d_tab.cpp" break; case 172: /* slotliteral: floatp */ #line 1287 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3888 "lang11d_tab.cpp" break; case 173: /* slotliteral: ascii */ #line 1288 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3894 "lang11d_tab.cpp" break; case 174: /* slotliteral: string */ #line 1289 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3900 "lang11d_tab.cpp" break; case 175: /* slotliteral: symbol */ #line 1290 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3906 "lang11d_tab.cpp" break; case 176: /* slotliteral: trueobj */ #line 1291 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3912 "lang11d_tab.cpp" break; case 177: /* slotliteral: falseobj */ #line 1292 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3918 "lang11d_tab.cpp" break; case 178: /* slotliteral: nilobj */ #line 1293 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3924 "lang11d_tab.cpp" break; case 179: /* slotliteral: listlit */ #line 1294 "lang11d" { yyval = (intptr_t)newPyrLiteralNode(NULL, (PyrParseNode*)yyvsp[0]); } #line 3930 "lang11d_tab.cpp" break; case 180: /* blockliteral: block */ #line 1297 "lang11d" { yyval = (intptr_t)newPyrPushLitNode(NULL, (PyrParseNode*)yyvsp[0]); } #line 3936 "lang11d_tab.cpp" break; case 181: /* pushname: name */ #line 1300 "lang11d" { yyval = (intptr_t)newPyrPushNameNode((PyrSlotNode*)yyvsp[0]); } #line 3942 "lang11d_tab.cpp" break; case 182: /* pushliteral: integer */ #line 1303 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3948 "lang11d_tab.cpp" break; case 183: /* pushliteral: floatp */ #line 1304 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3954 "lang11d_tab.cpp" break; case 184: /* pushliteral: ascii */ #line 1305 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3960 "lang11d_tab.cpp" break; case 185: /* pushliteral: string */ #line 1306 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3966 "lang11d_tab.cpp" break; case 186: /* pushliteral: symbol */ #line 1307 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3972 "lang11d_tab.cpp" break; case 187: /* pushliteral: trueobj */ #line 1308 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3978 "lang11d_tab.cpp" break; case 188: /* pushliteral: falseobj */ #line 1309 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3984 "lang11d_tab.cpp" break; case 189: /* pushliteral: nilobj */ #line 1310 "lang11d" { yyval = (intptr_t)newPyrPushLitNode((PyrSlotNode*)yyvsp[0], NULL); } #line 3990 "lang11d_tab.cpp" break; case 190: /* pushliteral: listlit */ #line 1311 "lang11d" { yyval = (intptr_t)newPyrPushLitNode(NULL, (PyrParseNode*)yyvsp[0]); } #line 3996 "lang11d_tab.cpp" break; case 191: /* listliteral: integer */ #line 1314 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4002 "lang11d_tab.cpp" break; case 192: /* listliteral: floatp */ #line 1315 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4008 "lang11d_tab.cpp" break; case 193: /* listliteral: ascii */ #line 1316 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4014 "lang11d_tab.cpp" break; case 194: /* listliteral: string */ #line 1317 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4020 "lang11d_tab.cpp" break; case 195: /* listliteral: symbol */ #line 1318 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4026 "lang11d_tab.cpp" break; case 196: /* listliteral: name */ #line 1319 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4032 "lang11d_tab.cpp" break; case 197: /* listliteral: trueobj */ #line 1320 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4038 "lang11d_tab.cpp" break; case 198: /* listliteral: falseobj */ #line 1321 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4044 "lang11d_tab.cpp" break; case 199: /* listliteral: nilobj */ #line 1322 "lang11d" { yyval = (intptr_t)newPyrLiteralNode((PyrSlotNode*)yyvsp[0], NULL); } #line 4050 "lang11d_tab.cpp" break; case 200: /* listliteral: listlit2 */ #line 1323 "lang11d" { yyval = (intptr_t)newPyrLiteralNode(NULL, (PyrParseNode*)yyvsp[0]); } #line 4056 "lang11d_tab.cpp" break; case 201: /* listliteral: dictlit2 */ #line 1324 "lang11d" { yyval = (intptr_t)newPyrLiteralNode(NULL, (PyrParseNode*)yyvsp[0]); } #line 4062 "lang11d_tab.cpp" break; case 202: /* block: '{' argdecls funcvardecls funcbody '}' */ #line 1328 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-3], (PyrVarListNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-1], false); } #line 4069 "lang11d_tab.cpp" break; case 203: /* block: BEGINCLOSEDFUNC argdecls funcvardecls funcbody '}' */ #line 1331 "lang11d" { yyval = (intptr_t)newPyrBlockNode((PyrArgListNode*)yyvsp[-3], (PyrVarListNode*)yyvsp[-2], (PyrParseNode*)yyvsp[-1], true); } #line 4076 "lang11d_tab.cpp" break; case 204: /* funcvardecls: %empty */ #line 1335 "lang11d" { yyval = 0; } #line 4082 "lang11d_tab.cpp" break; case 205: /* funcvardecls: funcvardecls funcvardecl */ #line 1337 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 4088 "lang11d_tab.cpp" break; case 207: /* funcvardecls1: funcvardecls1 funcvardecl */ #line 1342 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-1], (PyrParseNode*)yyvsp[0]); } #line 4094 "lang11d_tab.cpp" break; case 208: /* funcvardecl: VAR vardeflist ';' */ #line 1346 "lang11d" { yyval = (intptr_t)newPyrVarListNode((PyrVarDefNode*)yyvsp[-1], varLocal); } #line 4100 "lang11d_tab.cpp" break; case 209: /* argdecls: %empty */ #line 1349 "lang11d" { yyval = 0; } #line 4106 "lang11d_tab.cpp" break; case 210: /* argdecls: ARG vardeflist ';' */ #line 1351 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-1], NULL, NULL); } #line 4114 "lang11d_tab.cpp" break; case 211: /* argdecls: ARG vardeflist0 ELLIPSIS name ';' */ #line 1355 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1], NULL); } #line 4122 "lang11d_tab.cpp" break; case 212: /* argdecls: '|' slotdeflist '|' */ #line 1359 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-1], NULL, NULL); } #line 4130 "lang11d_tab.cpp" break; case 213: /* argdecls: '|' slotdeflist0 ELLIPSIS name '|' */ #line 1363 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1], NULL); } #line 4138 "lang11d_tab.cpp" break; case 214: /* argdecls: '|' slotdeflist0 ELLIPSIS name ',' name '|' */ #line 1367 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-5], (PyrSlotNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1]); } #line 4146 "lang11d_tab.cpp" break; case 215: /* argdecls1: ARG vardeflist ';' */ #line 1373 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-1], NULL, NULL); } #line 4154 "lang11d_tab.cpp" break; case 216: /* argdecls1: ARG vardeflist0 ELLIPSIS name ';' */ #line 1377 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1], NULL); } #line 4162 "lang11d_tab.cpp" break; case 217: /* argdecls1: '|' slotdeflist '|' */ #line 1381 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-1], NULL, NULL); } #line 4170 "lang11d_tab.cpp" break; case 218: /* argdecls1: '|' slotdeflist0 ELLIPSIS name '|' */ #line 1385 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1], NULL); } #line 4178 "lang11d_tab.cpp" break; case 219: /* argdecls1: '|' slotdeflist0 ELLIPSIS name ',' name '|' */ #line 1389 "lang11d" { yyval = (intptr_t)newPyrArgListNode((PyrVarDefNode*)yyvsp[-5], (PyrSlotNode*)yyvsp[-3], (PyrSlotNode*)yyvsp[-1]); } #line 4186 "lang11d_tab.cpp" break; case 221: /* constdeflist: constdeflist optcomma constdef */ #line 1397 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4192 "lang11d_tab.cpp" break; case 222: /* constdef: rspec name '=' slotliteral */ #line 1401 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], yyvsp[-3]); } #line 4198 "lang11d_tab.cpp" break; case 223: /* slotdeflist0: %empty */ #line 1404 "lang11d" { yyval = 0; } #line 4204 "lang11d_tab.cpp" break; case 226: /* slotdeflist: slotdeflist optcomma slotdef */ #line 1410 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4210 "lang11d_tab.cpp" break; case 227: /* slotdef: name */ #line 1414 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[0], NULL, 0); } #line 4216 "lang11d_tab.cpp" break; case 228: /* slotdef: name optequal slotliteral */ #line 1416 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], 0); } #line 4222 "lang11d_tab.cpp" break; case 229: /* slotdef: name optequal '(' exprseq ')' */ #line 1418 "lang11d" { PyrParseNode* node = (PyrParseNode*)yyvsp[-1]; node->mParens = 1; yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-4], node, 0); } #line 4232 "lang11d_tab.cpp" break; case 230: /* vardeflist0: %empty */ #line 1425 "lang11d" { yyval = 0; } #line 4238 "lang11d_tab.cpp" break; case 233: /* vardeflist: vardeflist ',' vardef */ #line 1431 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4244 "lang11d_tab.cpp" break; case 234: /* vardef: name */ #line 1435 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[0], NULL, 0); } #line 4250 "lang11d_tab.cpp" break; case 235: /* vardef: name '=' expr */ #line 1437 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], 0); } #line 4256 "lang11d_tab.cpp" break; case 236: /* vardef: name '(' exprseq ')' */ #line 1439 "lang11d" { PyrParseNode* node = (PyrParseNode*)yyvsp[-1]; node->mParens = 1; yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-3], node, 0); } #line 4266 "lang11d_tab.cpp" break; case 237: /* dictslotdef: exprseq ':' exprseq */ #line 1447 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4272 "lang11d_tab.cpp" break; case 238: /* dictslotdef: keybinop exprseq */ #line 1449 "lang11d" { PyrParseNode* key = newPyrPushLitNode((PyrSlotNode*)yyvsp[-1], NULL); yyval = (intptr_t)linkNextNode(key, (PyrParseNode*)yyvsp[0]); } #line 4281 "lang11d_tab.cpp" break; case 240: /* dictslotlist1: dictslotlist1 ',' dictslotdef */ #line 1457 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4287 "lang11d_tab.cpp" break; case 241: /* dictslotlist: %empty */ #line 1460 "lang11d" { yyval = 0; } #line 4293 "lang11d_tab.cpp" break; case 244: /* rwslotdeflist: rwslotdeflist ',' rwslotdef */ #line 1466 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4299 "lang11d_tab.cpp" break; case 245: /* rwslotdef: rwspec name */ #line 1470 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[0], NULL, yyvsp[-1]); } #line 4305 "lang11d_tab.cpp" break; case 246: /* rwslotdef: rwspec name '=' slotliteral */ #line 1472 "lang11d" { yyval = (intptr_t)newPyrVarDefNode((PyrSlotNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0], yyvsp[-3]); } #line 4311 "lang11d_tab.cpp" break; case 247: /* dictlit2: '(' litdictslotlist ')' */ #line 1476 "lang11d" { yyval = (intptr_t)newPyrLitDictNode((PyrParseNode*)yyvsp[-1]); } #line 4317 "lang11d_tab.cpp" break; case 248: /* litdictslotdef: listliteral ':' listliteral */ #line 1480 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4323 "lang11d_tab.cpp" break; case 249: /* litdictslotdef: keybinop listliteral */ #line 1482 "lang11d" { PyrParseNode* key = newPyrPushLitNode((PyrSlotNode*)yyvsp[-1], NULL); yyval = (intptr_t)linkNextNode(key, (PyrParseNode*)yyvsp[0]); } #line 4332 "lang11d_tab.cpp" break; case 251: /* litdictslotlist1: litdictslotlist1 ',' litdictslotdef */ #line 1490 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4338 "lang11d_tab.cpp" break; case 252: /* litdictslotlist: %empty */ #line 1493 "lang11d" { yyval = 0; } #line 4344 "lang11d_tab.cpp" break; case 254: /* listlit: '#' '[' literallistc ']' */ #line 1500 "lang11d" { yyval = (intptr_t)newPyrLitListNode(0, (PyrParseNode*)yyvsp[-1]); } #line 4350 "lang11d_tab.cpp" break; case 255: /* listlit: '#' classname '[' literallistc ']' */ #line 1502 "lang11d" { yyval = (intptr_t)newPyrLitListNode((PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); } #line 4356 "lang11d_tab.cpp" break; case 256: /* listlit2: '[' literallistc ']' */ #line 1506 "lang11d" { yyval = (intptr_t)newPyrLitListNode(0, (PyrParseNode*)yyvsp[-1]); } #line 4362 "lang11d_tab.cpp" break; case 257: /* listlit2: classname '[' literallistc ']' */ #line 1508 "lang11d" { yyval = (intptr_t)newPyrLitListNode((PyrParseNode*)yyvsp[-3], (PyrParseNode*)yyvsp[-1]); } #line 4368 "lang11d_tab.cpp" break; case 258: /* literallistc: %empty */ #line 1511 "lang11d" { yyval = 0; } #line 4374 "lang11d_tab.cpp" break; case 261: /* literallist1: literallist1 ',' listliteral */ #line 1517 "lang11d" { yyval = (intptr_t)linkNextNode((PyrParseNode*)yyvsp[-2], (PyrParseNode*)yyvsp[0]); } #line 4380 "lang11d_tab.cpp" break; case 262: /* rwspec: %empty */ #line 1520 "lang11d" { yyval = rwPrivate; } #line 4386 "lang11d_tab.cpp" break; case 263: /* rwspec: '<' */ #line 1522 "lang11d" { yyval = rwReadOnly; } #line 4392 "lang11d_tab.cpp" break; case 264: /* rwspec: READWRITEVAR */ #line 1524 "lang11d" { yyval = rwReadWrite; } #line 4398 "lang11d_tab.cpp" break; case 265: /* rwspec: '>' */ #line 1526 "lang11d" { yyval = rwWriteOnly; } #line 4404 "lang11d_tab.cpp" break; case 266: /* rspec: %empty */ #line 1529 "lang11d" { yyval = rwPrivate; } #line 4410 "lang11d_tab.cpp" break; case 267: /* rspec: '<' */ #line 1531 "lang11d" { yyval = rwReadOnly; } #line 4416 "lang11d_tab.cpp" break; case 268: /* integer: INTEGER */ #line 1534 "lang11d" { yyval = zzval; } #line 4422 "lang11d_tab.cpp" break; case 269: /* integer: '-' INTEGER */ #line 1536 "lang11d" { PyrSlotNode *node; node = (PyrSlotNode*)zzval; SetRaw(&node->mSlot, -slotRawInt(&node->mSlot)); yyval = zzval; } #line 4433 "lang11d_tab.cpp" break; case 270: /* floatr: SC_FLOAT */ #line 1544 "lang11d" { yyval = zzval; } #line 4439 "lang11d_tab.cpp" break; case 271: /* floatr: '-' SC_FLOAT */ #line 1546 "lang11d" { PyrSlotNode *node; node = (PyrSlotNode*)zzval; SetRaw(&node->mSlot, -slotRawFloat(&node->mSlot)); yyval = zzval; } #line 4450 "lang11d_tab.cpp" break; case 272: /* accidental: ACCIDENTAL */ #line 1554 "lang11d" { yyval = zzval; } #line 4456 "lang11d_tab.cpp" break; case 273: /* accidental: '-' ACCIDENTAL */ #line 1556 "lang11d" { PyrSlotNode *node; double intval, fracval; node = (PyrSlotNode*)zzval; intval = floor(slotRawFloat(&node->mSlot) + 0.5); fracval = slotRawFloat(&node->mSlot) - intval; SetRaw(&node->mSlot, -intval + fracval); yyval = zzval; } #line 4470 "lang11d_tab.cpp" break; case 274: /* pie: PIE */ #line 1566 "lang11d" { yyval = zzval; } #line 4476 "lang11d_tab.cpp" break; case 277: /* floatp: floatr pie */ #line 1572 "lang11d" { PyrSlotNode *node; node = (PyrSlotNode*)yyvsp[-1]; SetRaw(&node->mSlot, slotRawFloat(&node->mSlot) * pi); } #line 4486 "lang11d_tab.cpp" break; case 278: /* floatp: integer pie */ #line 1578 "lang11d" { PyrSlotNode *node; double ival; node = (PyrSlotNode*)yyvsp[-1]; ival = slotRawInt(&node->mSlot); SetFloat(&node->mSlot, ival * pi); } #line 4498 "lang11d_tab.cpp" break; case 279: /* floatp: pie */ #line 1586 "lang11d" { PyrSlotNode *node; node = (PyrSlotNode*)zzval; SetFloat(&node->mSlot, pi); yyval = zzval; } #line 4509 "lang11d_tab.cpp" break; case 280: /* floatp: '-' pie */ #line 1593 "lang11d" { PyrSlotNode *node; node = (PyrSlotNode*)zzval; SetFloat(&node->mSlot, -pi); yyval = zzval; } #line 4520 "lang11d_tab.cpp" break; case 281: /* name: NAME */ #line 1601 "lang11d" { yyval = zzval; } #line 4526 "lang11d_tab.cpp" break; case 282: /* name: WHILE */ #line 1602 "lang11d" { yyval = zzval; } #line 4532 "lang11d_tab.cpp" break; case 283: /* classname: CLASSNAME */ #line 1605 "lang11d" { yyval = zzval; } #line 4538 "lang11d_tab.cpp" break; case 284: /* primname: PRIMITIVENAME */ #line 1608 "lang11d" { yyval = zzval; } #line 4544 "lang11d_tab.cpp" break; case 285: /* trueobj: TRUEOBJ */ #line 1611 "lang11d" { yyval = zzval; } #line 4550 "lang11d_tab.cpp" break; case 286: /* falseobj: FALSEOBJ */ #line 1614 "lang11d" { yyval = zzval; } #line 4556 "lang11d_tab.cpp" break; case 287: /* nilobj: NILOBJ */ #line 1617 "lang11d" { yyval = zzval; } #line 4562 "lang11d_tab.cpp" break; case 288: /* ascii: ASCII */ #line 1620 "lang11d" { yyval = zzval; } #line 4568 "lang11d_tab.cpp" break; case 289: /* symbol: SYMBOL */ #line 1623 "lang11d" { yyval = zzval; } #line 4574 "lang11d_tab.cpp" break; case 290: /* string: STRING */ #line 1626 "lang11d" { yyval = zzval; } #line 4580 "lang11d_tab.cpp" break; case 291: /* pseudovar: PSEUDOVAR */ #line 1629 "lang11d" { yyval = zzval; } #line 4586 "lang11d_tab.cpp" break; case 292: /* binop: BINOP */ #line 1632 "lang11d" { yyval = zzval; } #line 4592 "lang11d_tab.cpp" break; case 293: /* binop: READWRITEVAR */ #line 1633 "lang11d" { yyval = zzval; } #line 4598 "lang11d_tab.cpp" break; case 294: /* binop: '<' */ #line 1634 "lang11d" { yyval = zzval; } #line 4604 "lang11d_tab.cpp" break; case 295: /* binop: '>' */ #line 1635 "lang11d" { yyval = zzval; } #line 4610 "lang11d_tab.cpp" break; case 296: /* binop: '-' */ #line 1636 "lang11d" { yyval = zzval; } #line 4616 "lang11d_tab.cpp" break; case 297: /* binop: '*' */ #line 1637 "lang11d" { yyval = zzval; } #line 4622 "lang11d_tab.cpp" break; case 298: /* binop: '+' */ #line 1638 "lang11d" { yyval = zzval; } #line 4628 "lang11d_tab.cpp" break; case 299: /* binop: '|' */ #line 1639 "lang11d" { yyval = zzval; } #line 4634 "lang11d_tab.cpp" break; case 300: /* keybinop: KEYBINOP */ #line 1642 "lang11d" { yyval = zzval; } #line 4640 "lang11d_tab.cpp" break; case 303: /* curryarg: CURRYARG */ #line 1649 "lang11d" { yyval = zzval; } #line 4646 "lang11d_tab.cpp" break; #line 4650 "lang11d_tab.cpp" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; { yypcontext_t yyctx = {yyssp, yytoken}; char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx); if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == -1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = YY_CAST (char *, YYSTACK_ALLOC (YY_CAST (YYSIZE_T, yymsg_alloc))); if (yymsg) { yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx); yymsgp = yymsg; } else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = YYENOMEM; } } yyerror (yymsgp); if (yysyntax_error_status == YYENOMEM) YYNOMEM; } } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (0) YYERROR; ++yynerrs; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ /* Pop stack until we find a state that shifts the error token. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYSYMBOL_YYerror; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", YY_ACCESSING_SYMBOL (yystate), yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturnlab; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturnlab; /*-----------------------------------------------------------. | yyexhaustedlab -- YYNOMEM (memory exhaustion) comes here. | `-----------------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; goto yyreturnlab; /*----------------------------------------------------------. | yyreturnlab -- parsing is finished, clean up and return. | `----------------------------------------------------------*/ yyreturnlab: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", YY_ACCESSING_SYMBOL (+*yyssp), yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); return yyresult; }
188,808
C++
.cpp
4,292
37.982992
159
0.51058
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
29,860
SC_CoreMIDI.cpp
supercollider_supercollider/lang/LangPrimSource/SC_CoreMIDI.cpp
/* 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 */ /* changes by charles picasso 14/april/2008 (sysex parsing + added running status) changes by jan trutzschler v. f. 9/9/2002 the midiReadProc calls doAction in the class MIDIIn. with the arguments: inUid, status, chan, val1, val2 added prDisposeMIDIClient added prRestartMIDI 19/9 call different actions,disconnect midiInPort, midiout: sendmidi 04/feb/03 prListMIDIEndpoints modification by Ron Kuivila added jt. */ #if SC_IPHONE # include <mach/mach_time.h> #else # include <CoreAudio/HostTime.h> # include <Carbon/Carbon.h> #endif #include <CoreMIDI/CoreMIDI.h> #include <vector> #include "SCBase.h" #include "VMGlobals.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSched.h" #include "GC.h" PyrSymbol* s_domidiaction; PyrSymbol* s_midiNoteOnAction; PyrSymbol* s_midiNoteOffAction; PyrSymbol* s_midiTouchAction; PyrSymbol* s_midiControlAction; PyrSymbol* s_midiPolyTouchAction; PyrSymbol* s_midiProgramAction; PyrSymbol* s_midiBendAction; PyrSymbol* s_midiSysexAction; PyrSymbol* s_midiInvalidSysexAction; PyrSymbol* s_midiSysrtAction; PyrSymbol* s_midiSMPTEAction; // jt PyrSymbol* s_midiin; PyrSymbol* s_numMIDIDev; PyrSymbol* s_midiclient; const int kMaxMidiPorts = 128; MIDIClientRef gMIDIClient = 0; MIDIPortRef gMIDIInPort[kMaxMidiPorts], gMIDIOutPort[kMaxMidiPorts]; int gNumMIDIInPorts = 0, gNumMIDIOutPorts = 0; bool gMIDIInitialized = false; // cp static bool gSysexFlag = false; static Byte gRunningStatus = 0; std::vector<Byte> gSysexData; void midiNotifyProc(const MIDINotification* msg, void* refCon) {} extern bool compiledOK; #if 0 static void dumpSysexData() { if(gSysexData.size() <= 0) return; std::vector<Byte>::const_iterator iter = gSysexData.begin(), end = gSysexData.end(); int i=0; while(iter != end) { if((i % 16) == 0 && (i > 0)) printf("\n"); ++i; printf("%02X ", *iter++); } printf("\n"); printf("sysex data dump size: %i bytes.\n", gSysexData.size()); } #endif static void sysexBegin() { gRunningStatus = 0; // clear running status gSysexData.clear(); gSysexFlag = true; } static void scCallSysexAction(PyrSymbol* action, int recoverFromUID) { VMGlobals* g = gMainVMGlobals; if (recoverFromUID) { // rebuild the VM so sc won't crash with two following calls ++g->sp; SetObject(g->sp, s_midiin->u.classobj); // Set the class MIDIIn ++g->sp; SetInt(g->sp, recoverFromUID); // src ++g->sp; } PyrInt8Array* sysexArray = newPyrInt8Array(g->gc, gSysexData.size(), 0, true); sysexArray->size = gSysexData.size(); std::copy(gSysexData.begin(), gSysexData.end(), sysexArray->b); SetObject(g->sp, (PyrObject*)sysexArray); // chan argument unneeded as there runInterpreter(g, action, 3); // special sysex action in the lang } static void sysexEnd(int lastUID) { gSysexFlag = false; scCallSysexAction(s_midiSysexAction, lastUID); } static void sysexEndInvalid() { gSysexFlag = false; scCallSysexAction(s_midiInvalidSysexAction, 0); } static int midiProcessSystemPacket(MIDIPacket* pkt, int chan) { int index, data; VMGlobals* g = gMainVMGlobals; switch (chan) { case 7: // added cp: Sysex EOX must be taken into account if first on data packet case 0: { int last_uid = 0; int m = pkt->length; Byte* p_pkt = pkt->data; Byte pktval; while (m--) { pktval = *p_pkt++; if (pktval & 0x80) { // status byte if (pktval == 0xF7) { // end packet gSysexData.push_back(pktval); // add EOX if (gSysexFlag) sysexEnd(last_uid); // if last_uid != 0 rebuild the VM. else sysexEndInvalid(); // invalid 1 byte with only EOX can happen break; } else if (pktval == 0xF0) { // new packet if (gSysexFlag) { // invalid new one/should not happen -- but handle in case // store the last uid value previous to invalid data to rebuild VM after sysexEndInvalid call // since it may call sysexEnd() just after it ! if (slotIntVal(g->sp - 1, &last_uid)) { post("error: failed retrieving uid value !"); last_uid = -1; } sysexEndInvalid(); } sysexBegin(); // new sysex in gSysexData.push_back(pktval); // add SOX } else { // abnormal data in middle of sysex packet gSysexData.push_back(pktval); // add it as an abort message sysexEndInvalid(); // flush invalid m = 0; // discard all packet break; } } else if (gSysexFlag) gSysexData.push_back(pktval); // add Byte else // garbage - handle in case - discard it break; } return (pkt->length - m); } break; case 1: index = pkt->data[1] >> 4; data = pkt->data[1] & 0xf; switch (index) { case 1: case 3: case 5: case 7: { data = data << 4; } } SetInt(g->sp, index); // chan unneeded ++g->sp; SetInt(g->sp, data); // special smpte action in the lang runInterpreter(g, s_midiSMPTEAction, 4); return 2; case 2: // songptr ++g->sp; SetInt(g->sp, (pkt->data[2] << 7) | pkt->data[1]); // val1 runInterpreter(g, s_midiSysrtAction, 4); return 3; case 3: // song select ++g->sp; SetInt(g->sp, pkt->data[1]); // val1 runInterpreter(g, s_midiSysrtAction, 4); return 2; case 6: // tunerequest case 8: // clock case 9: // tick case 10: // start case 11: // continue case 12: // stop case 14: // activeSense case 15: // reset gRunningStatus = 0; // clear running status runInterpreter(g, s_midiSysrtAction, 3); return 1; default: g->sp -= 3; // nevermind break; } return (1); } static void midiProcessPacket(MIDIPacket* pkt, size_t uid) { // jt if (pkt) { gLangMutex.lock(); // dont know if this is really needed/seems to be more stable.. // it is needed -jamesmcc if (compiledOK) { VMGlobals* g = gMainVMGlobals; int i = 0; // cp : changed uint8 to int if packet->length >= 256 bug:(infinite loop) while (i < pkt->length) { uint8 status = pkt->data[i] & 0xF0; uint8 chan = pkt->data[i] & 0x0F; g->canCallOS = false; // cannot call the OS ++g->sp; SetObject(g->sp, s_midiin->u.classobj); // Set the class MIDIIn // set arguments: ++g->sp; SetInt(g->sp, uid); // src // ++g->sp; SetInt(g->sp, status); //status ++g->sp; SetInt(g->sp, chan); // chan if (status & 0x80) // set the running status for voice messages gRunningStatus = ((status >> 4) == 0xF) ? 0 : pkt->data[i]; // keep also additional info L: switch (status) { case 0x80: // noteOff ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 ++g->sp; SetInt(g->sp, pkt->data[i + 2]); // val2 runInterpreter(g, s_midiNoteOffAction, 5); i += 3; break; case 0x90: // noteOn ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 ++g->sp; SetInt(g->sp, pkt->data[i + 2]); // val2 // runInterpreter(g, pkt->data[i+2] ? s_midiNoteOnAction : s_midiNoteOffAction, 5); runInterpreter(g, s_midiNoteOnAction, 5); i += 3; break; case 0xA0: // polytouch ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 ++g->sp; SetInt(g->sp, pkt->data[i + 2]); // val2 runInterpreter(g, s_midiPolyTouchAction, 5); i += 3; break; case 0xB0: // control ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 ++g->sp; SetInt(g->sp, pkt->data[i + 2]); // val2 runInterpreter(g, s_midiControlAction, 5); i += 3; break; case 0xC0: // program ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 runInterpreter(g, s_midiProgramAction, 4); i += 2; break; case 0xD0: // touch ++g->sp; SetInt(g->sp, pkt->data[i + 1]); // val1 runInterpreter(g, s_midiTouchAction, 4); i += 2; break; case 0xE0: // bend ++g->sp; SetInt(g->sp, (pkt->data[i + 2] << 7) | pkt->data[i + 1]); // val1 runInterpreter(g, s_midiBendAction, 4); i += 3; break; case 0xF0: i += midiProcessSystemPacket(pkt, chan); break; default: // data byte => continuing sysex message if (gRunningStatus && !gSysexFlag) { // modified cp: handling running status. may be we should here status = gRunningStatus & 0xF0; // accept running status only inside a packet beginning chan = gRunningStatus & 0x0F; // with a valid status byte ? SetInt(g->sp, chan); --i; goto L; // parse again with running status set } chan = 0; i += midiProcessSystemPacket(pkt, chan); break; } } g->canCallOS = false; } gLangMutex.unlock(); } } static void midiReadProc(const MIDIPacketList* pktlist, void* readProcRefCon, void* srcConnRefCon) { MIDIPacket* pkt = (MIDIPacket*)pktlist->packet; size_t uid = (size_t)srcConnRefCon; for (uint32 i = 0; i < pktlist->numPackets; ++i) { midiProcessPacket(pkt, uid); pkt = MIDIPacketNext(pkt); } } int midiCleanUp(); int initMIDI(int numIn, int numOut) { OSStatus err; CFAllocatorRef alloc = CFAllocatorGetDefault(); int enc = kCFStringEncodingMacRoman; midiCleanUp(); if (numIn > kMaxMidiPorts) { printf("MIDI: note that maximum midi in ports is limited to %d.\n", kMaxMidiPorts); } if (numOut > kMaxMidiPorts) { printf("MIDI: note that maximum midi out ports is limited to %d.\n", kMaxMidiPorts); } numIn = sc_clip(numIn, 1, kMaxMidiPorts); numOut = sc_clip(numOut, 1, kMaxMidiPorts); if (!gMIDIClient) { CFStringRef clientName = CFStringCreateWithCString(alloc, "SuperCollider", enc); err = MIDIClientCreate(clientName, midiNotifyProc, nil, &gMIDIClient); if (err) { post("Could not create MIDI client. error: "); return errFailed; } CFRelease(clientName); } for (int i = 0; i < numIn; ++i) { char str[32]; sprintf(str, "in%d\n", i); CFStringRef inputPortName = CFStringCreateWithCString(alloc, str, enc); err = MIDIInputPortCreate(gMIDIClient, inputPortName, midiReadProc, &i, gMIDIInPort + i); if (err) { gNumMIDIInPorts = i; post("Could not create MIDI port %s. error %d\n", str, err); return errFailed; } CFRelease(inputPortName); } /*int n = MIDIGetNumberOfSources(); printf("%d sources\n", n); for (i = 0; i < n; ++i) { MIDIEndpointRef src = MIDIGetSource(i); MIDIPortConnectSource(inPort, src, NULL); }*/ gNumMIDIInPorts = numIn; for (int i = 0; i < numOut; ++i) { char str[32]; sprintf(str, "out%d\n", i); CFStringRef outputPortName = CFStringCreateWithCString(alloc, str, enc); err = MIDIOutputPortCreate(gMIDIClient, outputPortName, gMIDIOutPort + i); if (err) { gNumMIDIOutPorts = i; post("Could not create MIDI out port. error %d\n", err); return errFailed; } CFRelease(outputPortName); } gNumMIDIOutPorts = numOut; return errNone; } int midiCleanUp() { /* * do not catch errors when disposing ports * MIDIClientDispose should normally dispose the ports attached to it * but clean up the pointers in case */ int i = 0; for (i = 0; i < gNumMIDIOutPorts; ++i) { MIDIPortDispose(gMIDIOutPort[i]); gMIDIOutPort[i] = 0; } gNumMIDIOutPorts = 0; for (i = 0; i < gNumMIDIInPorts; ++i) { MIDIPortDispose(gMIDIInPort[i]); gMIDIInPort[i] = 0; } gNumMIDIInPorts = 0; // Disposing and immediately re-initializing an identical midi client can cause crashes. Don't dispose - instead, // reuse the one we've created already. // if (gMIDIClient) { // if( MIDIClientDispose(gMIDIClient) ) { // post( "Error: failed to dispose MIDIClient\n" ); // return errFailed; // } // gMIDIClient = 0; // } return errNone; } void midiListEndpoints() {} int prListMIDIEndpoints(struct VMGlobals* g, int numArgsPushed); int prListMIDIEndpoints(struct VMGlobals* g, int numArgsPushed) { OSStatus error; PyrSlot* a = g->sp; int numSrc = MIDIGetNumberOfSources(); int numDst = MIDIGetNumberOfDestinations(); PyrObject* idarray = newPyrArray(g->gc, 6 * sizeof(PyrObject), 0, true); SetObject(a, idarray); // this is okay here as we don't use the receiver PyrObject* idarraySo = newPyrArray(g->gc, numSrc * sizeof(SInt32), 0, true); SetObject(idarray->slots + idarray->size++, idarraySo); g->gc->GCWriteNew(idarray, idarraySo); // we know idarraySo is white so we can use GCWriteNew PyrObject* devarraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarraySo); g->gc->GCWriteNew(idarray, devarraySo); // we know devarraySo is white so we can use GCWriteNew PyrObject* namearraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearraySo); g->gc->GCWriteNew(idarray, namearraySo); // we know namearraySo is white so we can use GCWriteNew PyrObject* idarrayDe = newPyrArray(g->gc, numDst * sizeof(SInt32), 0, true); SetObject(idarray->slots + idarray->size++, idarrayDe); g->gc->GCWriteNew(idarray, idarrayDe); // we know idarrayDe is white so we can use GCWriteNew PyrObject* namearrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearrayDe); g->gc->GCWriteNew(idarray, namearrayDe); // we know namearrayDe is white so we can use GCWriteNew PyrObject* devarrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarrayDe); g->gc->GCWriteNew(idarray, devarrayDe); // we know devarrayDe is white so we can use GCWriteNew for (int i = 0; i < numSrc; ++i) { MIDIEndpointRef src = MIDIGetSource(i); SInt32 id; MIDIObjectGetIntegerProperty(src, kMIDIPropertyUniqueID, &id); MIDIEntityRef ent; error = MIDIEndpointGetEntity(src, &ent); CFStringRef devname, endname; char cendname[1024], cdevname[1024]; // Virtual sources don't have entities if (error) { MIDIObjectGetStringProperty(src, kMIDIPropertyName, &devname); MIDIObjectGetStringProperty(src, kMIDIPropertyName, &endname); if (devname) CFStringGetCString(devname, cdevname, 1024, kCFStringEncodingUTF8); if (endname) CFStringGetCString(endname, cendname, 1024, kCFStringEncodingUTF8); } else { MIDIDeviceRef dev; MIDIEntityGetDevice(ent, &dev); MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &devname); MIDIObjectGetStringProperty(src, kMIDIPropertyName, &endname); if (devname) CFStringGetCString(devname, cdevname, 1024, kCFStringEncodingUTF8); if (endname) CFStringGetCString(endname, cendname, 1024, kCFStringEncodingUTF8); } PyrString* string = newPyrString(g->gc, cendname, 0, true); SetObject(namearraySo->slots + i, string); namearraySo->size++; g->gc->GCWriteNew(namearraySo, (PyrObject*)string); // we know string is white so we can use GCWriteNew PyrString* devstring = newPyrString(g->gc, cdevname, 0, true); SetObject(devarraySo->slots + i, devstring); devarraySo->size++; g->gc->GCWriteNew(devarraySo, (PyrObject*)devstring); // we know devString is white so we can use GCWriteNew SetInt(idarraySo->slots + i, id); idarraySo->size++; if (devname) CFRelease(devname); if (endname) CFRelease(endname); } // post("numDst %d\n", numDst); for (int i = 0; i < numDst; ++i) { MIDIEndpointRef dst = MIDIGetDestination(i); SInt32 id; MIDIObjectGetIntegerProperty(dst, kMIDIPropertyUniqueID, &id); MIDIEntityRef ent; error = MIDIEndpointGetEntity(dst, &ent); CFStringRef devname, endname; char cendname[1024], cdevname[1024]; // Virtual destinations don't have entities either if (error) { MIDIObjectGetStringProperty(dst, kMIDIPropertyName, &devname); MIDIObjectGetStringProperty(dst, kMIDIPropertyName, &endname); if (devname) CFStringGetCString(devname, cdevname, 1024, kCFStringEncodingUTF8); if (endname) CFStringGetCString(endname, cendname, 1024, kCFStringEncodingUTF8); } else { MIDIDeviceRef dev; MIDIEntityGetDevice(ent, &dev); MIDIObjectGetStringProperty(dev, kMIDIPropertyName, &devname); MIDIObjectGetStringProperty(dst, kMIDIPropertyName, &endname); if (devname) CFStringGetCString(devname, cdevname, 1024, kCFStringEncodingUTF8); if (endname) CFStringGetCString(endname, cendname, 1024, kCFStringEncodingUTF8); } PyrString* string = newPyrString(g->gc, cendname, 0, true); SetObject(namearrayDe->slots + namearrayDe->size++, string); g->gc->GCWriteNew(namearrayDe, (PyrObject*)string); // we know string is white so we can use GCWriteNew PyrString* devstring = newPyrString(g->gc, cdevname, 0, true); SetObject(devarrayDe->slots + devarrayDe->size++, devstring); g->gc->GCWriteNew(devarrayDe, (PyrObject*)devstring); // we know devstring is white so we can use GCWriteNew SetInt(idarrayDe->slots + idarrayDe->size++, id); if (devname) CFRelease(devname); if (endname) CFRelease(endname); } return errNone; } int prConnectMIDIIn(struct VMGlobals* g, int numArgsPushed); int prConnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { PyrSlot* inputIndexSlot = g->sp - 1; PyrSlot* uidSlot = g->sp; int err, inputIndex, uid; err = slotIntVal(inputIndexSlot, &inputIndex); if (err) return errWrongType; if (inputIndex < 0 || inputIndex >= gNumMIDIInPorts) return errIndexOutOfRange; err = slotIntVal(uidSlot, &uid); if (err) return errWrongType; MIDIEndpointRef src = 0; MIDIObjectType mtype; MIDIObjectFindByUniqueID(uid, &src, &mtype); if (mtype != kMIDIObjectType_Source) return errFailed; // MIDIPortConnectSource's third parameter is just a unique value used to help // identify the source. It expects a void*, so we reinterpret_cast from uid to // avoid a compiler warning. // See: https://stackoverflow.com/questions/9051292/midireadproc-using-srcconnrefcon-to-listen-to-only-one-source MIDIPortConnectSource(gMIDIInPort[inputIndex], src, reinterpret_cast<void*>(uid)); return errNone; } int prDisconnectMIDIIn(struct VMGlobals* g, int numArgsPushed); int prDisconnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; if (inputIndex < 0 || inputIndex >= gNumMIDIInPorts) return errIndexOutOfRange; err = slotIntVal(c, &uid); if (err) return err; MIDIEndpointRef src = 0; MIDIObjectType mtype; MIDIObjectFindByUniqueID(uid, &src, &mtype); if (mtype != kMIDIObjectType_Source) return errFailed; MIDIPortDisconnectSource(gMIDIInPort[inputIndex], src); return errNone; } int prInitMIDI(struct VMGlobals* g, int numArgsPushed); int prInitMIDI(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, numIn, numOut; err = slotIntVal(b, &numIn); if (err) return errWrongType; err = slotIntVal(c, &numOut); if (err) return errWrongType; return initMIDI(numIn, numOut); } int prDisposeMIDIClient(VMGlobals* g, int numArgsPushed); int prDisposeMIDIClient(VMGlobals* g, int numArgsPushed) { return midiCleanUp(); } int prRestartMIDI(VMGlobals* g, int numArgsPushed); int prRestartMIDI(VMGlobals* g, int numArgsPushed) { MIDIRestart(); return errNone; } void freeSysex(MIDISysexSendRequest* pk); void freeSysex(MIDISysexSendRequest* pk) { free(pk); } int prSendSysex(VMGlobals* g, int numArgsPushed); int prSendSysex(VMGlobals* g, int numArgsPushed) { int err, uid, size; if (!isKindOfSlot(g->sp, s_int8array->u.classobj)) return errWrongType; PyrInt8Array* packet = slotRawInt8Array(g->sp); size = packet->size; PyrSlot* u = g->sp - 1; err = slotIntVal(u, &uid); if (err) return err; MIDIEndpointRef dest; MIDIObjectType mtype; MIDIObjectFindByUniqueID(uid, (MIDIObjectRef*)&dest, &mtype); if (mtype != kMIDIObjectType_Destination) return errFailed; if (!dest) return errFailed; MIDISysexSendRequest* pk = (MIDISysexSendRequest*)malloc(sizeof(MIDISysexSendRequest) + size); Byte* data = (Byte*)pk + sizeof(MIDISysexSendRequest); memcpy(data, packet->b, size); pk->complete = false; pk->destination = dest; pk->data = data; pk->bytesToSend = size; pk->completionProc = freeSysex; pk->completionRefCon = 0; return ((MIDISendSysex(pk) == (OSStatus)0) ? errNone : errFailed); } #if SC_IPHONE static struct mach_timebase_info machTimebaseInfo() { struct mach_timebase_info info; mach_timebase_info(&info); return info; } static MIDITimeStamp midiTime(float latencySeconds) { // add the latency expressed in seconds, to the current host time base. static struct mach_timebase_info info = machTimebaseInfo(); // cache the timebase info. Float64 latencyNanos = 1000000000 * latencySeconds; MIDITimeStamp latencyMIDI = (latencyNanos / (Float64)info.numer) * (Float64)info.denom; return (MIDITimeStamp)mach_absolute_time() + latencyMIDI; } #else static MIDITimeStamp midiTime(float latencySeconds) { // add the latency expressed in seconds, to the current host time base. UInt64 latencyNanos = 1000000000 * latencySeconds; // secs to nano return (MIDITimeStamp)AudioGetCurrentHostTime() + AudioConvertNanosToHostTime(latencyNanos); } #endif void sendmidi(int port, MIDIEndpointRef dest, int length, int hiStatus, int loStatus, int aval, int bval, float late); void sendmidi(int port, MIDIEndpointRef dest, int length, int hiStatus, int loStatus, int aval, int bval, float late) { MIDIPacketList mpktlist; MIDIPacketList* pktlist = &mpktlist; MIDIPacket* pk = MIDIPacketListInit(pktlist); ByteCount nData = (ByteCount)length; pk->data[0] = (Byte)(hiStatus & 0xF0) | (loStatus & 0x0F); pk->data[1] = (Byte)aval; pk->data[2] = (Byte)bval; pk = MIDIPacketListAdd(pktlist, sizeof(struct MIDIPacketList), pk, midiTime(late), nData, pk->data); /*OSStatus error =*/MIDISend(gMIDIOutPort[port], dest, pktlist); } int prSendMIDIOut(struct VMGlobals* g, int numArgsPushed); int prSendMIDIOut(struct VMGlobals* g, int numArgsPushed) { // port, uid, len, hiStatus, loStatus, a, b, latency // PyrSlot *m = g->sp - 8; PyrSlot* p = g->sp - 7; PyrSlot* u = g->sp - 6; PyrSlot* l = g->sp - 5; PyrSlot* his = g->sp - 4; PyrSlot* los = g->sp - 3; PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* plat = g->sp; int err, outputIndex, uid, length, hiStatus, loStatus, aval, bval; float late; err = slotIntVal(p, &outputIndex); if (err) return err; if (outputIndex < 0 || outputIndex >= gNumMIDIOutPorts) return errIndexOutOfRange; err = slotIntVal(u, &uid); if (err) return err; err = slotIntVal(l, &length); if (err) return err; err = slotIntVal(his, &hiStatus); if (err) return err; err = slotIntVal(los, &loStatus); if (err) return err; err = slotIntVal(a, &aval); if (err) return err; err = slotIntVal(b, &bval); if (err) return err; err = slotFloatVal(plat, &late); if (err) return err; MIDIEndpointRef dest; MIDIObjectType mtype; MIDIObjectFindByUniqueID(uid, (MIDIObjectRef*)&dest, &mtype); if (mtype != kMIDIObjectType_Destination) return errFailed; if (!dest) return errFailed; sendmidi(outputIndex, dest, length, hiStatus, loStatus, aval, bval, late); return errNone; } // not needed in CoreMIDI: int initMIDIClient() { return errNone; } int prInitMIDIClient(struct VMGlobals* g, int numArgsPushed); int prInitMIDIClient(struct VMGlobals* g, int numArgsPushed) { return initMIDIClient(); } //-------------- void initMIDIPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; gSysexData.reserve(1024); s_midiin = getsym("MIDIIn"); s_domidiaction = getsym("doAction"); s_midiNoteOnAction = getsym("doNoteOnAction"); s_midiNoteOffAction = getsym("doNoteOffAction"); s_midiTouchAction = getsym("doTouchAction"); s_midiControlAction = getsym("doControlAction"); s_midiPolyTouchAction = getsym("doPolyTouchAction"); s_midiProgramAction = getsym("doProgramAction"); s_midiBendAction = getsym("doBendAction"); s_midiSysexAction = getsym("doSysexAction"); s_midiInvalidSysexAction = getsym("doInvalidSysexAction"); // client can handle incorrect case s_midiSysrtAction = getsym("doSysrtAction"); s_midiSMPTEAction = getsym("doSMPTEaction"); s_numMIDIDev = getsym("prSetNumberOfDevices"); s_midiclient = getsym("MIDIClient"); definePrimitive(base, index++, "_ListMIDIEndpoints", prListMIDIEndpoints, 1, 0); definePrimitive(base, index++, "_InitMIDI", prInitMIDI, 3, 0); definePrimitive(base, index++, "_InitMIDIClient", prInitMIDIClient, 1, 0); definePrimitive(base, index++, "_ConnectMIDIIn", prConnectMIDIIn, 3, 0); definePrimitive(base, index++, "_DisconnectMIDIIn", prDisconnectMIDIIn, 3, 0); definePrimitive(base, index++, "_DisposeMIDIClient", prDisposeMIDIClient, 1, 0); definePrimitive(base, index++, "_RestartMIDI", prRestartMIDI, 1, 0); definePrimitive(base, index++, "_SendMIDIOut", prSendMIDIOut, 9, 0); definePrimitive(base, index++, "_SendSysex", prSendSysex, 3, 0); if (gMIDIClient) midiCleanUp(); }
29,487
C++
.cpp
721
32.747573
119
0.621875
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
29,861
PyrFilePrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrFilePrim.cpp
/* 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 */ /* Primitives for File i/o. */ /* SuperCollider headers */ #include "GC.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrSymbol.h" #include "PyrFilePrim.h" #include "ReadWriteMacros.h" #include "SCBase.h" #include "sc_popen.h" /* SuperCollider newer headers*/ #include "SC_SndFileHelpers.hpp" #include "SC_Filesystem.hpp" // resolveIfAlias #include "SC_Codecvt.hpp" // utf8_str_to_path, path_to_utf8_str /* C stdlib headers */ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <cerrno> #include <fcntl.h> #include <math.h> #include <sstream> /* C++ stdlib headers */ #include <tuple> #include <filesystem> /* system headers */ #ifndef _WIN32 # include <unistd.h> #else # include <direct.h> #endif #if defined(__APPLE__) || defined(SC_IPHONE) # include <CoreFoundation/CFString.h> # include <CoreFoundation/CFBundle.h> # ifndef SC_IPHONE # include <CoreServices/CoreServices.h> # endif #endif #define DELIMITOR ':' namespace fs = std::filesystem; int prFileDelete(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); std::error_code error_code; fs::remove(p, error_code); if (error_code) SetFalse(a); else SetTrue(a); return errNone; } int prFileDeleteAll(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); if (fs::remove_all(p) > 0) { SetTrue(a); } else { SetFalse(a); } return errNone; } std::time_t to_time_t(std::filesystem::file_time_type file_time) { using namespace std::chrono; // in case of C++20 update, consider // https://stackoverflow.com/questions/61030383/how-to-convert-stdfilesystemfile-time-type-to-time-t auto sctp = time_point_cast<system_clock::duration>(file_time - std::filesystem::file_time_type::clock::now() + system_clock::now()); return system_clock::to_time_t(sctp); } int prFileMTime(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); auto mtime = fs::last_write_time(p); SetInt(a, to_time_t(mtime)); return errNone; } int prFileExists(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); bool res = fs::exists(p); SetBool(a, res); return errNone; } int prFileRealPath(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char ipath[PATH_MAX]; char opath[PATH_MAX]; int err; err = slotStrVal(b, ipath, PATH_MAX); if (err) return err; bool isAlias = false; fs::path p = SC_Codecvt::utf8_str_to_path(ipath); p = SC_Filesystem::resolveIfAlias(p, isAlias); if (p.empty()) return errFailed; std::error_code error_code; p = fs::canonical(p, error_code).make_preferred(); if (error_code) { SetNil(a); return errNone; } strncpy(opath, SC_Codecvt::path_to_utf8_str(p).c_str(), PATH_MAX - 1); opath[PATH_MAX - 1] = '\0'; PyrString* pyrString = newPyrString(g->gc, opath, 0, true); SetObject(a, pyrString); return errNone; } int prFileMkDir(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); bool result = fs::create_directories(p); SetBool(a, result); return errNone; } int prFileCopy(struct VMGlobals* g, int numArgsPushed) { PyrSlot *b = g->sp - 1, *c = g->sp; char filename1[PATH_MAX]; char filename2[PATH_MAX]; int error; error = slotStrVal(b, filename1, PATH_MAX); if (error != errNone) return error; error = slotStrVal(c, filename2, PATH_MAX); if (error != errNone) return error; const fs::path& p1 = SC_Codecvt::utf8_str_to_path(filename1); const fs::path& p2 = SC_Codecvt::utf8_str_to_path(filename2); std::error_code error_code; fs::copy(p1, p2, error_code); if (error_code) { std::ostringstream s; s << error_code.message() << ": copy from \"" << filename1 << "\" to \"" << filename2 << "\""; throw std::runtime_error(s.str()); } return errNone; } int prFileTypeToInt(const fs::file_type& type) { // see https://en.cppreference.com/w/cpp/filesystem/file_type // and also check this with the `File.type` method located in // `Common/Files/Files.sc` switch (type) { case fs::file_type::none: return 0; case fs::file_type::not_found: return 1; case fs::file_type::regular: return 2; case fs::file_type::directory: return 3; case fs::file_type::symlink: return 4; case fs::file_type::block: return 5; case fs::file_type::character: return 6; case fs::file_type::fifo: return 7; case fs::file_type::socket: return 8; default: return 0; } } int prFileType(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); fs::file_status s(fs::symlink_status(p)); SetInt(a, prFileTypeToInt(s.type())); return errNone; } int prFileSize(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a = g->sp - 1, *b = g->sp; char filename[PATH_MAX]; int error = slotStrVal(b, filename, PATH_MAX); if (error != errNone) return error; const fs::path& p = SC_Codecvt::utf8_str_to_path(filename); uintmax_t sz = fs::file_size(p); SetInt(a, sz); return errNone; } int prFileOpen(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; char filename[PATH_MAX]; const size_t buf_size = 12; char mode[buf_size]; PyrFile* pfile; FILE* file; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotObj(c) || !isKindOf(slotRawObject(c), class_string) || NotObj(b) || !isKindOf(slotRawObject(b), class_string)) return errWrongType; if (slotRawObject(b)->size > PATH_MAX - 1) return errFailed; if (slotRawObject(c)->size > buf_size - 1) return errFailed; pfile = (PyrFile*)slotRawObject(a); memcpy(filename, slotRawString(b)->s, slotRawObject(b)->size); filename[slotRawString(b)->size] = 0; const fs::path& path = SC_Codecvt::utf8_str_to_path(filename); memcpy(mode, slotRawString(c)->s, slotRawObject(c)->size); mode[slotRawString(c)->size] = 0; #ifdef _WIN32 if (strcmp(mode, "w") == 0) strcpy(mode, "wb"); if (strcmp(mode, "r") == 0) strcpy(mode, "rb"); // use _wfopen on Windows for full Unicode compatibility wchar_t wmode[buf_size]; size_t wmode_size = 0; mbstowcs_s(&wmode_size, wmode, buf_size, mode, buf_size - 1); file = _wfopen(path.wstring().c_str(), wmode); #else file = fopen(path.c_str(), mode); #endif //_WIN32 if (file) { SetPtr(&pfile->fileptr, file); SetTrue(a); } else { #ifdef _WIN32 // check if directory exisits // create a temporary file (somewhere) for a handle // the file is deleted automatically when closed if (fs::is_directory(path)) { int err; # ifdef _MSC_VER err = tmpfile_s(&file); if (!err) { SetPtr(&pfile->fileptr, file); SetTrue(a); return errNone; } # elif defined(__MINGW32__) file = tmpfile(); if (file) { SetPtr(&pfile->fileptr, file); SetTrue(a); return errNone; } # else # error compiler unsupported # endif } #endif SetNil(a); SetFalse(a); } return errNone; } int prFileClose(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errNone; SetPtr(&pfile->fileptr, nullptr); if (fclose(file)) return errFailed; return errNone; } int prFileFlush(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file != nullptr) fflush(file); return errNone; } int prFilePos(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; long length; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if ((length = ftell(file)) == -1) return errFailed; SetInt(a, (int)length); return errNone; } int prFileLength(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrFile* pfile = (PyrFile*)slotRawObject(a); FILE* file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; // preserve file position fpos_t pos; if (fgetpos(file, &pos)) return errFailed; if (fseek(file, 0, SEEK_END)) return errFailed; size_t length; length = ftell(file); if (fsetpos(file, &pos)) return errFailed; SetInt(a, length); return errNone; } int prFileSeek(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; PyrFile* pfile; FILE* file; size_t offset; int origin; static int originTable[3] = { SEEK_SET, SEEK_CUR, SEEK_END }; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotInt(b)) return errWrongType; if (NotInt(c)) return errWrongType; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; offset = slotRawInt(b); origin = slotRawInt(c); if (origin < 0 || origin > 2) return errIndexOutOfRange; origin = originTable[origin]; // translate in case ANSI constants ever change.. if (fseek(file, offset, origin)) return errFailed; return errNone; } int prFileWrite(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *ptr; PyrFile* pfile; FILE* file; PyrObject* obj; char chr; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; switch (GetTag(b)) { case tagInt: { SC_IOStream<FILE*> scio(file); scio.writeInt32_be(slotRawInt(b)); break; } case tagSym: fwrite(slotRawSymbol(b)->name, sizeof(char), slotRawSymbol(b)->length, file); break; case tagChar: chr = slotRawChar(b); fwrite(&chr, sizeof(char), 1, file); break; case tagNil: case tagFalse: case tagTrue: case tagPtr: return errWrongType; case tagObj: { // writes the indexable part of any non obj_slot format object obj = slotRawObject(b); if (!isKindOf(obj, class_rawarray) || isKindOf(obj, class_symbolarray)) return errWrongType; if (obj->size) { ptr = obj->slots; int elemSize = gFormatElemSize[obj->obj_format]; int numElems = obj->size; #if BYTE_ORDER != BIG_ENDIAN switch (elemSize) { case 1: fwrite(ptr, elemSize, numElems, file); break; case 2: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 2; for (; ptr < ptrend; ptr += 2) { fputc(ptr[1], file); fputc(ptr[0], file); } break; } case 4: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 4; for (; ptr < ptrend; ptr += 4) { fputc(ptr[3], file); fputc(ptr[2], file); fputc(ptr[1], file); fputc(ptr[0], file); } break; } case 8: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 8; for (; ptr < ptrend; ptr += 8) { fputc(ptr[7], file); fputc(ptr[6], file); fputc(ptr[5], file); fputc(ptr[4], file); fputc(ptr[3], file); fputc(ptr[2], file); fputc(ptr[1], file); fputc(ptr[0], file); } break; } } #else fwrite(ptr, elemSize, numElems, file); #endif } break; } default: // double { SC_IOStream<FILE*> scio(file); scio.writeDouble_be(slotRawFloat(b)); break; } } return errNone; } int prFileWriteLE(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *ptr; PyrFile* pfile; FILE* file; PyrObject* obj; char chr; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; switch (GetTag(b)) { case tagInt: { SC_IOStream<FILE*> scio(file); scio.writeInt32_le(slotRawInt(b)); break; } case tagSym: fwrite(slotRawSymbol(b)->name, sizeof(char), slotRawSymbol(b)->length, file); break; case tagChar: chr = slotRawInt(b); fwrite(&chr, sizeof(char), 1, file); break; case tagNil: case tagFalse: case tagTrue: case tagPtr: return errWrongType; case tagObj: { // writes the indexable part of any non obj_slot format object obj = slotRawObject(b); if (!isKindOf(obj, class_rawarray) || isKindOf(obj, class_symbolarray)) return errWrongType; if (obj->size) { ptr = obj->slots; int elemSize = gFormatElemSize[obj->obj_format]; int numElems = obj->size; #if BYTE_ORDER == BIG_ENDIAN switch (elemSize) { case 1: fwrite(ptr, elemSize, numElems, file); break; case 2: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 2; for (; ptr < ptrend; ptr += 2) { fputc(ptr[1], file); fputc(ptr[0], file); } break; } case 4: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 4; for (; ptr < ptrend; ptr += 4) { fputc(ptr[3], file); fputc(ptr[2], file); fputc(ptr[1], file); fputc(ptr[0], file); } break; } case 8: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 8; for (; ptr < ptrend; ptr += 8) { fputc(ptr[7], file); fputc(ptr[6], file); fputc(ptr[5], file); fputc(ptr[4], file); fputc(ptr[3], file); fputc(ptr[2], file); fputc(ptr[1], file); fputc(ptr[0], file); } break; } } #else fwrite(ptr, elemSize, numElems, file); #endif } break; } default: // double { SC_IOStream<FILE*> scio(file); scio.writeDouble_le(slotRawFloat(b)); break; } } return errNone; } int prFileReadLine(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; // receiver(a File), string PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; char* result = fgets(slotRawString(b)->s, MAXINDEXSIZE(slotRawObject(b)) - 1, file); if (!result) { SetNil(a); } else { slotRawString(b)->size = strlen(slotRawString(b)->s); if (slotRawString(b)->s[slotRawString(b)->size - 1] == '\n') slotRawString(b)->size--; slotCopy(a, b); } return errNone; } int prFilePutInt32(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int val; int err = slotIntVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeInt32_be(val); return errNone; } int prFilePutInt16(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int val; int err = slotIntVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeInt16_be(val); return errNone; } int prFilePutInt32LE(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int val; int err = slotIntVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeInt32_le(val); return errNone; } int prFilePutInt16LE(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int val; int err = slotIntVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeInt16_le(val); return errNone; } int prFilePutInt8(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int val; int err = slotIntVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeInt8(val); return errNone; } int prFilePutChar(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; char z; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (NotChar(b)) return errWrongType; z = slotRawChar(b); SC_IOStream<FILE*> scio(file); scio.writeInt8(z); return errNone; } int prFilePutFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) { dumpObjectSlot(a); return errFailed; } float val; int err = slotFloatVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeFloat_be(val); return errNone; } int prFilePutDouble(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; double val; int err = slotDoubleVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeDouble_be(val); return errNone; } int prFilePutFloatLE(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) { dumpObjectSlot(a); return errFailed; } float val; int err = slotFloatVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeFloat_le(val); return errNone; } int prFilePutDoubleLE(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; double val; int err = slotDoubleVal(b, &val); if (err) return err; SC_IOStream<FILE*> scio(file); scio.writeDouble_le(val); return errNone; } int prFilePutString(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrFile* pfile; FILE* file; PyrString* string; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (NotObj(b) || slotRawObject(b)->classptr != class_string) return errWrongType; string = slotRawString(b); if (string->size) { fwrite(string->s, 1, string->size, file); } return errNone; } int prFileGetDouble(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetFloat(a, scio.readDouble_be()); } return errNone; } int prFileGetFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetFloat(a, scio.readFloat_be()); } return errNone; } int prFileGetDoubleLE(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetFloat(a, scio.readDouble_le()); } return errNone; } int prFileGetFloatLE(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetFloat(a, scio.readFloat_le()); } return errNone; } int prFileGetChar(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; char z; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int count = fread(&z, sizeof(char), 1, file); if (count == 0) SetNil(a); else SetChar(a, z); return errNone; } int prFileGetInt8(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; int8 z; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int count = fread(&z, sizeof(int8), 1, file); if (count == 0) SetNil(a); else SetInt(a, z); return errNone; } int prFileGetInt16(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetInt(a, scio.readInt16_be()); } return errNone; } int prFileGetInt32(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetInt(a, scio.readInt32_be()); } return errNone; } int prFileGetInt16LE(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetInt(a, scio.readInt16_le()); } return errNone; } int prFileGetInt32LE(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrFile* pfile; FILE* file; a = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; if (feof(file)) SetNil(a); else { SC_IOStream<FILE*> scio(file); SetInt(a, scio.readInt32_le()); } return errNone; } int prFileReadRaw(struct VMGlobals* g, int numArgsPushed) { PyrFile* pfile; FILE* file; PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (!isKindOfSlot(b, class_rawarray) || isKindOfSlot(b, class_symbolarray)) return errWrongType; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int elemSize = gFormatElemSize[slotRawObject(b)->obj_format]; int numElems = slotRawObject(b)->size; numElems = fread(slotRawString(b)->s, elemSize, numElems, file); slotRawObject(b)->size = numElems; #if BYTE_ORDER != BIG_ENDIAN switch (elemSize) { case 1: break; case 2: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 2; for (; ptr < ptrend; ptr += 2) { char temp = ptr[0]; ptr[0] = ptr[1]; ptr[1] = temp; } break; } case 4: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 4; for (; ptr < ptrend; ptr += 4) { char temp = ptr[0]; ptr[0] = ptr[3]; ptr[3] = temp; temp = ptr[1]; ptr[1] = ptr[2]; ptr[2] = temp; } break; } case 8: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 8; for (; ptr < ptrend; ptr += 8) { char temp = ptr[0]; ptr[0] = ptr[7]; ptr[7] = temp; temp = ptr[1]; ptr[1] = ptr[6]; ptr[6] = temp; temp = ptr[2]; ptr[2] = ptr[5]; ptr[5] = temp; temp = ptr[3]; ptr[3] = ptr[4]; ptr[4] = temp; } break; } } #endif if (slotRawObject(b)->size == 0) SetNil(a); else slotCopy(a, b); return errNone; } int prFileReadRawLE(struct VMGlobals* g, int numArgsPushed) { PyrFile* pfile; FILE* file; PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (!isKindOfSlot(b, class_rawarray) || isKindOfSlot(b, class_symbolarray)) return errWrongType; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errFailed; int elemSize = gFormatElemSize[slotRawObject(b)->obj_format]; int numElems = slotRawObject(b)->size; numElems = fread(slotRawString(b)->s, elemSize, numElems, file); slotRawObject(b)->size = numElems; #if BYTE_ORDER == BIG_ENDIAN switch (elemSize) { case 1: break; case 2: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 2; for (; ptr < ptrend; ptr += 2) { char temp = ptr[0]; ptr[0] = ptr[1]; ptr[1] = temp; } break; } case 4: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 4; for (; ptr < ptrend; ptr += 4) { char temp = ptr[0]; ptr[0] = ptr[3]; ptr[3] = temp; temp = ptr[1]; ptr[1] = ptr[2]; ptr[2] = temp; } break; } case 8: { char* ptr = slotRawString(b)->s; char* ptrend = ptr + numElems * 8; for (; ptr < ptrend; ptr += 8) { char temp = ptr[0]; ptr[0] = ptr[7]; ptr[7] = temp; temp = ptr[1]; ptr[1] = ptr[6]; ptr[6] = temp; temp = ptr[2]; ptr[2] = ptr[5]; ptr[5] = temp; temp = ptr[3]; ptr[3] = ptr[4]; ptr[4] = temp; } break; } } #endif if (slotRawObject(b)->size == 0) SetNil(a); else slotCopy(a, b); return errNone; } int prFileGetcwd(struct VMGlobals* g, int numArgsPushed) { // PyrSlot* a = g->sp - 1; // File PyrSlot* string = g->sp; if (!isKindOfSlot(string, class_string)) return errWrongType; #ifdef _WIN32 // use wide version, then convert to utf8 wchar_t buf[PATH_MAX]; wchar_t* wcwd = _wgetcwd(buf, PATH_MAX); if (wcwd == nullptr) { error(strerror(errno)); return errFailed; } const std::string cwd_str = SC_Codecvt::utf16_wcstr_to_utf8_string(wcwd); const char* cwd = cwd_str.c_str(); #else char buf[PATH_MAX]; const char* cwd = getcwd(buf, PATH_MAX); if (cwd == nullptr) { error(strerror(errno)); return errFailed; } #endif strcpy(slotRawString(string)->s, cwd); slotRawString(string)->size = strlen(slotRawString(string)->s); return errNone; } //----------------------------------------------------------------------------// // Pipe primitives //----------------------------------------------------------------------------// int prPipeOpen(struct VMGlobals* g, int numArgsPushed) { PyrSlot* callerSlot = g->sp - 2; PyrSlot* commandLineSlot = g->sp - 1; PyrSlot* modeSlot = g->sp; // commandLine and mode must be objects if (NotObj(modeSlot) || NotObj(commandLineSlot)) return errWrongType; PyrFile* pfile = reinterpret_cast<PyrFile*>(slotRawObject(callerSlot)); // c++17 structured binding declarations will make this into a single line // auto [error, string] = ... int error; std::string commandLine; std::tie(error, commandLine) = slotStrStdStrVal(commandLineSlot); if (error != errNone) return error; std::string mode; std::tie(error, mode) = slotStrStdStrVal(modeSlot); if (error != errNone) return error; pid_t pid; FILE* file; std::tie(pid, file) = sc_popen(std::move(commandLine), mode); if (file != nullptr) { SetPtr(&pfile->fileptr, file); SetInt(callerSlot, pid); } else { SetNil(callerSlot); } return errNone; } int prPipeOpenArgv(struct VMGlobals* g, int numArgsPushed) { PyrSlot* callerSlot = g->sp - 2; PyrSlot* argsSlot = g->sp - 1; PyrSlot* modeSlot = g->sp; //???? #ifdef SC_IPHONE SetInt(callerSlot, 0); return errNone; #endif // argsSlot must be an object if (NotObj(argsSlot) || NotObj(modeSlot)) return errWrongType; PyrFile* pfile = reinterpret_cast<PyrFile*>(slotRawObject(callerSlot)); PyrObject* argsColl = slotRawObject(argsSlot); // argsColl must be a collection if (!(slotRawInt(&argsColl->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; // collection must contain at least one string: the path of executable to run if (argsColl->size < 1) return errFailed; // c++17 structured binding declarations will make this into a single line // auto [error, mode] = ...; int error; std::string mode; std::tie(error, mode) = slotStrStdStrVal(modeSlot); if (error != errNone) return error; std::vector<std::string> strings; std::tie(error, strings) = PyrCollToVectorStdString(argsColl); if (error != errNone) return error; pid_t pid; FILE* file; std::tie(pid, file) = sc_popen_argv(strings, mode); if (file != nullptr) { SetPtr(&pfile->fileptr, file); SetInt(callerSlot, pid); } else { SetNil(callerSlot); } return errNone; } int prPipeClose(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrSlot* b; PyrFile* pfile; FILE* file; pid_t pid; a = g->sp - 1; b = g->sp; pfile = (PyrFile*)slotRawObject(a); file = (FILE*)slotRawPtr(&pfile->fileptr); if (file == nullptr) return errNone; pid = (pid_t)slotRawInt(b); SetPtr(&pfile->fileptr, nullptr); int perr = sc_pclose(file, pid); SetInt(a, perr); if (perr == -1) return errFailed; return errNone; } //----------------------------------------------------------------------------// // SoundFile primitives //----------------------------------------------------------------------------// #ifndef NO_LIBSNDFILE int sampleFormatToString(struct SF_INFO* info, const char** string) { unsigned int format = info->format & SF_FORMAT_SUBMASK; switch (format) { case SF_FORMAT_DPCM_8: case SF_FORMAT_PCM_S8: *string = "int16"; break; case SF_FORMAT_DPCM_16: case SF_FORMAT_PCM_16: case SF_FORMAT_DWVW_16: *string = "int16"; break; case SF_FORMAT_PCM_24: case SF_FORMAT_DWVW_24: *string = "int24"; break; case SF_FORMAT_PCM_32: *string = "int32"; break; case SF_FORMAT_FLOAT: *string = "float"; break; case SF_FORMAT_DOUBLE: *string = "double"; break; case SF_FORMAT_ULAW: *string = "ulaw"; break; case SF_FORMAT_ALAW: *string = "alaw"; break; # ifdef SNDFILE_HAS_VORBIS case SF_FORMAT_VORBIS: *string = "vorbis"; break; # endif # ifdef SNDFILE_HAS_OPUS case SF_FORMAT_OPUS: *string = "opus"; break; # endif # ifdef SNDFILE_HAS_MPEG case SF_FORMAT_MPEG_LAYER_I: *string = "mp1"; break; case SF_FORMAT_MPEG_LAYER_II: *string = "mp2"; break; case SF_FORMAT_MPEG_LAYER_III: *string = "mp3"; break; # endif default: *string = "float"; break; } return errNone; } int headerFormatToString(struct SF_INFO* info, const char** string) { switch (info->format & SF_FORMAT_TYPEMASK) { case SF_FORMAT_WAV: *string = "WAV"; break; case SF_FORMAT_AIFF: *string = "AIFF"; break; case SF_FORMAT_AU: *string = "SUN"; break; case SF_FORMAT_IRCAM: *string = "IRCAM"; break; case SF_FORMAT_RAW: *string = "raw"; break; case SF_FORMAT_W64: *string = "W64"; break; case SF_FORMAT_RF64: *string = "RF64"; break; case SF_FORMAT_FLAC: *string = "FLAC"; break; # if defined(SNDFILE_HAS_VORBIS) || defined(SNDFILE_HAS_OPUS) case SF_FORMAT_OGG: *string = "OGG"; break; # endif # ifdef SNDFILE_HAS_MPEG case SF_FORMAT_MPEG: *string = "MPEG"; break; # endif /* case SF_FORMAT_PAF : break ; case SF_FORMAT_SVX : break ; case SF_FORMAT_NIST : break ; case SF_FORMAT_VOC : break ; case SF_FORMAT_MAT4 : break ; case SF_FORMAT_MAT5 : break ; case SF_FORMAT_PVF : break ; case SF_FORMAT_XI : break ; case SF_FORMAT_HTK : break ; case SF_FORMAT_SDS : break ; */ default: *string = " "; break; } return errNone; } int sndfileFormatInfoToStrings(struct SF_INFO* info, const char** stringHead, const char** stringSample) { int error = 0; error = headerFormatToString(info, stringHead); error = sampleFormatToString(info, stringSample); return error; } int prSFOpenRead(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; char filename[PATH_MAX]; SNDFILE* file; SF_INFO info; const char* headerstr; const char* sampleformatstr; a = g->sp - 1; b = g->sp; PyrObject* obj1 = slotRawObject(a); if (!isKindOfSlot(b, class_string)) return errWrongType; if (slotRawObject(b)->size > PATH_MAX - 1) return errFailed; memcpy(filename, slotRawString(b)->s, slotRawObject(b)->size); filename[slotRawString(b)->size] = 0; info.format = 0; file = sndfileOpenFromCStr(filename, SFM_READ, &info); if (file) { SetPtr(obj1->slots + 0, file); sndfileFormatInfoToStrings(&info, &headerstr, &sampleformatstr); // headerFormatToString(&info, &headerstr); PyrString* hpstr = newPyrString(g->gc, headerstr, 0, true); SetObject(obj1->slots + 1, hpstr); g->gc->GCWriteNew(obj1, (PyrObjectHdr*)hpstr); // we know hpstr is white so we can use GCWriteNew PyrString* smpstr = newPyrString(g->gc, sampleformatstr, 0, true); SetObject(obj1->slots + 2, smpstr); g->gc->GCWriteNew(obj1, (PyrObjectHdr*)smpstr); // we know smpstr is white so we can use GCWriteNew SetInt(obj1->slots + 3, info.frames); SetInt(obj1->slots + 4, info.channels); SetInt(obj1->slots + 5, info.samplerate); SetTrue(a); } else { SetNil(a); SetFalse(a); } return errNone; } int prSFOpenWrite(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; char filename[PATH_MAX]; SNDFILE* file; SF_INFO info; PyrSlot* headerSlot; PyrSlot* formatSlot; int error; a = g->sp - 1; b = g->sp; headerSlot = (slotRawObject(a)->slots + 1); formatSlot = (slotRawObject(a)->slots + 2); if (!isKindOfSlot(headerSlot, class_string)) return errWrongType; if (!isKindOfSlot(formatSlot, class_string)) return errWrongType; if (!isKindOfSlot(b, class_string)) return errWrongType; if (slotRawObject(b)->size > PATH_MAX - 1) return errFailed; memcpy(filename, slotRawString(b)->s, slotRawObject(b)->size); filename[slotRawString(b)->size] = 0; # ifdef _WIN32 char* headerFormat = (char*)malloc(slotRawObject(headerSlot)->size); # else char headerFormat[slotRawString(headerSlot)->size]; # endif memcpy(headerFormat, slotRawString(headerSlot)->s, slotRawObject(headerSlot)->size); headerFormat[slotRawString(headerSlot)->size] = 0; # ifdef _WIN32 char* sampleFormat = (char*)malloc(slotRawString(formatSlot)->size); # else char sampleFormat[slotRawString(formatSlot)->size]; # endif memcpy(sampleFormat, slotRawString(formatSlot)->s, slotRawObject(formatSlot)->size); sampleFormat[slotRawString(formatSlot)->size] = 0; error = sndfileFormatInfoFromStrings(&info, headerFormat, sampleFormat); if (error) { # ifdef _WIN32 free(sampleFormat); free(headerFormat); # endif return errFailed; } if (error) return errFailed; // slotIntVal(slotRawObject(a)->slots + 3, &info.frames); slotIntVal(slotRawObject(a)->slots + 4, &info.channels); slotIntVal(slotRawObject(a)->slots + 5, &info.samplerate); file = sndfileOpenFromCStr(filename, SFM_WRITE, &info); sf_command(file, SFC_SET_CLIPPING, nullptr, SF_TRUE); if (file) { SetPtr(slotRawObject(a)->slots + 0, file); SetTrue(a); } else { SetNil(a); SetFalse(a); } return errNone; } int prSFClose(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SNDFILE* file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); if (file) { sf_close(file); SetNil(slotRawObject(a)->slots + 0); } return errNone; } int prSFRead(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; a = g->sp - 1; b = g->sp; SNDFILE* file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); if (!isKindOfSlot(b, class_rawarray)) return errWrongType; switch (slotRawObject(b)->obj_format) { case obj_int16: slotRawObject(b)->size = sf_read_short(file, (short*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_int32: slotRawObject(b)->size = sf_read_int(file, (int*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_float: slotRawObject(b)->size = sf_read_float(file, (float*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_double: slotRawObject(b)->size = sf_read_double(file, (double*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; default: error("sample format not supported.\n"); return errFailed; } return errNone; } int prSFWrite(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; a = g->sp - 1; b = g->sp; SNDFILE* file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); if (!isKindOfSlot(b, class_rawarray)) return errWrongType; switch (slotRawObject(b)->obj_format) { case obj_int16: sf_write_short(file, (short*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_int32: sf_write_int(file, (int*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_float: sf_write_float(file, (float*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; case obj_double: sf_write_double(file, (double*)slotRawInt8Array(b)->b, slotRawObject(b)->size); break; default: error("sample format not supported.\n"); return errFailed; } return errNone; } int prSFSeek(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; a = g->sp - 2; b = g->sp - 1; c = g->sp; SNDFILE* file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); int origin, offset; int err = slotIntVal(b, &offset); if (err) return err; err = slotIntVal(c, &origin); if (err) return err; sf_seek(file, offset, origin); return errNone; } int prSFHeaderInfoString(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SNDFILE* file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]); if (file) { static char strbuffer[(1 << 16)]; sf_command(file, SFC_GET_LOG_INFO, strbuffer, (1 << 16)); PyrString* pstring = newPyrString(g->gc, strbuffer, 0, true); // post(strbuffer); SetObject(a, pstring); return errNone; } return errFailed; } #else // !NO_LIBSNDFILE int prSFOpenRead(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFOpenWrite(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFClose(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFWrite(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFRead(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFSeek(struct VMGlobals* g, int numArgsPushed) { return errFailed; } int prSFHeaderInfoString(struct VMGlobals* g, int numArgsPushed) { return errFailed; } #endif // !NO_LIBSNDFILE ///////////// void initFilePrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_SFOpenRead", prSFOpenRead, 2, 0); definePrimitive(base, index++, "_SFOpenWrite", prSFOpenWrite, 2, 0); definePrimitive(base, index++, "_SFClose", prSFClose, 1, 0); definePrimitive(base, index++, "_SFWrite", prSFWrite, 2, 0); definePrimitive(base, index++, "_SFRead", prSFRead, 2, 0); definePrimitive(base, index++, "_SFSeek", prSFSeek, 3, 0); definePrimitive(base, index++, "_SFHeaderInfoString", prSFHeaderInfoString, 1, 0); definePrimitive(base, index++, "_PipeOpen", prPipeOpen, 3, 0); definePrimitive(base, index++, "_PipeOpenArgv", prPipeOpenArgv, 3, 0); definePrimitive(base, index++, "_PipeClose", prPipeClose, 2, 0); definePrimitive(base, index++, "_FileDelete", prFileDelete, 2, 0); definePrimitive(base, index++, "_FileDeleteAll", prFileDeleteAll, 2, 0); definePrimitive(base, index++, "_FileMTime", prFileMTime, 2, 0); definePrimitive(base, index++, "_FileExists", prFileExists, 2, 0); definePrimitive(base, index++, "_FileRealPath", prFileRealPath, 2, 0); definePrimitive(base, index++, "_FileMkDir", prFileMkDir, 2, 0); definePrimitive(base, index++, "_FileCopy", prFileCopy, 3, 0); definePrimitive(base, index++, "_FileType", prFileType, 2, 0); definePrimitive(base, index++, "_FileSize", prFileSize, 2, 0); definePrimitive(base, index++, "_FileOpen", prFileOpen, 3, 0); definePrimitive(base, index++, "_FileClose", prFileClose, 1, 0); definePrimitive(base, index++, "_FileFlush", prFileFlush, 1, 0); definePrimitive(base, index++, "_FileSeek", prFileSeek, 3, 0); definePrimitive(base, index++, "_FilePos", prFilePos, 1, 0); definePrimitive(base, index++, "_FileLength", prFileLength, 1, 0); definePrimitive(base, index++, "_FileWrite", prFileWrite, 2, 0); definePrimitive(base, index++, "_FileWriteLE", prFileWriteLE, 2, 0); definePrimitive(base, index++, "_FileReadLine", prFileReadLine, 2, 0); definePrimitive(base, index++, "_File_getcwd", prFileGetcwd, 2, 0); definePrimitive(base, index++, "_FilePutChar", prFilePutChar, 2, 0); definePrimitive(base, index++, "_FilePutInt8", prFilePutInt8, 2, 0); definePrimitive(base, index++, "_FilePutInt16", prFilePutInt16, 2, 0); definePrimitive(base, index++, "_FilePutInt32", prFilePutInt32, 2, 0); definePrimitive(base, index++, "_FilePutFloat", prFilePutFloat, 2, 0); definePrimitive(base, index++, "_FilePutDouble", prFilePutDouble, 2, 0); definePrimitive(base, index++, "_FilePutInt16LE", prFilePutInt16LE, 2, 0); definePrimitive(base, index++, "_FilePutInt32LE", prFilePutInt32LE, 2, 0); definePrimitive(base, index++, "_FilePutFloatLE", prFilePutFloatLE, 2, 0); definePrimitive(base, index++, "_FilePutDoubleLE", prFilePutDoubleLE, 2, 0); definePrimitive(base, index++, "_FileGetChar", prFileGetChar, 1, 0); definePrimitive(base, index++, "_FileGetInt8", prFileGetInt8, 1, 0); definePrimitive(base, index++, "_FileGetInt16", prFileGetInt16, 1, 0); definePrimitive(base, index++, "_FileGetInt32", prFileGetInt32, 1, 0); definePrimitive(base, index++, "_FileGetFloat", prFileGetFloat, 1, 0); definePrimitive(base, index++, "_FileGetDouble", prFileGetDouble, 1, 0); definePrimitive(base, index++, "_FileGetInt16LE", prFileGetInt16LE, 1, 0); definePrimitive(base, index++, "_FileGetInt32LE", prFileGetInt32LE, 1, 0); definePrimitive(base, index++, "_FileGetFloatLE", prFileGetFloatLE, 1, 0); definePrimitive(base, index++, "_FileGetDoubleLE", prFileGetDoubleLE, 1, 0); definePrimitive(base, index++, "_FilePutString", prFilePutString, 2, 0); definePrimitive(base, index++, "_FileReadRaw", prFileReadRaw, 2, 0); definePrimitive(base, index++, "_FileReadRawLE", prFileReadRawLE, 2, 0); }
50,657
C++
.cpp
1,613
24.711717
113
0.59045
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
29,863
PyrMathPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrMathPrim.cpp
/* 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 "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrMathPrim.h" #include "MiscInlineMath.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSignal.h" #include "PyrParseNode.h" #include "PyrMessage.h" #include "clz.h" #include <stdlib.h> #include <string.h> #include <math.h> #include "SC_Endian.h" #include "SCBase.h" #define BOOST_MATH_DISABLE_FLOAT128 1 #include "boost/math/special_functions.hpp" #include "boost/math/special_functions/spherical_harmonic.hpp" #include "boost/math/special_functions/legendre.hpp" #include "PyrSymbol.h" #include <vector> const int INT_MAX_BY_PyrSlot = INT_MAX / sizeof(PyrSlot); inline bool IsSignal(PyrSlot* slot) { return (IsObj(slot) && slotRawObject(slot)->classptr == class_signal); } inline bool NotSignal(PyrSlot* slot) { return (NotObj(slot) || slotRawObject(slot)->classptr != class_signal); } /* functors for dispatching template code */ struct addNum { static inline double run(double lhs, double rhs) { return lhs + rhs; } static inline int run(int lhs, int rhs) { return lhs + rhs; } static inline PyrObject* signal_xf(VMGlobals* g, PyrObject* ina, float inb) { return signal_add_xf(g, ina, inb); } static inline PyrObject* signal_fx(VMGlobals* g, float ina, PyrObject* inb) { return signal_xf(g, inb, ina); } static inline PyrObject* signal_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { return signal_add_xx(g, ina, inb); } }; struct mulNum { static inline double run(double lhs, double rhs) { return lhs * rhs; } static inline int run(int lhs, int rhs) { return lhs * rhs; } static inline PyrObject* signal_xf(VMGlobals* g, PyrObject* ina, float inb) { return signal_mul_xf(g, ina, inb); } static inline PyrObject* signal_fx(VMGlobals* g, float ina, PyrObject* inb) { return signal_xf(g, inb, ina); } static inline PyrObject* signal_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { return signal_mul_xx(g, ina, inb); } }; struct subNum { static inline double run(double lhs, double rhs) { return lhs - rhs; } static inline int run(int lhs, int rhs) { return lhs - rhs; } static inline PyrObject* signal_xf(VMGlobals* g, PyrObject* ina, float inb) { return signal_sub_xf(g, ina, inb); } static inline PyrObject* signal_fx(VMGlobals* g, float ina, PyrObject* inb) { return signal_sub_fx(g, ina, inb); } static inline PyrObject* signal_xx(VMGlobals* g, PyrObject* ina, PyrObject* inb) { return signal_sub_xx(g, ina, inb); } }; template <typename Functor> inline int prOpNum(VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrSymbol* msg; a = g->sp - 1; b = g->sp; switch (GetTag(a)) { case tagInt: switch (GetTag(b)) { case tagInt: SetRaw(a, Functor::run(slotRawInt(a), slotRawInt(b))); break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) SetObject(a, Functor::signal_fx(g, slotRawInt(a), slotRawObject(b))); else goto send_normal_2; break; default: SetFloat(a, slotRawInt(a) + slotRawFloat(b)); break; } break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: // leave self in 'a' break; case tagObj: if (isKindOf(slotRawObject(a), class_signal)) { switch (GetTag(b)) { case tagInt: SetRaw(a, Functor::signal_xf(g, slotRawObject(a), slotRawInt(b))); break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) { SetRaw(a, Functor::signal_xx(g, slotRawObject(a), slotRawObject(b))); } else goto send_normal_2; break; default: // double SetRaw(a, Functor::signal_xf(g, slotRawObject(a), slotRawFloat(b))); break; } } else goto send_normal_2; break; default: // double switch (GetTag(b)) { case tagInt: SetRaw(a, Functor::run(slotRawFloat(a), (double)slotRawInt(b))); break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) SetObject(a, Functor::signal_fx(g, slotRawFloat(a), slotRawObject(b))); else goto send_normal_2; break; default: // double SetRaw(a, Functor::run(slotRawFloat(a), slotRawFloat(b))); break; } break; } g->sp--; // drop g->numpop = 0; #if TAILCALLOPTIMIZE g->tailCall = 0; #endif return errNone; send_normal_2: if (numArgsPushed != -1) // special case flag meaning it is a primitive return errFailed; // arguments remain on the stack msg = gSpecialBinarySelectors[g->primitiveIndex]; sendMessage(g, msg, 2, 0); return errNone; } template <typename Functor> inline int prOpInt(VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrSymbol* msg; a = g->sp - 1; b = g->sp; switch (GetTag(b)) { case tagInt: SetRaw(a, Functor::run(slotRawInt(a), slotRawInt(b))); break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) SetObject(a, Functor::signal_fx(g, slotRawInt(a), slotRawObject(b))); else goto send_normal_2; break; default: SetFloat(a, Functor::run((double)slotRawInt(a), slotRawFloat(b))); break; } g->sp--; // drop g->numpop = 0; #if TAILCALLOPTIMIZE g->tailCall = 0; #endif return errNone; send_normal_2: if (numArgsPushed != -1) // special case flag meaning it is a primitive return errFailed; // arguments remain on the stack msg = gSpecialBinarySelectors[g->primitiveIndex]; sendMessage(g, msg, 2, 0); return errNone; } template <typename Functor> inline int prOpFloat(VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrSymbol* msg; a = g->sp - 1; b = g->sp; switch (GetTag(b)) { case tagInt: SetRaw(a, Functor::run(slotRawFloat(a), (double)slotRawInt(b))); break; case tagChar: case tagPtr: case tagNil: case tagFalse: case tagTrue: goto send_normal_2; case tagSym: SetSymbol(a, slotRawSymbol(b)); break; case tagObj: if (isKindOf(slotRawObject(b), class_signal)) SetObject(a, Functor::signal_fx(g, slotRawFloat(a), slotRawObject(b))); else goto send_normal_2; break; default: SetRaw(a, Functor::run(slotRawFloat(a), slotRawFloat(b))); break; } g->sp--; // drop g->numpop = 0; #if TAILCALLOPTIMIZE g->tailCall = 0; #endif return errNone; send_normal_2: if (numArgsPushed != -1) // special case flag meaning it is a primitive return errFailed; // arguments remain on the stack msg = gSpecialBinarySelectors[g->primitiveIndex]; sendMessage(g, msg, 2, 0); return errNone; } int prAddNum(VMGlobals* g, int numArgsPushed) { return prOpNum<addNum>(g, numArgsPushed); } int prSubNum(VMGlobals* g, int numArgsPushed) { return prOpNum<subNum>(g, numArgsPushed); } int prMulNum(VMGlobals* g, int numArgsPushed) { return prOpNum<mulNum>(g, numArgsPushed); } int prAddFloat(VMGlobals* g, int numArgsPushed) { return prOpFloat<addNum>(g, numArgsPushed); } int prSubFloat(VMGlobals* g, int numArgsPushed) { return prOpFloat<subNum>(g, numArgsPushed); } int prMulFloat(VMGlobals* g, int numArgsPushed) { return prOpFloat<mulNum>(g, numArgsPushed); } int prAddInt(VMGlobals* g, int numArgsPushed) { return prOpInt<addNum>(g, numArgsPushed); } int prSubInt(VMGlobals* g, int numArgsPushed) { return prOpInt<subNum>(g, numArgsPushed); } int prMulInt(VMGlobals* g, int numArgsPushed) { return prOpInt<mulNum>(g, numArgsPushed); } int prNthPrime(VMGlobals* g, int numArgsPushed) { PyrSlot* a; int n, p; a = g->sp; n = slotRawInt(a); p = nthPrime(n); if (p == 0) { SetNil(a); } else { SetInt(a, p); } return errNone; } int prPrevPrime(VMGlobals* g, int numArgsPushed) { PyrSlot* a; int n, p, i; a = g->sp; n = slotRawInt(a); i = prevPrime(n); p = nthPrime(i); if (p == 0) { SetNil(a); } else { SetInt(a, p); } return errNone; } int prNextPrime(VMGlobals* g, int numArgsPushed) { PyrSlot* a; int n, p, i; a = g->sp; n = slotRawInt(a); i = nextPrime(n); p = nthPrime(i); if (p == 0) { SetNil(a); } else { SetInt(a, p); } return errNone; } int prIsPrime(VMGlobals* g, int numArgsPushed) { PyrSlot* a; int n, p, sqrtn, i; a = g->sp; n = slotRawInt(a); SetNil(a); if (n <= 2) { if (n == 2) { SetTrue(a); } else { SetFalse(a); } } else if (n <= nthPrime(NUMPRIMES - 1)) { // do a search of the primes table i = findPrime(n); if (i >= 0) { SetTrue(a); } else { SetFalse(a); } } else { #ifdef _WIN32 sqrtn = (int)sqrt(static_cast<double>(n)); #else sqrtn = (int)sqrt(n); #endif for (i = 0; i < NUMPRIMES; ++i) { p = nthPrime(i); if (n % p == 0) { SetFalse(a); break; } if (p >= sqrtn) { SetTrue(a); break; } } } return errNone; } int prIndexOfPrime(VMGlobals* g, int numArgsPushed) { PyrSlot* a; int n, p; a = g->sp; n = slotRawInt(a); if (n <= 2) { if (n == 2) { SetInt(a, 0); } else { SetNil(a); } } else if (n <= nthPrime(NUMPRIMES - 1)) { p = findPrime(n); if (p < 0) { SetNil(a); } else { SetInt(a, p); } } else { SetNil(a); } return errNone; } int prAs32Bits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; // return an integer that is a bit pattern for the 32 bit float representation union { float f; int32 i; } u; u.f = slotRawFloat(a); SetInt(a, u.i); return errNone; } int prHigh32Bits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; #if BYTE_ORDER == BIG_ENDIAN union { struct { uint32 hi, lo; } i; double f; } du; #else union { struct { uint32 lo, hi; } i; double f; } du; #endif du.f = slotRawFloat(a); SetInt(a, du.i.hi); return errNone; } int prLow32Bits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; #if BYTE_ORDER == BIG_ENDIAN union { struct { uint32 hi, lo; } i; double f; } du; #else union { struct { uint32 lo, hi; } i; double f; } du; #endif du.f = slotRawFloat(a); SetInt(a, du.i.lo); return errNone; } int prFrom32Bits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; int err, word; err = slotIntVal(b, &word); if (err) return err; union { float f; int32 i; } u; u.i = word; SetFloat(a, u.f); return errNone; } int prFrom64Bits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, hi, lo; err = slotIntVal(b, &hi); if (err) return err; err = slotIntVal(c, &lo); if (err) return err; #if BYTE_ORDER == BIG_ENDIAN union { struct { uint32 hi, lo; } i; double f; } du; #else union { struct { uint32 lo, hi; } i; double f; } du; #endif du.i.hi = hi; du.i.lo = lo; SetFloat(a, du.f); return errNone; } int mathClipInt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; double lo, hi; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsInt(b) && IsInt(c)) { SetRaw(a, sc_clip(slotRawInt(a), slotRawInt(b), slotRawInt(c))); } else { err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetFloat(a, sc_clip((double)slotRawInt(a), lo, hi)); } return errNone; } int mathClipFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; double lo, hi; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else { err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetRaw(a, sc_clip(slotRawFloat(a), lo, hi)); } return errNone; } int mathClipSignal(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; float lo, hi; int err; PyrObject* sig; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsSignal(b) && IsSignal(c)) { sig = signal_clip_x(g, slotRawObject(a), slotRawObject(b), slotRawObject(c)); SetObject(a, sig); } else { err = slotFloatVal(b, &lo); if (err) return err; err = slotFloatVal(c, &hi); if (err) return err; sig = signal_clip_f(g, slotRawObject(a), lo, hi); SetObject(a, sig); } return errNone; } int mathWrapInt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsInt(b) && IsInt(c)) { SetRaw(a, sc_mod((int)(slotRawInt(a) - slotRawInt(b)), (int)(slotRawInt(c) - slotRawInt(b) + 1)) + slotRawInt(b)); } else { double x, lo, hi; x = slotRawInt(a); err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetFloat(a, sc_mod(x - lo, hi - lo) + lo); } return errNone; } int mathWrapFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; double lo, hi; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else { err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetRaw(a, sc_mod(slotRawFloat(a) - lo, hi - lo) + lo); } return errNone; } int mathWrapSignal(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; float lo, hi; int err; PyrObject* sig; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsSignal(b) && IsSignal(c)) { sig = signal_wrap_x(g, slotRawObject(a), slotRawObject(b), slotRawObject(c)); SetObject(a, sig); } else { err = slotFloatVal(b, &lo); if (err) return err; err = slotFloatVal(c, &hi); if (err) return err; sig = signal_wrap_f(g, slotRawObject(a), lo, hi); SetObject(a, sig); } return errNone; } int mathFoldInt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsInt(b) && IsInt(c)) { SetRaw(a, sc_fold(slotRawInt(a), slotRawInt(b), slotRawInt(c))); } else { double x, lo, hi; x = slotRawInt(a); err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetFloat(a, sc_fold(x, lo, hi)); } return errNone; } int mathFoldFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; double lo, hi; int err; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else { err = slotDoubleVal(b, &lo); if (err) return err; err = slotDoubleVal(c, &hi); if (err) return err; SetRaw(a, sc_fold(slotRawFloat(a), lo, hi)); } return errNone; } int mathFoldSignal(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; float lo, hi; int err; PyrObject* sig; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (IsSym(b)) { *a = *b; } else if (IsSym(c)) { *a = *c; } else if (IsSignal(b) && IsSignal(c)) { sig = signal_fold_x(g, slotRawObject(a), slotRawObject(b), slotRawObject(c)); SetObject(a, sig); } else { err = slotFloatVal(b, &lo); if (err) return err; err = slotFloatVal(c, &hi); if (err) return err; sig = signal_fold_f(g, slotRawObject(a), lo, hi); SetObject(a, sig); } return errNone; } int prSimpleNumberSeries(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, size; if (IsInt(a) && (IsInt(b) || IsNil(b)) && IsInt(c)) { int first, second, last, step; first = slotRawInt(a); last = slotRawInt(c); second = IsInt(b) ? slotRawInt(b) : (first < last ? first + 1 : first - 1); step = second - first; if (step == 0) size = 1; else size = ((last - first) / step) + 1; if ((size < 1) || ((step >= 0) && (last < first)) || ((step <= 0) && (last > first))) { post("prSimpleNumberSeries: arguments do not form an arithmetic progression:\n\tfirst: %i, step: %i, last " "%i\n", first, step, last); return errFailed; } if (size > INT_MAX_BY_PyrSlot) { post("prSimpleNumberSeries: array size %i exceeds limit (%i)\n", size, INT_MAX_BY_PyrSlot); return errFailed; } PyrObject* obj = newPyrArray(g->gc, size, 0, true); obj->size = size; PyrSlot* slots = obj->slots; if (step == 1) { // Faster iteration for common case if (first == 0) { for (int i = 0; i < size; ++i) { SetInt(slots + i, i); } } else { for (int i = 0; i < size; ++i) { SetInt(slots + i, first++); } } } else { int val = first; for (int i = 0; i < size; ++i) { SetInt(slots + i, val); val += step; } } SetObject(a, obj); } else { double first, second, last, step; err = slotDoubleVal(a, &first); if (err) return err; err = slotDoubleVal(c, &last); if (err) return err; err = slotDoubleVal(b, &second); if (err) { if (first < last) second = first + 1.; else second = first - 1.; } step = second - first; if (step == 0.f) { size = 1; } else { size = (int)((last - first) / step) + 1; } if ((size < 1) || ((step >= 0) && (last < first)) || ((step <= 0) && (last > first))) { post("prSimpleNumberSeries: arguments do not form an arithmetic progression:\n\tfirst: %f, step: %f, last " "%f\n", first, step, last); return errFailed; } if (size > INT_MAX_BY_PyrSlot) { post("prSimpleNumberSeries: array size %i exceeds limit (%i)\n", size, INT_MAX_BY_PyrSlot); return errFailed; } PyrObject* obj = newPyrArray(g->gc, size, 0, true); obj->size = size; PyrSlot* slots = obj->slots; if (first == 0. && step == 1.) { // Faster iteration for common case for (long i = 0; i < size; ++i) { SetFloat(slots + i, i); } } else { double val = first; for (long i = 0; i < size; ++i) { val = first + step * i; SetFloat(slots + i, val); } } SetObject(a, obj); } return errNone; } /* asFraction {|maxDenominator=100| var mediant, lower, upper, temp; var n,d, k, k1; if (this < 0) { #n, d = this.neg.asFraction(maxDenominator); ^[n.neg, d] }; if (this < 1.0) { upper = [1.0, this.reciprocal.floor]; lower = [1.0, upper[1]+1.0]; }{ lower = [this.floor, 1.0]; upper = [lower[0]+1.0, 1.0]; }; mediant = [lower[0] + upper[0], lower[1] + upper[1]]; loop { mediant = [lower[0] + upper[0], lower[1] + upper[1]]; case { (this * mediant[1]) > mediant[0] } { if (maxDenominator < mediant[1]) {^upper}; d = upper[0] - (this * upper[1]); if (d == 0) {^upper}; lower = mediant; k = floor(((this * lower[1]) - lower[0]) / d); k1 = k + 1; temp = [lower[0] + (k1 * upper[0]), lower[1] + (k1 * upper[1])]; lower = [lower[0] + (k * upper[0]), lower[1] + (k * upper[1])]; upper = temp; } { (this * mediant[1]) == mediant[0] } { if (maxDenominator >= mediant[1]) {^mediant}; if (lower[1] < upper[1]) {^lower}; ^upper } { if (maxDenominator < mediant[1]) {^lower}; d = lower[0] - (this * lower[1]); if (d == 0) {^lower}; upper = mediant; k = floor(((this * upper[1]) - upper[0]) / d); k1 = k + 1; temp = [(k1 * lower[0]) + upper[0], (k1 * lower[1]) + upper[1]]; upper = [(k * lower[0]) + upper[0], (k * lower[1]) + upper[1]]; lower = temp; }; } } */ int prAsFraction(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; double mediant_num, lower_num, upper_num, temp_num; double mediant_den, lower_den, upper_den, temp_den; double x, d; int k, k1; int maxDenominator; int err; bool neg = false; err = slotDoubleVal(a, &x); if (err) return err; err = slotIntVal(b, &maxDenominator); if (err) return err; bool faster = IsTrue(c); PyrObject* obj = newPyrArray(g->gc, 2, 0, true); obj->size = 2; PyrSlot* slots = obj->slots; SetObject(a, obj); if (x < 0.0) { x = -x; neg = true; } if (x == 0.0) { SetInt(slots + 0, 0); SetInt(slots + 1, 1); return errNone; } if (x < 1.0) { upper_num = 1.0; upper_den = floor(1. / x); lower_num = 1.0; lower_den = upper_den + 1.; } else { lower_num = floor(x); lower_den = 1.0; upper_num = lower_num + 1.; upper_den = 1.0; } while (true) { mediant_num = lower_num + upper_num; mediant_den = lower_den + upper_den; // post(" md %g %g %g %g %g %g\n", mediant_num, mediant_den, lower_num, lower_den, upper_num, upper_den); if (x * mediant_den > mediant_num) { d = upper_num - (x * upper_den); if (maxDenominator < mediant_den || fabs(d) < 1e-5) { if (neg) upper_num = -upper_num; SetInt(slots + 0, (int)upper_num); SetInt(slots + 1, (int)upper_den); return errNone; } lower_num = mediant_num; lower_den = mediant_den; if (faster) { k = (int)floor(((x * lower_den) - lower_num) / d); if (k < 10000) { k1 = k + 1; temp_num = lower_num + (k1 * upper_num); temp_den = lower_den + (k1 * upper_den); lower_num = lower_num + (k * upper_num); lower_den = lower_den + (k * upper_den); upper_num = temp_num; upper_den = temp_den; } } } else if (x * mediant_den == mediant_num) { if (maxDenominator >= mediant_den) { if (neg) mediant_num = -mediant_num; SetInt(slots + 0, (int)mediant_num); SetInt(slots + 1, (int)mediant_den); return errNone; } else if (lower_den < upper_den) { if (neg) lower_num = -lower_num; SetInt(slots + 0, (int)lower_num); SetInt(slots + 1, (int)lower_den); return errNone; } else { if (neg) upper_num = -upper_num; SetInt(slots + 0, (int)upper_num); SetInt(slots + 1, (int)upper_den); return errNone; } } else { d = lower_num - (x * lower_den); if (maxDenominator < mediant_den || fabs(d) < 1e-5) { if (neg) lower_num = -lower_num; SetInt(slots + 0, (int)lower_num); SetInt(slots + 1, (int)lower_den); return errNone; } upper_num = mediant_num; upper_den = mediant_den; if (faster) { k = (int)floor(((x * upper_den) - upper_num) / d); if (k < 10000) { k1 = k + 1; temp_num = (k1 * lower_num) + upper_num; temp_den = (k1 * lower_den) + upper_den; upper_num = (k * lower_num) + upper_num; upper_den = (k * lower_den) + upper_den; lower_num = temp_num; lower_den = temp_den; } } } } } int prSphericalHarmonic(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; // n (spherical order) PyrSlot* b = g->sp - 2; // m (index within the order) PyrSlot* c = g->sp - 1; // theta PyrSlot* d = g->sp; // phi int err; int n = 0; int m = 0; double theta = 0.0; double phi = 0.0; err = slotDoubleVal(d, &phi); if (err) return err; err = slotDoubleVal(c, &theta); if (err) return err; err = slotIntVal(b, &m); if (err) return err; err = slotIntVal(a, &n); if (err) return err; auto res_cmplx = boost::math::spherical_harmonic(n, m, theta, phi); PyrObject* obj = instantiateObject(gMainVMGlobals->gc, getsym("Complex")->u.classobj, 0, true, true); SetObject(a, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, res_cmplx.real()); SetFloat(slots + 1, res_cmplx.imag()); return errNone; } template <typename Arg1T, typename Arg2T, std::complex<double> BoostFunctionT(Arg1T, Arg2T)> int prBoostTwoArgRetComplex(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; Arg1T arg1 = {}; Arg2T arg2 = {}; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; err = slotVal(b, &arg2); if (err) return err; auto res_cmplx = BoostFunctionT(arg1, arg2); PyrObject* obj = instantiateObject(gMainVMGlobals->gc, getsym("Complex")->u.classobj, 0, true, true); SetObject(a, obj); PyrSlot* slots = obj->slots; SetFloat(slots + 0, res_cmplx.real()); SetFloat(slots + 1, res_cmplx.imag()); return errNone; } template <typename Arg1T, std::vector<double> BoostFunctionT(Arg1T)> int prBoostOneArgRetArray(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; Arg1T arg1; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; auto res = BoostFunctionT(arg1); PyrObject* array = newPyrArray(g->gc, res.size(), 0, true); SetObject(a, array); PyrSlot* s = array->slots; for (auto item : res) { SetFloat(s, item); ++array->size; ++s; } return errNone; } template <typename RetT, RetT BoostFunctionT(unsigned, double const&)> int prBoostCheby(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; int arg1 = 0; double arg2 = 0.0; int err = slotIntVal(a, &arg1); if (err) return err; err = slotDoubleVal(b, &arg2); if (err) return err; RetT res = BoostFunctionT(arg1, arg2); setSlotVal(a, res); return errNone; } template <typename RetT, RetT BoostFunctionT(double const&)> int prBoostsqrt1pm1(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; double arg1 = 0; int err = slotDoubleVal(a, &arg1); if (err) return err; RetT res = BoostFunctionT(arg1); setSlotVal(a, res); return errNone; } template <typename RetT, typename Arg1T, RetT BoostFunctionT(Arg1T)> int prBoostOneArg(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; Arg1T arg1; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; RetT res = BoostFunctionT(arg1); setSlotVal(a, res); return errNone; } template <typename RetT, typename Arg1T, typename Arg2T, RetT BoostFunctionT(Arg1T, Arg2T)> int prBoostTwoArg(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; Arg1T arg1 = {}; Arg2T arg2 = {}; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; err = slotVal(b, &arg2); if (err) return err; RetT res = BoostFunctionT(arg1, arg2); setSlotVal(a, res); return errNone; } template <typename RetT, typename Arg1T, typename Arg2T, typename Arg3T, RetT BoostFunctionT(Arg1T, Arg2T, Arg3T)> int prBoostThreeArg(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; Arg1T arg1 = {}; Arg2T arg2 = {}; Arg3T arg3 = {}; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; err = slotVal(b, &arg2); if (err) return err; err = slotVal(c, &arg3); if (err) return err; RetT res = BoostFunctionT(arg1, arg2, arg3); setSlotVal(a, res); return errNone; } template <typename RetT, typename Arg1T, typename Arg2T, typename Arg3T, typename Arg4T, RetT BoostFunctionT(Arg1T, Arg2T, Arg3T, Arg4T)> int prBoostFourArg(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; PyrSlot* b = g->sp - 2; PyrSlot* c = g->sp - 1; PyrSlot* d = g->sp; Arg1T arg1 = {}; Arg2T arg2 = {}; Arg3T arg3 = {}; Arg4T arg4 = {}; int err = slotVal(a, &arg1); // slotVal only unwraps/extracts numeric values if (err) return err; err = slotVal(b, &arg2); if (err) return err; err = slotVal(c, &arg3); if (err) return err; err = slotVal(d, &arg4); if (err) return err; RetT res = BoostFunctionT(arg1, arg2, arg3, arg4); setSlotVal(a, res); return errNone; } void initMathPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_AddInt", prAddInt, 2, 0); definePrimitive(base, index++, "_SubInt", prSubInt, 2, 0); definePrimitive(base, index++, "_MulInt", prMulInt, 2, 0); definePrimitive(base, index++, "_AddFloat", prAddFloat, 2, 0); definePrimitive(base, index++, "_SubFloat", prSubFloat, 2, 0); definePrimitive(base, index++, "_MulFloat", prMulFloat, 2, 0); definePrimitive(base, index++, "_NthPrime", prNthPrime, 1, 0); definePrimitive(base, index++, "_PrevPrime", prPrevPrime, 1, 0); definePrimitive(base, index++, "_NextPrime", prNextPrime, 1, 0); definePrimitive(base, index++, "_IsPrime", prIsPrime, 1, 0); definePrimitive(base, index++, "_IndexOfPrime", prIndexOfPrime, 1, 0); definePrimitive(base, index++, "_As32Bits", prAs32Bits, 1, 0); definePrimitive(base, index++, "_High32Bits", prHigh32Bits, 1, 0); definePrimitive(base, index++, "_Low32Bits", prLow32Bits, 1, 0); definePrimitive(base, index++, "_From32Bits", prFrom32Bits, 2, 0); definePrimitive(base, index++, "_From64Bits", prFrom64Bits, 3, 0); definePrimitive(base, index++, "_ClipInt", mathClipInt, 3, 0); definePrimitive(base, index++, "_ClipFloat", mathClipFloat, 3, 0); definePrimitive(base, index++, "_ClipSignal", mathClipSignal, 3, 0); definePrimitive(base, index++, "_WrapInt", mathWrapInt, 3, 0); definePrimitive(base, index++, "_WrapFloat", mathWrapFloat, 3, 0); definePrimitive(base, index++, "_WrapSignal", mathWrapSignal, 3, 0); definePrimitive(base, index++, "_FoldInt", mathFoldInt, 3, 0); definePrimitive(base, index++, "_FoldFloat", mathFoldFloat, 3, 0); definePrimitive(base, index++, "_FoldSignal", mathFoldSignal, 3, 0); definePrimitive(base, index++, "_SimpleNumberSeries", prSimpleNumberSeries, 3, 0); definePrimitive(base, index++, "_AsFraction", prAsFraction, 3, 0); // Number Series: definePrimitive(base, index++, "_BernouliB2n", prBoostOneArg<double, int, boost::math::bernoulli_b2n<double>>, 1, 0); definePrimitive(base, index++, "_TangentT2n", prBoostOneArg<double, int, boost::math::tangent_t2n<double>>, 1, 0); // Gamma: definePrimitive(base, index++, "_TGamma", prBoostOneArg<double, double, boost::math::tgamma<double>>, 1, 0); definePrimitive(base, index++, "_TGamma1pm1", prBoostOneArg<double, double, boost::math::tgamma1pm1<double>>, 1, 0); definePrimitive(base, index++, "_LGamma", prBoostOneArg<double, double, boost::math::lgamma<double>>, 1, 0); definePrimitive(base, index++, "_Digamma", prBoostOneArg<double, double, boost::math::digamma<double>>, 1, 0); definePrimitive(base, index++, "_Trigamma", prBoostOneArg<double, double, boost::math::trigamma<double>>, 1, 0); definePrimitive(base, index++, "_Polygamma", prBoostTwoArg<double, int, double, boost::math::polygamma<double>>, 2, 0); definePrimitive(base, index++, "_TGammaRatio", prBoostTwoArg<double, double, double, boost::math::tgamma_ratio<double>>, 2, 0); definePrimitive(base, index++, "_TGammaDeltaRatio", prBoostTwoArg<double, double, double, boost::math::tgamma_delta_ratio<double>>, 2, 0); // Incomplete Gamma Functions definePrimitive(base, index++, "_GammaP", prBoostTwoArg<double, double, double, boost::math::gamma_p<double>>, 2, 0); definePrimitive(base, index++, "_GammaQ", prBoostTwoArg<double, double, double, boost::math::gamma_q<double>>, 2, 0); definePrimitive(base, index++, "_TGammaLower", prBoostTwoArg<double, double, double, boost::math::tgamma_lower<double>>, 2, 0); definePrimitive(base, index++, "_TGammaI", prBoostTwoArg<double, double, double, boost::math::tgamma<double>>, 2, 0); // Incomplete Gamma Function Inverses definePrimitive(base, index++, "_GammaPInv", prBoostTwoArg<double, double, double, boost::math::gamma_p_inv<double>>, 2, 0); definePrimitive(base, index++, "_GammaQInv", prBoostTwoArg<double, double, double, boost::math::gamma_q_inv<double>>, 2, 0); definePrimitive(base, index++, "_GammaPInvA", prBoostTwoArg<double, double, double, boost::math::gamma_p_inva<double>>, 2, 0); definePrimitive(base, index++, "_GammaQInvA", prBoostTwoArg<double, double, double, boost::math::gamma_q_inva<double>>, 2, 0); // Incomplete Gamma Function Derivative definePrimitive(base, index++, "_GammaPDerivative", prBoostTwoArg<double, double, double, boost::math::gamma_p_derivative<double>>, 2, 0); // Factorials and Binomial Coefficients: definePrimitive(base, index++, "_Factorial", prBoostOneArg<double, unsigned, boost::math::factorial<double>>, 1, 0); definePrimitive(base, index++, "_DoubleFactorial", prBoostOneArg<double, unsigned int, boost::math::double_factorial<double>>, 1, 0); definePrimitive(base, index++, "_RisingFactorial", prBoostTwoArg<double, double, int, boost::math::rising_factorial<double>>, 2, 0); definePrimitive(base, index++, "_FallingFactorial", prBoostTwoArg<double, double, unsigned, boost::math::falling_factorial<double>>, 2, 0); definePrimitive(base, index++, "_BinomialCoefficient", prBoostTwoArg<double, unsigned, unsigned, boost::math::binomial_coefficient<double>>, 2, 0); // Beta Functions: definePrimitive(base, index++, "_Beta", prBoostTwoArg<double, double, double, boost::math::beta<double>>, 2, 0); // Incomplete Betas, normalized and non-normalized definePrimitive(base, index++, "_IBeta", prBoostThreeArg<double, double, double, double, boost::math::ibeta<double>>, 3, 0); definePrimitive(base, index++, "_IBetaC", prBoostThreeArg<double, double, double, double, boost::math::ibetac<double>>, 3, 0); definePrimitive(base, index++, "_BetaFull", prBoostThreeArg<double, double, double, double, boost::math::beta<double>>, 3, 0); definePrimitive(base, index++, "_BetaCFull", prBoostThreeArg<double, double, double, double, boost::math::betac<double>>, 3, 0); // Incomplete Betas, inverse definePrimitive(base, index++, "_IBetaInv", prBoostThreeArg<double, double, double, double, boost::math::ibeta_inv<double>>, 3, 0); definePrimitive(base, index++, "_IBetaCInv", prBoostThreeArg<double, double, double, double, boost::math::ibetac_inv<double>>, 3, 0); definePrimitive(base, index++, "_IBetaInvA", prBoostThreeArg<double, double, double, double, boost::math::ibeta_inva<double>>, 3, 0); definePrimitive(base, index++, "_IBetaCInvA", prBoostThreeArg<double, double, double, double, boost::math::ibetac_inva<double>>, 3, 0); definePrimitive(base, index++, "_IBetaInvB", prBoostThreeArg<double, double, double, double, boost::math::ibeta_invb<double>>, 3, 0); definePrimitive(base, index++, "_IBetaCInvB", prBoostThreeArg<double, double, double, double, boost::math::ibetac_invb<double>>, 3, 0); // Incomplete Betas, derivative definePrimitive(base, index++, "_IBetaDerivative", prBoostThreeArg<double, double, double, double, boost::math::ibeta_derivative<double>>, 3, 0); // Error functions: definePrimitive(base, index++, "_Erf", prBoostOneArg<double, double, boost::math::erf<double>>, 1, 0); definePrimitive(base, index++, "_ErfC", prBoostOneArg<double, double, boost::math::erfc<double>>, 1, 0); definePrimitive(base, index++, "_ErfInv", prBoostOneArg<double, double, boost::math::erf_inv<double>>, 1, 0); definePrimitive(base, index++, "_ErfCInv", prBoostOneArg<double, double, boost::math::erfc_inv<double>>, 1, 0); // Polynomials: // Legendre (and Associated) definePrimitive(base, index++, "_LegendreP", prBoostTwoArg<double, int, double, boost::math::legendre_p<double>>, 2, 0); definePrimitive(base, index++, "_LegendrePPrime", prBoostTwoArg<double, int, double, boost::math::legendre_p_prime<double>>, 2, 0); definePrimitive(base, index++, "_LegendrePZeros", prBoostOneArgRetArray<int, boost::math::legendre_p_zeros<double>>, 1, 0); // TODO: generalize return array form? definePrimitive(base, index++, "_LegendrePAssoc", prBoostThreeArg<double, int, int, double, boost::math::legendre_p<double>>, 3, 0); definePrimitive(base, index++, "_LegendreQ", prBoostTwoArg<double, unsigned, double, boost::math::legendre_q<double>>, 2, 0); // Laguerre (and Associated) definePrimitive(base, index++, "_Laguerre", prBoostTwoArg<double, unsigned, double, boost::math::laguerre<double>>, 2, 0); definePrimitive(base, index++, "_LaguerreAssoc", prBoostThreeArg<double, unsigned, double, double, boost::math::laguerre<double>>, 3, 0); // Hermite definePrimitive(base, index++, "_Hermite", prBoostTwoArg<double, unsigned, double, boost::math::hermite<double>>, 2, 0); // Chebyshev definePrimitive(base, index++, "_ChebyshevT", prBoostCheby<double, boost::math::chebyshev_t<double>>, 2, 0); definePrimitive(base, index++, "_ChebyshevU", prBoostCheby<double, boost::math::chebyshev_u<double>>, 2, 0); definePrimitive(base, index++, "_ChebyshevTPrime", prBoostCheby<double, boost::math::chebyshev_t_prime<double>>, 2, 0); // Spherical Harmonics definePrimitive(base, index++, "_SphericalHarmonic", prSphericalHarmonic, 4, 0); definePrimitive(base, index++, "_SphericalHarmonicR", prBoostFourArg<double, unsigned, int, double, double, boost::math::spherical_harmonic_r<double>>, 4, 0); definePrimitive(base, index++, "_SphericalHarmonicI", prBoostFourArg<double, unsigned, int, double, double, boost::math::spherical_harmonic_i<double>>, 4, 0); // Bessel Functions: // First and Second Kinds definePrimitive(base, index++, "_CylBesselJ", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_j<double>>, 2, 0); definePrimitive(base, index++, "_CylNeumann", prBoostTwoArg<double, double, double, boost::math::cyl_neumann<double>>, 2, 0); // Zero finder definePrimitive(base, index++, "_CylBesselJZero", prBoostTwoArg<double, double, int, boost::math::cyl_bessel_j_zero<double>>, 2, 0); definePrimitive(base, index++, "_CylNeumannZero", prBoostTwoArg<double, double, int, boost::math::cyl_neumann_zero<double>>, 2, 0); // Modified, First and Second Kinds definePrimitive(base, index++, "_CylBesselI", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_i<double>>, 2, 0); definePrimitive(base, index++, "_CylBesselK", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_k<double>>, 2, 0); // Spherical, First and Second Kinds definePrimitive(base, index++, "_SphBessel", prBoostTwoArg<double, unsigned, double, boost::math::sph_bessel<double>>, 2, 0); definePrimitive(base, index++, "_SphNeumann", prBoostTwoArg<double, unsigned, double, boost::math::sph_neumann<double>>, 2, 0); // Derivatives definePrimitive(base, index++, "_CylBesselJPrime", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_j_prime<double>>, 2, 0); definePrimitive(base, index++, "_CylNeumannPrime", prBoostTwoArg<double, double, double, boost::math::cyl_neumann_prime<double>>, 2, 0); definePrimitive(base, index++, "_CylBesselIPrime", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_i_prime<double>>, 2, 0); definePrimitive(base, index++, "_CylBesselKPrime", prBoostTwoArg<double, double, double, boost::math::cyl_bessel_k_prime<double>>, 2, 0); definePrimitive(base, index++, "_SphBesselPrime", prBoostTwoArg<double, unsigned, double, boost::math::sph_bessel_prime<double>>, 2, 0); definePrimitive(base, index++, "_SphNeumannPrime", prBoostTwoArg<double, unsigned, double, boost::math::sph_neumann_prime<double>>, 2, 0); // Hankel Functions: // Cyclic definePrimitive(base, index++, "_CylHankel1", prBoostTwoArgRetComplex<double, double, boost::math::cyl_hankel_1<double>>, 2, 0); definePrimitive(base, index++, "_CylHankel2", prBoostTwoArgRetComplex<double, double, boost::math::cyl_hankel_2<double>>, 2, 0); // Spherical definePrimitive(base, index++, "_SphHankel1", prBoostTwoArgRetComplex<double, double, boost::math::sph_hankel_1<double>>, 2, 0); definePrimitive(base, index++, "_SphHankel2", prBoostTwoArgRetComplex<double, double, boost::math::sph_hankel_2<double>>, 2, 0); // Airy Functions: definePrimitive(base, index++, "_AiryAi", prBoostOneArg<double, double, boost::math::airy_ai<double>>, 1, 0); definePrimitive(base, index++, "_AiryBi", prBoostOneArg<double, double, boost::math::airy_bi<double>>, 1, 0); definePrimitive(base, index++, "_AiryAiPrime", prBoostOneArg<double, double, boost::math::airy_ai_prime<double>>, 1, 0); definePrimitive(base, index++, "_AiryBiPrime", prBoostOneArg<double, double, boost::math::airy_bi_prime<double>>, 1, 0); definePrimitive(base, index++, "_AiryAiZero", prBoostOneArg<double, int, boost::math::airy_ai_zero<double>>, 1, 0); definePrimitive(base, index++, "_AiryBiZero", prBoostOneArg<double, int, boost::math::airy_bi_zero<double>>, 1, 0); // Elliptic Integrals: // Elliptic Integrals - Carlson Form definePrimitive(base, index++, "_EllintRf", prBoostThreeArg<double, double, double, double, boost::math::ellint_rf<double>>, 3, 0); definePrimitive(base, index++, "_EllintRd", prBoostThreeArg<double, double, double, double, boost::math::ellint_rd<double>>, 3, 0); definePrimitive(base, index++, "_EllintRj", prBoostFourArg<double, double, double, double, double, boost::math::ellint_rj<double>>, 4, 0); definePrimitive(base, index++, "_EllintRc", prBoostTwoArg<double, double, double, boost::math::ellint_rc<double>>, 2, 0); definePrimitive(base, index++, "_EllintRg", prBoostThreeArg<double, double, double, double, boost::math::ellint_rg<double>>, 3, 0); // Elliptic Integrals of the First, Second, Third Kind, D - Legendre Form definePrimitive(base, index++, "_Ellint1", prBoostTwoArg<double, double, double, boost::math::ellint_1<double>>, 2, 0); definePrimitive(base, index++, "_Ellint1C", prBoostOneArg<double, double, boost::math::ellint_1<double>>, 1, 0); definePrimitive(base, index++, "_Ellint2", prBoostTwoArg<double, double, double, boost::math::ellint_2<double>>, 2, 0); definePrimitive(base, index++, "_Ellint2C", prBoostOneArg<double, double, boost::math::ellint_2<double>>, 1, 0); definePrimitive(base, index++, "_Ellint3", prBoostThreeArg<double, double, double, double, boost::math::ellint_3<double>>, 3, 0); definePrimitive(base, index++, "_Ellint3C", prBoostTwoArg<double, double, double, boost::math::ellint_3<double>>, 2, 0); definePrimitive(base, index++, "_EllintD", prBoostTwoArg<double, double, double, boost::math::ellint_d<double>>, 2, 0); definePrimitive(base, index++, "_EllintDC", prBoostOneArg<double, double, boost::math::ellint_d<double>>, 1, 0); // Jacobi Zeta, Heuman Lambda Function definePrimitive(base, index++, "_JacobiZeta", prBoostTwoArg<double, double, double, boost::math::jacobi_zeta<double>>, 2, 0); definePrimitive(base, index++, "_HeumanLambda", prBoostTwoArg<double, double, double, boost::math::heuman_lambda<double>>, 2, 0); // Jacobi Elliptic Functions: definePrimitive(base, index++, "_JacobiCd", prBoostTwoArg<double, double, double, boost::math::jacobi_cd<double>>, 2, 0); definePrimitive(base, index++, "_JacobiCn", prBoostTwoArg<double, double, double, boost::math::jacobi_cn<double>>, 2, 0); definePrimitive(base, index++, "_JacobiCs", prBoostTwoArg<double, double, double, boost::math::jacobi_cs<double>>, 2, 0); definePrimitive(base, index++, "_JacobiDc", prBoostTwoArg<double, double, double, boost::math::jacobi_dc<double>>, 2, 0); definePrimitive(base, index++, "_JacobiDn", prBoostTwoArg<double, double, double, boost::math::jacobi_dn<double>>, 2, 0); definePrimitive(base, index++, "_JacobiDs", prBoostTwoArg<double, double, double, boost::math::jacobi_ds<double>>, 2, 0); definePrimitive(base, index++, "_JacobiNc", prBoostTwoArg<double, double, double, boost::math::jacobi_nc<double>>, 2, 0); definePrimitive(base, index++, "_JacobiNd", prBoostTwoArg<double, double, double, boost::math::jacobi_nd<double>>, 2, 0); definePrimitive(base, index++, "_JacobiNs", prBoostTwoArg<double, double, double, boost::math::jacobi_ns<double>>, 2, 0); definePrimitive(base, index++, "_JacobiSc", prBoostTwoArg<double, double, double, boost::math::jacobi_sc<double>>, 2, 0); definePrimitive(base, index++, "_JacobiSd", prBoostTwoArg<double, double, double, boost::math::jacobi_sd<double>>, 2, 0); definePrimitive(base, index++, "_JacobiSn", prBoostTwoArg<double, double, double, boost::math::jacobi_sn<double>>, 2, 0); // Zeta Function: definePrimitive(base, index++, "_Zeta", prBoostOneArg<double, double, boost::math::zeta<double>>, 1, 0); // Exponential Integrals: definePrimitive(base, index++, "_ExpintEn", prBoostTwoArg<double, double, double, boost::math::expint<double>>, 2, 0); definePrimitive(base, index++, "_ExpintEi", prBoostOneArg<double, double, boost::math::expint<double>>, 1, 0); // Basic functions: definePrimitive(base, index++, "_SinPi", prBoostOneArg<double, double, boost::math::sin_pi<double>>, 1, 0); definePrimitive(base, index++, "_CosPi", prBoostOneArg<double, double, boost::math::cos_pi<double>>, 1, 0); definePrimitive(base, index++, "_Log1p", prBoostOneArg<double, double, boost::math::log1p<double>>, 1, 0); definePrimitive(base, index++, "_ExpM1", prBoostOneArg<double, double, boost::math::expm1<double>>, 1, 0); definePrimitive(base, index++, "_Cbrt", prBoostOneArg<double, double, boost::math::cbrt<double>>, 1, 0); definePrimitive(base, index++, "_Sqrt1pm1", prBoostsqrt1pm1<double, boost::math::sqrt1pm1<double>>, 1, 0); definePrimitive(base, index++, "_PowM1", prBoostTwoArg<double, double, double, boost::math::powm1<double>>, 2, 0); definePrimitive(base, index++, "_Hypot2", prBoostTwoArg<double, double, double, boost::math::hypot<double>>, 2, 0); // Sinus Cardinal and Hyperbolic Sinus Cardinal Functions: definePrimitive(base, index++, "_SincPi", prBoostOneArg<double, double, boost::math::sinc_pi<double>>, 1, 0); definePrimitive(base, index++, "_SinhcPi", prBoostOneArg<double, double, boost::math::sinhc_pi<double>>, 1, 0); // Inverse Hyperbolic Functions: definePrimitive(base, index++, "_Asinh", prBoostOneArg<double, double, boost::math::asinh<double>>, 1, 0); definePrimitive(base, index++, "_Acosh", prBoostOneArg<double, double, boost::math::acosh<double>>, 1, 0); definePrimitive(base, index++, "_Atanh", prBoostOneArg<double, double, boost::math::atanh<double>>, 1, 0); // Owen's T function: definePrimitive(base, index++, "_OwensT", prBoostTwoArg<double, double, double, boost::math::owens_t<double>>, 2, 0); }
54,697
C++
.cpp
1,403
30.71846
120
0.577463
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
29,864
SC_AudioDevicePrim.cpp
supercollider_supercollider/lang/LangPrimSource/SC_AudioDevicePrim.cpp
/* 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 defined(SC_AUDIO_API_COREAUDIO) # include <CoreAudio/AudioHardware.h> #elif defined(SC_AUDIO_API_PORTAUDIO) # include "portaudio.h" # include "SC_PaUtils.hpp" #endif #include "SCBase.h" #include "VMGlobals.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "GC.h" enum { OUT = 0, IN, BOTH }; #if defined(SC_AUDIO_API_COREAUDIO) int listDevices(VMGlobals* g, int type) { int numDevices, num = 0; PyrSlot* a = g->sp - 2; AudioObjectPropertyAddress propertyAddress; propertyAddress.mSelector = kAudioHardwarePropertyDevices; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; // unsigned long count; UInt32 count; // OSStatus err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &count, 0); OSStatus err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count); AudioDeviceID* devices = (AudioDeviceID*)malloc(count); // err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &count, devices); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count, devices); if (err != kAudioHardwareNoError) { free(devices); return 0; } numDevices = count / sizeof(AudioDeviceID); int i; if (type < BOTH) { if (type < IN) { propertyAddress.mScope = kAudioDevicePropertyScopeOutput; } else { propertyAddress.mScope = kAudioDevicePropertyScopeInput; } for (i = 0; i < numDevices; i++) { Boolean writeable; propertyAddress.mSelector = kAudioDevicePropertyStreams; // err = AudioDeviceGetPropertyInfo(devices[i], 0, type, kAudioDevicePropertyStreams, &count, &writeable); err = AudioObjectGetPropertyDataSize(devices[i], &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { free(devices); return 0; } err = AudioObjectIsPropertySettable(devices[i], &propertyAddress, &writeable); if (err != kAudioHardwareNoError) { free(devices); return 0; } if (!count) devices[i] = 0; else num++; } } else num = numDevices; PyrObject* devArray = newPyrArray(g->gc, num * sizeof(PyrObject), 0, true); SetObject(a, devArray); // this is okay here as we don't use the receiver below int j = 0; for (i = 0; i < numDevices; i++) { if (!devices[i]) continue; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mSelector = kAudioDevicePropertyDeviceName; // err = AudioDeviceGetPropertyInfo(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, 0); err = AudioObjectGetPropertyDataSize(devices[i], &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { break; } char* name = (char*)malloc(count); // err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, name); err = AudioObjectGetPropertyData(devices[i], &propertyAddress, 0, NULL, &count, name); if (err != kAudioHardwareNoError) { free(name); break; } PyrString* string = newPyrString(g->gc, name, 0, true); SetObject(devArray->slots + j, string); devArray->size++; g->gc->GCWriteNew(devArray, (PyrObject*)string); // we know array is white so we can use GCWriteNew free(name); j++; } free(devices); return 1; } #elif defined(SC_AUDIO_API_PORTAUDIO) int listDevices(VMGlobals* g, int type) { if (Pa_Initialize() != paNoError) return 0; auto numDevices = Pa_GetDeviceCount(); if (numDevices < 0) { Pa_Terminate(); return 0; } std::vector<const PaDeviceInfo*> deviceInfos; for (PaDeviceIndex i = 0; i < numDevices; i++) { auto* pdi = Pa_GetDeviceInfo(i); if (type == IN) { if (pdi->maxInputChannels > 0) deviceInfos.push_back(pdi); } else if (type == OUT) { if (pdi->maxOutputChannels > 0) deviceInfos.push_back(pdi); } else deviceInfos.push_back(pdi); } PyrObject* devArray = newPyrArray(g->gc, deviceInfos.size() * sizeof(PyrObject), 0, true); SetObject(g->sp - 2, devArray); // this is okay here as we don't use the receiver below devArray->size = deviceInfos.size(); for (int i = 0; i < deviceInfos.size(); i++) { PyrString* string = newPyrString(g->gc, GetPaDeviceName(deviceInfos[i]).c_str(), 0, true); SetObject(devArray->slots + i, string); g->gc->GCWriteNew(devArray, reinterpret_cast<PyrObject*>(string)); // we know array is white so we can use GCWriteNew } Pa_Terminate(); return 1; } #else int listDevices(VMGlobals* g, int type) { return 0; // listing devices fails when using neither CoreAudio nor PortAudio } #endif int prListAudioDevices(VMGlobals* g, int numArgsPushed) { int in = 0; int out = 0; slotIntVal(g->sp, &out); slotIntVal(g->sp - 1, &in); int type; if (in && out) type = BOTH; else if (in) type = IN; else type = OUT; if (listDevices(g, type)) return errNone; return errFailed; } void initAudioDevicePrimitives() { definePrimitive(nextPrimitiveIndex(), 0, "_ListAudioDevices", prListAudioDevices, 3, 0); }
6,568
C++
.cpp
163
33.06135
118
0.651798
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
29,865
SC_HID_api.cpp
supercollider_supercollider/lang/LangPrimSource/SC_HID_api.cpp
/* HIDAPI based HID support. Copyright (c) 2013 Marije Baalman, 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 */ #include "SCBase.h" #include "VMGlobals.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSched.h" #include "GC.h" #include <atomic> #include <cstring> #include "SC_LanguageClient.h" extern bool compiledOK; #ifdef HAVE_HIDAPI # if 1 static inline void trace(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vpost(fmt, ap); va_end(ap); } # else static inline void trace(...) {} # endif // needed for string conversions # include <wchar.h> # include <cstdlib> # include <hidapi.h> # include <hidapi_parser.h> # include <map> typedef std::map<int, hid_dev_desc*> hid_map_t; // helper function to convert from unicode to ansi char* wchar_to_char(wchar_t* wchs) { if (wchs == nullptr) return nullptr; int len = wcslen(wchs) + 1; char* chs = (char*)malloc(sizeof(char) * len); std::wcstombs(chs, wchs, len); return chs; } wchar_t* char_to_wchar(char* chs) { if (chs == nullptr) return nullptr; int len = std::strlen(chs) + 1; wchar_t* wchs = (wchar_t*)malloc(sizeof(wchar_t) * len); std::mbstowcs(wchs, chs, len); return wchs; } static PyrSymbol* s_hidapi = nullptr; static PyrSymbol* s_hidElementData = nullptr; static PyrSymbol* s_hidDeviceData = nullptr; static PyrSymbol* s_hidClosed = nullptr; class SC_HID_API_Threadpool { typedef std::map<hid_dev_desc*, std::thread> ThreadMap; public: void openDevice(hid_dev_desc* desc, std::atomic<bool>& shouldBeRunning) { trace("open device %p\n"); std::lock_guard<std::mutex> lock(guard); if (map.find(desc) != map.end()) // thread already polling device return; std::thread deviceThread([=, &shouldBeRunning] { trace("start polling thread for %d\n", desc); while (true) { unsigned char buf[256]; int res = hid_read_timeout(desc->device, buf, sizeof(buf), 250); if (res > 0) { hid_parse_input_report(buf, res, desc); } else if (res == -1) { trace("device thread interrupted \n"); hid_throw_readerror(desc); trace("device thread closed device \n"); return; } } std::lock_guard<std::mutex> lock_(guard); auto it = map.find(desc); std::thread thisThread = std::move(it->second); map.erase(it); thisThread.detach(); }); map.emplace(desc, std::move(deviceThread)); } void closeDevice(hid_dev_desc* desc) { std::thread thread; { std::lock_guard<std::mutex> lock(guard); auto it = map.find(desc); if (it == map.end()) { std::printf("device already closed %p\n", desc->device); return; } thread = std::move(it->second); } thread.detach(); hid_close_device(desc); trace("close device: interrupted \n"); } private: ThreadMap map; std::mutex guard; }; struct SC_HID_APIManager { public: static SC_HID_APIManager& instance(); int init(); int closeAll(); int build_devicelist(); int free_devicelist(); int open_device_path(const char* path, int vendor, int product); int open_device(int vendor, int product, char* serial_number = nullptr); int close_device(int joy_idx); void close_all_devices(); struct hid_dev_desc* get_device(int joy_idx); void setPyrObject(PyrObject* obj); SC_HID_APIManager(); ~SC_HID_APIManager(); int initialize_hidapi(); void elementData(int, struct hid_device_element*); void deviceData(int, struct hid_dev_desc*); void deviceRepetitiveReadError(int, struct hid_dev_desc*); struct hid_device_info* devinfos; protected: void handleDevice(int, struct hid_dev_desc*, std::atomic<bool> const& shouldBeRunning); void handleElement(int, struct hid_device_element*, std::atomic<bool> const& shouldBeRunning); void deviceClosed(int, struct hid_dev_desc*, std::atomic<bool> const& shouldBeRunning); private: hid_map_t hiddevices; // declares a vector of hiddevices int number_of_hids; // language interface PyrObject* m_obj; std::atomic<bool> m_running; std::atomic<bool> mShouldBeRunning; SC_HID_API_Threadpool mThreads; }; static void hid_element_cb(struct hid_device_element* el, void* data) { SC_HID_APIManager::instance().elementData(*((int*)data), el); } static void hid_descriptor_cb(struct hid_dev_desc* dd, void* data) { SC_HID_APIManager::instance().deviceData(*((int*)data), dd); } void hid_readerror_cb(hid_dev_desc* dd, void* data) { SC_HID_APIManager::instance().deviceRepetitiveReadError(*((int*)data), dd); } void SC_HID_APIManager::deviceData(int id, struct hid_dev_desc* dd) { handleDevice(id, dd, mShouldBeRunning); } void SC_HID_APIManager::elementData(int id, struct hid_device_element* ele) { handleElement(id, ele, mShouldBeRunning); } void SC_HID_APIManager::deviceRepetitiveReadError(int id, struct hid_dev_desc* dd) { deviceClosed(id, dd, mShouldBeRunning); // hiddevices.erase( id ); } void SC_HID_APIManager::setPyrObject(PyrObject* obj) { m_obj = obj; } void SC_HID_APIManager::close_all_devices() { for (auto elem : hiddevices) mThreads.closeDevice(elem.second); hiddevices.clear(); } int SC_HID_APIManager::open_device_path(const char* path, int vendor, int product) { // struct hid_dev_desc* newdevdesc; newdevdesc = hid_open_device_path(path, vendor, product); if (!newdevdesc) { post("HIDAPI : Unable to open device %s: %d, %d\n", path, vendor, product); return -1; } else { hiddevices.insert(std::pair<int, hid_dev_desc*>(number_of_hids, newdevdesc)); newdevdesc->index = number_of_hids; hid_set_descriptor_callback(newdevdesc, (hid_descriptor_callback)hid_descriptor_cb, &newdevdesc->index); hid_set_readerror_callback(newdevdesc, (hid_device_readerror_callback)hid_readerror_cb, &newdevdesc->index); hid_set_element_callback(newdevdesc, (hid_element_callback)hid_element_cb, &newdevdesc->index); number_of_hids++; mThreads.openDevice(newdevdesc, mShouldBeRunning); return newdevdesc->index; } } int SC_HID_APIManager::open_device(int vendor, int product, char* serial_number) { // struct hid_dev_desc* newdevdesc; if (serial_number != nullptr) { wchar_t* serialW = char_to_wchar(serial_number); newdevdesc = hid_open_device(vendor, product, serialW); free(serialW); } else { newdevdesc = hid_open_device(vendor, product, nullptr); } if (!newdevdesc) { post("HIDAPI: Unable to open device %d, %d %s\n", vendor, product, serial_number); return -1; } else { hiddevices.insert(std::pair<int, hid_dev_desc*>(number_of_hids, newdevdesc)); newdevdesc->index = number_of_hids; hid_set_descriptor_callback(newdevdesc, (hid_descriptor_callback)hid_descriptor_cb, &newdevdesc->index); hid_set_readerror_callback(newdevdesc, (hid_device_readerror_callback)hid_readerror_cb, &newdevdesc->index); hid_set_element_callback(newdevdesc, (hid_element_callback)hid_element_cb, &newdevdesc->index); number_of_hids++; mThreads.openDevice(newdevdesc, mShouldBeRunning); return newdevdesc->index; } } int SC_HID_APIManager::close_device(int joy_idx) { struct hid_dev_desc* hidtoclose = get_device(joy_idx); if (hidtoclose == nullptr) { post("HIDAPI: could not find device to close %d\n", joy_idx); return 1; // not a fatal error } else { mThreads.closeDevice(hidtoclose); hiddevices.erase(joy_idx); } return 1; } struct hid_dev_desc* SC_HID_APIManager::get_device(int joy_idx) { auto iterator = hiddevices.find(joy_idx); if (iterator == hiddevices.end()) { post("HIDAPI : device was not open %d\n", joy_idx); return nullptr; } return hiddevices.find(joy_idx)->second; } SC_HID_APIManager& SC_HID_APIManager::instance() { static SC_HID_APIManager instance; return instance; } SC_HID_APIManager::SC_HID_APIManager(): m_running(false) { number_of_hids = 0; } SC_HID_APIManager::~SC_HID_APIManager() { close_all_devices(); } int SC_HID_APIManager::init() { number_of_hids = 0; mShouldBeRunning = true; if (!m_running) initialize_hidapi(); return m_running ? errNone : errFailed; } int SC_HID_APIManager::closeAll() { m_running = false; mShouldBeRunning = false; close_all_devices(); return errNone; } int SC_HID_APIManager::initialize_hidapi() { m_running = false; if (hid_init()) { post("Unable to initialize hidapi\n"); return errFailed; } m_running = true; return errNone; } int SC_HID_APIManager::build_devicelist() { struct hid_device_info* cur_dev; devinfos = hid_enumerate(0x0, 0x0); cur_dev = devinfos; int count = 0; while (cur_dev) { count++; cur_dev = cur_dev->next; } return count; } int SC_HID_APIManager::free_devicelist() { hid_free_enumeration(devinfos); devinfos = nullptr; return errNone; } void SC_HID_APIManager::deviceClosed(int joy_idx, struct hid_dev_desc* dd, std::atomic<bool> const& shouldBeRunning) { int status = lockLanguageOrQuit(shouldBeRunning); if (status == EINTR) return; if (status) { trace("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = false; ++g->sp; SetObject(g->sp, s_hidapi->u.classobj); // set the class HID_API ++g->sp; SetInt(g->sp, joy_idx); runInterpreter(g, s_hidClosed, 2); g->canCallOS = false; } gLangMutex.unlock(); } void SC_HID_APIManager::handleElement(int joy_idx, struct hid_device_element* ele, std::atomic<bool> const& shouldBeRunning) { int status = lockLanguageOrQuit(shouldBeRunning); if (status == EINTR) return; if (status) { postfl("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = false; ++g->sp; SetObject(g->sp, s_hidapi->u.classobj); // set the class HID_API ++g->sp; SetInt(g->sp, joy_idx); ++g->sp; SetInt(g->sp, ele->index); ++g->sp; SetInt(g->sp, ele->usage_page); ++g->sp; SetInt(g->sp, ele->usage); ++g->sp; SetInt(g->sp, ele->value); ++g->sp; SetFloat(g->sp, hid_element_map_logical(ele)); ++g->sp; SetFloat(g->sp, hid_element_map_physical(ele)); ++g->sp; SetInt(g->sp, ele->array_value); runInterpreter(g, s_hidElementData, 9); g->canCallOS = false; } gLangMutex.unlock(); } void SC_HID_APIManager::handleDevice(int joy_idx, struct hid_dev_desc* devd, std::atomic<bool> const& shouldBeRunning) { int status = lockLanguageOrQuit(shouldBeRunning); if (status == EINTR) return; if (status) { postfl("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = false; ++g->sp; SetObject(g->sp, s_hidapi->u.classobj); // set the class HID_API ++g->sp; SetInt(g->sp, joy_idx); ++g->sp; SetInt(g->sp, devd->device_collection->num_elements); runInterpreter(g, s_hidDeviceData, 3); g->canCallOS = false; } gLangMutex.unlock(); } // ---------- primitive calls: --------------- int prHID_API_Initialize(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; SC_HID_APIManager::instance().setPyrObject(slotRawObject(self)); // initialize HID_APIManager return SC_HID_APIManager::instance().init(); } int prHID_API_CloseAll(VMGlobals* g, int numArgsPushed) { // close all devices, and cleanup manager return SC_HID_APIManager::instance().closeAll(); } int prHID_API_BuildDeviceList(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; // no arguments const char emptyString[] = ""; // iterate over available devices and return info to language to populate the list there int result = SC_HID_APIManager::instance().build_devicelist(); if (result > 0) { PyrObject* allDevsArray = newPyrArray(g->gc, result * sizeof(PyrObject), 0, true); SetObject(self, allDevsArray); // this is okay here as we don't use the receiver struct hid_device_info* cur_dev = SC_HID_APIManager::instance().devinfos; while (cur_dev) { PyrObject* devInfo = newPyrArray(g->gc, 11 * sizeof(PyrObject), 0, true); SetObject(allDevsArray->slots + allDevsArray->size++, devInfo); g->gc->GCWriteNew(allDevsArray, devInfo); // we know devInfo is white so we can use GCWriteNew SetInt(devInfo->slots + devInfo->size++, cur_dev->vendor_id); SetInt(devInfo->slots + devInfo->size++, cur_dev->product_id); PyrString* dev_path_name = newPyrString(g->gc, cur_dev->path, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_path_name); g->gc->GCWriteNew(devInfo, dev_path_name); // we know dev_path_name is white so we can use GCWriteNew const char* mystring; if (cur_dev->serial_number != nullptr) mystring = wchar_to_char(cur_dev->serial_number); else mystring = emptyString; PyrString* dev_serial = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_serial); g->gc->GCWriteNew(devInfo, dev_serial); // we know dev_serial is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); if (cur_dev->manufacturer_string != nullptr) mystring = wchar_to_char(cur_dev->manufacturer_string); else mystring = emptyString; PyrString* dev_man_name = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_man_name); g->gc->GCWriteNew(devInfo, dev_man_name); // we know dev_man_name is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); if (cur_dev->product_string != nullptr) mystring = wchar_to_char(cur_dev->product_string); else mystring = emptyString; PyrString* dev_prod_name = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_prod_name); g->gc->GCWriteNew(devInfo, dev_prod_name); // we know dev_prod_name is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); SetInt(devInfo->slots + devInfo->size++, cur_dev->release_number); SetInt(devInfo->slots + devInfo->size++, cur_dev->interface_number); SetInt(devInfo->slots + devInfo->size++, cur_dev->usage_page); SetInt(devInfo->slots + devInfo->size++, cur_dev->usage); cur_dev = cur_dev->next; } SC_HID_APIManager::instance().free_devicelist(); } else { // send back info that no devices were found, or empty array SetInt(self, 0); } return errNone; } int prHID_API_Open(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg1 = args + 1; PyrSlot* arg2 = args + 2; PyrSlot* arg3 = args + 3; int err; char path[256]; int vendorid; int productid; // char serial_number[256]; // could also use serial_number as specification to open device, but this is not // working yet err = slotIntVal(arg1, &vendorid); if (err != errNone) return err; err = slotIntVal(arg2, &productid); if (err != errNone) return err; int result; err = slotStrVal(arg3, path, sizeof(path)); if (err) return err; result = SC_HID_APIManager::instance().open_device_path(path, vendorid, productid); /* // could also use serial_number as specification to open device, but this is not working yet if ( NotNil( arg3 ) ){ err = slotStrVal(arg3, serial_number, sizeof(serial_number)); if (err) return err; // open device result = SC_HID_APIManager::instance().open_device( vendorid, productid, serial_number ); } else { // open device result = SC_HID_APIManager::instance().open_device( vendorid, productid, NULL ); } */ SetInt(self, result); return errNone; } int prHID_API_Close(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg = args + 1; int err; int joyid; err = slotIntVal(arg, &joyid); if (err != errNone) return err; int result = SC_HID_APIManager::instance().close_device(joyid); SetInt(self, result); return errNone; } int prHID_API_GetInfo(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg = args + 1; int err; int joyid; err = slotIntVal(arg, &joyid); if (err != errNone) return err; const char emptyString[] = ""; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_info* cur_dev = devdesc->info; if (cur_dev != nullptr) { PyrObject* devInfo = newPyrArray(g->gc, 9 * sizeof(PyrObject), 0, true); SetObject(self, devInfo); SetInt(devInfo->slots + devInfo->size++, cur_dev->vendor_id); SetInt(devInfo->slots + devInfo->size++, cur_dev->product_id); PyrString* dev_path_name = newPyrString(g->gc, cur_dev->path, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_path_name); g->gc->GCWriteNew(devInfo, dev_path_name); // we know dev_path_name is white so we can use GCWriteNew const char* mystring; if (cur_dev->serial_number != nullptr) { mystring = wchar_to_char(cur_dev->serial_number); } else { mystring = emptyString; } PyrString* dev_serial = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_serial); g->gc->GCWriteNew(devInfo, dev_serial); // we know dev_serial is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); if (cur_dev->manufacturer_string != nullptr) { mystring = wchar_to_char(cur_dev->manufacturer_string); } else { mystring = emptyString; } PyrString* dev_man_name = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_man_name); g->gc->GCWriteNew(devInfo, dev_man_name); // we know dev_man_name is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); if (cur_dev->product_string != nullptr) { mystring = wchar_to_char(cur_dev->product_string); } else { mystring = emptyString; } PyrString* dev_prod_name = newPyrString(g->gc, mystring, 0, true); SetObject(devInfo->slots + devInfo->size++, dev_prod_name); g->gc->GCWriteNew(devInfo, dev_prod_name); // we know dev_prod_name is white so we can use GCWriteNew if (mystring != emptyString) free((void*)mystring); SetInt(devInfo->slots + devInfo->size++, cur_dev->release_number); SetInt(devInfo->slots + devInfo->size++, cur_dev->interface_number); } else { SetInt(self, 0); } return errNone; } int prHID_API_GetNumberOfCollections(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg = args + 1; int err; int joyid; err = slotIntVal(arg, &joyid); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* cur_dev = devdesc->device_collection; if (cur_dev != nullptr) { SetInt(self, cur_dev->num_collections); } else { SetInt(self, 0); } return errNone; } int prHID_API_GetCollectionInfo(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg1 = args + 1; PyrSlot* arg2 = args + 2; int err; int joyid; int collectionid; err = slotIntVal(arg1, &joyid); if (err != errNone) return err; err = slotIntVal(arg2, &collectionid); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* curdev = devdesc->device_collection; struct hid_device_collection* curcollection = curdev->first_collection; struct hid_device_collection* thiscollection = nullptr; bool found = curcollection->index == collectionid; if (found) { thiscollection = curcollection; } while (curcollection != nullptr && !found) { found = curcollection->index == collectionid; if (found) { thiscollection = curcollection; } curcollection = curcollection->next_collection; } if (thiscollection != nullptr) { PyrObject* elInfo = newPyrArray(g->gc, 9 * sizeof(PyrObject), 0, true); SetObject(self, elInfo); SetInt(elInfo->slots + elInfo->size++, thiscollection->index); SetInt(elInfo->slots + elInfo->size++, thiscollection->type); SetInt(elInfo->slots + elInfo->size++, thiscollection->usage_page); SetInt(elInfo->slots + elInfo->size++, thiscollection->usage_index); if (thiscollection->parent_collection != nullptr) { SetInt(elInfo->slots + elInfo->size++, thiscollection->parent_collection->index); } else { SetInt(elInfo->slots + elInfo->size++, -2); } SetInt(elInfo->slots + elInfo->size++, thiscollection->num_collections); if (thiscollection->first_collection != nullptr) { SetInt(elInfo->slots + elInfo->size++, thiscollection->first_collection->index); } else { SetInt(elInfo->slots + elInfo->size++, -1); } SetInt(elInfo->slots + elInfo->size++, thiscollection->num_elements); if (thiscollection->first_element != nullptr) { SetInt(elInfo->slots + elInfo->size++, thiscollection->first_element->index); } else { SetInt(elInfo->slots + elInfo->size++, -1); } } else { SetInt(self, 0); } return errNone; } int prHID_API_GetNumberOfElements(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg = args + 1; int err; int joyid; err = slotIntVal(arg, &joyid); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* cur_dev = devdesc->device_collection; if (cur_dev != nullptr) { SetInt(self, cur_dev->num_elements); } else { SetInt(self, 0); } return errNone; } int prHID_API_GetElementInfo(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* self = args + 0; PyrSlot* arg1 = args + 1; PyrSlot* arg2 = args + 2; int err; int joyid; int elementid; err = slotIntVal(arg1, &joyid); if (err != errNone) return err; err = slotIntVal(arg2, &elementid); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* curdev = devdesc->device_collection; struct hid_device_element* curelement = curdev->first_element; struct hid_device_element* thiselement = nullptr; bool found = curelement->index == elementid; if (found) { thiselement = curelement; } while (curelement != nullptr && !found) { found = curelement->index == elementid; if (found) { thiselement = curelement; } curelement = curelement->next; } if (thiselement != nullptr) { PyrObject* elInfo = newPyrArray(g->gc, 18 * sizeof(PyrObject), 0, true); SetObject(self, elInfo); SetInt(elInfo->slots + elInfo->size++, thiselement->index); SetInt(elInfo->slots + elInfo->size++, thiselement->io_type); SetInt(elInfo->slots + elInfo->size++, thiselement->type); SetInt(elInfo->slots + elInfo->size++, thiselement->usage_page); SetInt(elInfo->slots + elInfo->size++, thiselement->usage); SetInt(elInfo->slots + elInfo->size++, thiselement->usage_min); SetInt(elInfo->slots + elInfo->size++, thiselement->usage_max); SetInt(elInfo->slots + elInfo->size++, thiselement->logical_min); SetInt(elInfo->slots + elInfo->size++, thiselement->logical_max); SetInt(elInfo->slots + elInfo->size++, thiselement->phys_min); SetInt(elInfo->slots + elInfo->size++, thiselement->phys_max); SetInt(elInfo->slots + elInfo->size++, thiselement->unit_exponent); SetInt(elInfo->slots + elInfo->size++, thiselement->unit); SetInt(elInfo->slots + elInfo->size++, thiselement->report_size); SetInt(elInfo->slots + elInfo->size++, thiselement->report_id); SetInt(elInfo->slots + elInfo->size++, thiselement->report_index); SetInt(elInfo->slots + elInfo->size++, thiselement->value); SetInt(elInfo->slots + elInfo->size++, thiselement->parent_collection->index); } else { SetInt(self, 0); } return errNone; } int prHID_API_SetElementOutput(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* joyIdSlot = args + 1; PyrSlot* elementIdSlot = args + 2; PyrSlot* valueSlot = args + 3; int err; int joyid; int elementid; int value; err = slotIntVal(joyIdSlot, &joyid); if (err != errNone) return err; err = slotIntVal(elementIdSlot, &elementid); if (err != errNone) return err; err = slotIntVal(valueSlot, &value); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* curdev = devdesc->device_collection; struct hid_device_element* curelement = curdev->first_element; struct hid_device_element* thiselement = nullptr; if (devdesc != nullptr) { bool found = false; while (curelement != nullptr && !found) { found = (curelement->index == elementid) && (curelement->io_type == 2); if (found) { thiselement = curelement; } curelement = hid_get_next_output_element(curelement); } if (thiselement != nullptr) { thiselement->value = value; hid_send_output_report(devdesc, thiselement->report_id); } } return errNone; } int prHID_API_SetElementRepeat(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - numArgsPushed + 1; PyrSlot* joyIdSlot = args + 1; PyrSlot* elementIdSlot = args + 2; PyrSlot* valueSlot = args + 3; int err; int joyid; int elementid; int value; err = slotIntVal(joyIdSlot, &joyid); if (err != errNone) return err; err = slotIntVal(elementIdSlot, &elementid); if (err != errNone) return err; err = slotIntVal(valueSlot, &value); if (err != errNone) return err; struct hid_dev_desc* devdesc = SC_HID_APIManager::instance().get_device(joyid); struct hid_device_collection* curdev = devdesc->device_collection; struct hid_device_element* curelement = curdev->first_element; struct hid_device_element* thiselement = nullptr; if (devdesc != nullptr) { bool found = false; while (curelement != nullptr && !found) { found = (curelement->index == elementid) && (curelement->io_type == 1); if (found) { thiselement = curelement; } curelement = hid_get_next_input_element(curelement); } if (thiselement != nullptr) { thiselement->repeat = value; } } return errNone; } void close_HID_API_Devices() { SC_HID_APIManager::instance().closeAll(); } void initHIDAPIPrimitives() { int base, index; close_HID_API_Devices(); s_hidapi = getsym("HID"); base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_HID_API_Initialize", prHID_API_Initialize, 1, 0); // this initializes the hid subsystem definePrimitive(base, index++, "_HID_API_CloseAll", prHID_API_CloseAll, 1, 0); // this also cleans up and closes devices definePrimitive(base, index++, "_HID_API_BuildDeviceList", prHID_API_BuildDeviceList, 1, 0); // this gets device info about the various devices that are attached definePrimitive(base, index++, "_HID_API_OpenDevice", prHID_API_Open, 3, 0); // opens a specific device definePrimitive(base, index++, "_HID_API_CloseDevice", prHID_API_Close, 2, 0); // closes a specific device definePrimitive(base, index++, "_HID_API_GetInfo", prHID_API_GetInfo, 2, 0); // gets info about a specific device definePrimitive(base, index++, "_HID_API_GetNumberOfCollections", prHID_API_GetNumberOfCollections, 2, 0); // gets number of elements of a device definePrimitive(base, index++, "_HID_API_GetCollectionInfo", prHID_API_GetCollectionInfo, 3, 0); // gets info about a specific device element definePrimitive(base, index++, "_HID_API_GetNumberOfElements", prHID_API_GetNumberOfElements, 2, 0); // gets number of elements of a device definePrimitive(base, index++, "_HID_API_GetElementInfo", prHID_API_GetElementInfo, 4, 0); // gets info about a specific device element definePrimitive(base, index++, "_HID_API_SetElementOutput", prHID_API_SetElementOutput, 3, 0); // sets the output value of a specific device element, and sends the report definePrimitive(base, index++, "_HID_API_SetElementRepeat", prHID_API_SetElementRepeat, 3, 0); // sets the repeat property of a specific device element s_hidElementData = getsym("prHIDElementData"); // send back element data s_hidDeviceData = getsym("prHIDDeviceData"); // send back device data s_hidClosed = getsym("prHIDDeviceClosed"); // send back that device was closed } void deinitHIDAPIPrimitives() { SC_HID_APIManager::instance().closeAll(); } #else // no HID API void initHIDAPIPrimitives() { // other platforms? } void deinitHIDAPIPrimitives() {} #endif /// HAVE_API_HID // EOF
32,932
C++
.cpp
807
33.775713
120
0.633871
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
29,866
SC_PortMIDI.cpp
supercollider_supercollider/lang/LangPrimSource/SC_PortMIDI.cpp
/* 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 */ /* changes by jan trutzschler v. f. 9/9/2002 the midiReadProc calls doAction in the class MIDIIn. with the arguments: inUid, status, chan, val1, val2 added prDisposeMIDIClient added prRestartMIDI 19/9 call different actions,disconnect midiInPort, midiout: sendmidi 04/feb/03 prListMIDIEndpoints modification by Ron Kuivila added jt. */ #include "PortMIDI.h" #include "PortTime.h" #include "SCBase.h" #include "VMGlobals.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSched.h" #include "GC.h" #include "SC_Lock.h" #include <map> #include <cstring> #include <vector> using std::memset; // symbols to call back into lang PyrSymbol* s_domidiaction; PyrSymbol* s_midiNoteOnAction; PyrSymbol* s_midiNoteOffAction; PyrSymbol* s_midiTouchAction; PyrSymbol* s_midiControlAction; PyrSymbol* s_midiPolyTouchAction; PyrSymbol* s_midiProgramAction; PyrSymbol* s_midiBendAction; PyrSymbol* s_midiSysexAction; PyrSymbol* s_midiInvalidSysexAction; PyrSymbol* s_midiSysrtAction; PyrSymbol* s_midiSMPTEAction; PyrSymbol* s_midiin; PyrSymbol* s_numMIDIDev; PyrSymbol* s_midiclient; const int kMaxMidiPorts = 128; int gNumMIDIInPorts = 0, gNumMIDIOutPorts = 0; bool gMIDIInitialized = false; static std::vector<uint8_t> gSysexData; static bool gSysexFlag = false; static uint8_t gRunningStatus = 0; PmStream* gMIDIInStreams[kMaxMidiPorts]; bool gMIDIInStreamUsed[kMaxMidiPorts]; PmStream* gMIDIOutStreams[kMaxMidiPorts]; std::map<int, int> gMidiInputIndexToPmDevIndex; std::map<int, int> gMidiOutputIndexToPmDevIndex; SC_Lock gPmStreamMutex; /* if INPUT_BUFFER_SIZE is 0, PortMidi uses a default value */ #define PMSTREAM_INPUT_BUFFER_SIZE 0 #define PMSTREAM_OUTPUT_BUFFER_SIZE 100 #define PMSTREAM_DRIVER_INFO NULL #define PMSTREAM_TIME_PROC NULL #define PMSTREAM_TIME_INFO NULL extern bool compiledOK; static void sysexBegin() { gRunningStatus = 0; // clear running status gSysexData.clear(); gSysexFlag = true; } static void scCallSysexAction(PyrSymbol* action) { VMGlobals* g = gMainVMGlobals; uint8_t* pSysexData = &gSysexData[0]; // Convert to array access PyrInt8Array* sysexArray = newPyrInt8Array(g->gc, gSysexData.size(), 0, true); sysexArray->size = gSysexData.size(); memcpy(sysexArray->b, pSysexData, gSysexData.size()); ++g->sp; SetObject(g->sp, (PyrObject*)sysexArray); // chan argument unneeded as there runInterpreter(g, action, 3); // special sysex action in the lang } static void sysexEnd() { gSysexFlag = false; scCallSysexAction(s_midiSysexAction); } static void sysexEndInvalid() { gSysexFlag = false; scCallSysexAction(s_midiInvalidSysexAction); } static int midiProcessPartialSystemPacket(uint32_t msg) { int index, data; VMGlobals* g = gMainVMGlobals; // to iterate over the contents of the message byte by byte uint8_t* p = reinterpret_cast<uint8_t*>(&msg); int i = 0; while (i < 4) { switch (p[i]) { /* SysEx start */ case 0xF0: if (gSysexFlag) { sysexEndInvalid(); } sysexBegin(); // new sysex in gSysexData.push_back(p[i]); // add SOX i++; break; /* SysEx end */ case 0xF7: gSysexData.push_back(p[i]); // add EOX if (gSysexFlag) sysexEnd(); // if last_uid != 0 rebuild the VM. else sysexEndInvalid(); // invalid 1 byte with only EOX can happen return 0; /* MIDI clock. Can only be received as the first byte */ case 0xF1: index = p[i + 1] >> 4; data = p[i + 1] & 0xf; if (index % 2) { data = data << 4; } ++g->sp; SetInt(g->sp, index); // chan unneeded ++g->sp; SetInt(g->sp, data); // special smpte action in the lang runInterpreter(g, s_midiSMPTEAction, 4); return 0; /* Song pointer. Can only be received as the first byte */ case 0xF2: ++g->sp; SetInt(g->sp, 2); ++g->sp; SetInt(g->sp, (p[i + 2] << 7) | p[i + 1]); runInterpreter(g, s_midiSysrtAction, 4); return 0; /* Song select. Can only be received as the first byte */ case 0xF3: ++g->sp; SetInt(g->sp, 3); ++g->sp; SetInt(g->sp, p[i + 1]); runInterpreter(g, s_midiSysrtAction, 4); return 0; /* Realtime messages. Can be anywhere within a message */ case 0xF6: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFE: gRunningStatus = 0; // clear running status ++g->sp; SetInt(g->sp, p[i] & 0xF); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); i++; break; default: // This should be data if (p[i] & 0x80) { // if it a command byte, it is an error gSysexData.push_back(p[i]); // add it as an abort message sysexEndInvalid(); // flush invalid return 0; } else if (gSysexFlag) { gSysexData.push_back(p[i]); // add Byte i++; } else { // garbage - handle in case - discard it i++; break; } } } return 0; } /* timer "interrupt" for processing midi data */ static void PMProcessMidi(PtTimestamp timestamp, void* userData) { PmEvent buffer; /* just one message at a time */ for (int i = 0; i < gNumMIDIInPorts; ++i) { for (;;) { long Tstatus, data1, data2; // Only lock the PM mutex while accessing the PortMidi functionality. It is very important to not acquire // the lang mutex while holding the PM mutex to avoid a deadlock, since the laguage may try to acquire the // PM mutex for a MIDIOut operation { lock_guard<SC_Lock> mulo(gPmStreamMutex); PmStream* midi_in = gMIDIInStreams[i]; if (!midi_in) { break; } const PmError result = Pm_Poll(midi_in); if (result == pmNoData) { break; } else if (result != pmGotData) { std::printf("errrr %s\n", Pm_GetErrorText(result)); continue; } if (Pm_Read(midi_in, &buffer, 1) == pmBufferOverflow) continue; // unless there was overflow, we should have a message now Tstatus = Pm_MessageStatus(buffer.message); // The PM mutex is released here } // +---------------------------------------------+ // | Lock the interp. mutex and dispatch message | // +---------------------------------------------+ gLangMutex.lock(); if (compiledOK) { VMGlobals* g = gMainVMGlobals; uint8 status = static_cast<uint8>(Tstatus & 0xF0); uint8 chan = static_cast<uint8>(Tstatus & 0x0F); g->canCallOS = false; // cannot call the OS // Do not put the data in the stack again if we are in the middle of processing a System Message, if (!gSysexFlag) { ++g->sp; SetObject(g->sp, s_midiin->u.classobj); // Set the class MIDIIn ++g->sp; SetInt(g->sp, i); // src } if (status & 0x80) // set the running status for voice messages gRunningStatus = ((status >> 4) == 0xF) ? 0 : Tstatus; // keep also additional info L: switch (status) { case 0x80: // noteOff ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); ++g->sp; SetInt(g->sp, Pm_MessageData2(buffer.message)); runInterpreter(g, s_midiNoteOffAction, 5); break; case 0x90: // noteOn ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); ++g->sp; SetInt(g->sp, Pm_MessageData2(buffer.message)); // runInterpreter(g, data2 ? s_midiNoteOnAction : s_midiNoteOffAction, 5); runInterpreter(g, s_midiNoteOnAction, 5); break; case 0xA0: // polytouch ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); ++g->sp; SetInt(g->sp, Pm_MessageData2(buffer.message)); runInterpreter(g, s_midiPolyTouchAction, 5); break; case 0xB0: // control ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); ++g->sp; SetInt(g->sp, Pm_MessageData2(buffer.message)); runInterpreter(g, s_midiControlAction, 5); break; case 0xC0: // program ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); runInterpreter(g, s_midiProgramAction, 4); break; case 0xD0: // touch ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, Pm_MessageData1(buffer.message)); runInterpreter(g, s_midiTouchAction, 4); break; case 0xE0: // bend ++g->sp; SetInt(g->sp, chan); // chan ++g->sp; SetInt(g->sp, (Pm_MessageData2(buffer.message) << 7) | Pm_MessageData1(buffer.message)); runInterpreter(g, s_midiBendAction, 4); break; case 0xF0: // only the first Pm_Event will carry the 0xF0 byte // we pass the messages to the processing function, which will take care of assembling the, midiProcessPartialSystemPacket(buffer.message); break; default: // data byte => continuing sysex message ir running status if (gRunningStatus && !gSysexFlag) { // handle running status status = gRunningStatus & 0xF0; // accept running status only inside a packet beginning chan = gRunningStatus & 0x0F; // with a valid status byte SetInt(g->sp, chan); goto L; // parse again with running status set // mv - get next byte } if (gSysexFlag) { midiProcessPartialSystemPacket(buffer.message); // process sysex packet } break; } g->canCallOS = false; } gLangMutex.unlock(); } // if (midi_in) } // for loop until numMIDIInPorts } /* ------------------------------------------------------------- */ static void midiCleanUp(); static int initMIDI(int numIn, int numOut) { midiCleanUp(); lock_guard<SC_Lock> mulo(gPmStreamMutex); const PmError initializationError = Pm_Initialize(); if (initializationError) { std::printf("MIDI: cannot open midi backend %s\n", Pm_GetErrorText(initializationError)); return errFailed; } /* Here, numIn and numOut are 0, even if the inputs to lang (MIDIClient init) were nil, but according to the documentation, it should be the number of inputs or outputs. That matches what I see in MIDIOut.sc -> MIDIClient *init, in which it is setting that to sources.size, and destinations.size, so I guess that the problem is that this information is not known at this point, or there is something missing. */ if (numIn > kMaxMidiPorts) { std::printf("MIDI: note that maximum midi in ports is limited to %i.\n", kMaxMidiPorts); } if (numOut > kMaxMidiPorts) { std::printf("MIDI: note that maximum midi out ports is limited to %i.\n", kMaxMidiPorts); } numIn = sc_clip(numIn, 1, kMaxMidiPorts); numOut = sc_clip(numOut, 1, kMaxMidiPorts); int inIndex = 0; int outIndex = 0; for (int i = 0; i < Pm_CountDevices(); ++i) { const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(i); if (devInfo->input) { gNumMIDIInPorts++; gMidiInputIndexToPmDevIndex[inIndex++] = i; } /* Ignore the MIDI Mapper. Otherwise, if it is allocated, we get "already allocated" errors */ if ((devInfo->output) && (strnicmp(devInfo->name, "Microsoft MIDI Mapper", 50) != 0)) { gNumMIDIOutPorts++; gMidiOutputIndexToPmDevIndex[outIndex++] = i; } } if (gNumMIDIInPorts > numIn) gNumMIDIInPorts = numIn; if (gNumMIDIOutPorts > numOut) gNumMIDIOutPorts = numOut; for (int i = 0; i < gNumMIDIOutPorts; i++) { const int pmdid = gMidiOutputIndexToPmDevIndex[i]; const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(pmdid); const PmError error = Pm_OpenOutput(&gMIDIOutStreams[i], pmdid, NULL, 512L, NULL, NULL, 0); std::printf("MIDI: device %d %d %d %s (%s)\n", i, pmdid, &gMIDIOutStreams[i], Pm_GetErrorText(error), devInfo->name); if (error) { std::printf("MIDI: cannot open device %d %d %s (%s)\n", i, pmdid, Pm_GetErrorText(error), devInfo->name); int hostError; if ((hostError = Pm_HasHostError(nullptr))) { char hostErrorString[PM_HOST_ERROR_MSG_LEN]; Pm_GetHostErrorText(hostErrorString, PM_HOST_ERROR_MSG_LEN); std::printf("MIDI: Host error %s\n", hostErrorString); } } } /* will call our function, PMProcessMidi() every millisecond */ Pt_Start(1, &PMProcessMidi, 0); /* start a timer with millisecond accuracy */ gMIDIInitialized = true; return errNone; } static int getNumSources() { int n = 0; for (int i = 0; i < Pm_CountDevices(); ++i) { const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(i); if (devInfo->input) { n++; } } return n; } static int getNumDestinations() { int n = 0; for (int i = 0; i < Pm_CountDevices(); ++i) { const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(i); if ((devInfo->output) && (strnicmp(devInfo->name, "Microsoft MIDI Mapper", 50) != 0)) { n++; } } return n; } /* ------------------------------------------------------------- */ static void midiCleanUp() { lock_guard<SC_Lock> mulo(gPmStreamMutex); if (gMIDIInitialized) { for (int i = 0; i < gNumMIDIOutPorts; ++i) { Pm_Abort(gMIDIOutStreams[i]); Pm_Close(gMIDIOutStreams[i]); } for (int i = 0; i < gNumMIDIInPorts; ++i) { if (gMIDIInStreamUsed[i]) { Pm_Abort(gMIDIInStreams[i]); Pm_Close(gMIDIInStreams[i]); } } gNumMIDIOutPorts = 0; gNumMIDIInPorts = 0; } // set the stream pointers to NULL memset(gMIDIInStreams, 0, kMaxMidiPorts * sizeof(PmStream*)); memset(gMIDIOutStreams, 0, kMaxMidiPorts * sizeof(PmStream*)); // Mark the MIDI ins as not used for (int i = 0; i < kMaxMidiPorts; i++) { gMIDIInStreamUsed[i] = false; } // delete the objects that map in/out indices to Pm dev indices gMidiInputIndexToPmDevIndex.clear(); gMidiOutputIndexToPmDevIndex.clear(); gMIDIInitialized = false; } /* ------------------------------------------------------------- */ void midiListEndpoints() {} /* ------------------------------------------------------------- */ int prListMIDIEndpoints(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; int numSrc = getNumSources(); int numDst = getNumDestinations(); PyrObject* idarray = newPyrArray(g->gc, 6 * sizeof(PyrObject), 0, true); SetObject(a, idarray); // 0 PyrObject* idarraySo = newPyrArray(g->gc, numSrc * sizeof(__int32), 0, true); SetObject(idarray->slots + idarray->size++, idarraySo); g->gc->GCWrite(idarray, idarraySo); // 1 PyrObject* devarraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarraySo); g->gc->GCWrite(idarray, devarraySo); // 2 PyrObject* namearraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearraySo); g->gc->GCWrite(idarray, namearraySo); // 3 PyrObject* idarrayDe = newPyrArray(g->gc, numDst * sizeof(__int32), 0, true); SetObject(idarray->slots + idarray->size++, idarrayDe); g->gc->GCWrite(idarray, idarrayDe); // 4 PyrObject* namearrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearrayDe); g->gc->GCWrite(idarray, namearrayDe); // 5 PyrObject* devarrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarrayDe); g->gc->GCWrite(idarray, devarrayDe); for (int i = 0; i < numSrc; ++i) { const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(gMidiInputIndexToPmDevIndex[i]); char cendname[1024], cdevname[1024]; // currently, copy both name strings in endpoint name and dev name strncpy(cendname, devInfo->name, 1023); cendname[1023] = 0; strncpy(cdevname, devInfo->name, 1023); cdevname[1023] = 0; PyrString* string = newPyrString(g->gc, cendname, 0, true); SetObject(namearraySo->slots + i, string); namearraySo->size++; g->gc->GCWrite(namearraySo, (PyrObject*)string); PyrString* devstring = newPyrString(g->gc, cdevname, 0, true); SetObject(devarraySo->slots + i, devstring); devarraySo->size++; g->gc->GCWrite(devarraySo, (PyrObject*)devstring); SetInt(idarraySo->slots + i, i); idarraySo->size++; } // post("numDst %d\n", numDst); for (int i = 0; i < numDst; ++i) { const PmDeviceInfo* devInfo = Pm_GetDeviceInfo(gMidiOutputIndexToPmDevIndex[i]); char cendname[1024], cdevname[1024]; // currently, copy both name strings in endpoint name and dev name strncpy(cendname, devInfo->name, 1023); cendname[1023] = 0; strncpy(cdevname, devInfo->name, 1023); cdevname[1023] = 0; PyrString* string = newPyrString(g->gc, cendname, 0, true); SetObject(namearrayDe->slots + namearrayDe->size++, string); g->gc->GCWrite(namearrayDe, (PyrObject*)string); PyrString* devstring = newPyrString(g->gc, cdevname, 0, true); SetObject(devarrayDe->slots + devarrayDe->size++, devstring); g->gc->GCWrite(devarrayDe, (PyrObject*)devstring); SetInt(idarrayDe->slots + idarrayDe->size++, i); } return errNone; } /* ------------------------------------------------------------- */ int prConnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { lock_guard<SC_Lock> mulo(gPmStreamMutex); // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return errWrongType; if (inputIndex < 0 || inputIndex >= gNumMIDIInPorts) return errIndexOutOfRange; err = slotIntVal(c, &uid); if (err) return errWrongType; PmStream* inStream = NULL; int pmdid = gMidiInputIndexToPmDevIndex[uid]; const PmError error = Pm_OpenInput(&inStream, pmdid, PMSTREAM_DRIVER_INFO, PMSTREAM_INPUT_BUFFER_SIZE, PMSTREAM_TIME_PROC, PMSTREAM_TIME_INFO); if (error) { std::printf("cannot open MIDI input: %s\n", Pm_GetErrorText(error)); int hostError; if ((hostError = Pm_HasHostError(nullptr))) { char hostErrorString[PM_HOST_ERROR_MSG_LEN]; Pm_GetHostErrorText(hostErrorString, PM_HOST_ERROR_MSG_LEN); std::printf("MIDI: Host error %s\n", hostErrorString); } return errFailed; } gMIDIInStreams[uid] = inStream; gMIDIInStreamUsed[uid] = true; return errNone; } /* ------------------------------------------------------------- */ int prDisconnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { lock_guard<SC_Lock> mulo(gPmStreamMutex); PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; if (inputIndex < 0 || inputIndex >= gNumMIDIInPorts) return errIndexOutOfRange; err = slotIntVal(c, &uid); if (err) return err; if (gMIDIInStreamUsed[uid]) { const PmError error = Pm_Close(gMIDIInStreams[uid]); if (error) { std::printf("cannot close MIDI device: %s\n", Pm_GetErrorText(error)); return errFailed; } gMIDIInStreamUsed[uid] = false; gMIDIInStreams[uid] = NULL; } return errNone; } /* ------------------------------------------------------------- */ int prInitMIDI(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, numIn, numOut; err = slotIntVal(b, &numIn); if (err) return errWrongType; err = slotIntVal(c, &numOut); if (err) return errWrongType; return initMIDI(numIn, numOut); } int prDisposeMIDIClient(VMGlobals* g, int numArgsPushed) { midiCleanUp(); return errNone; } int prRestartMIDI(VMGlobals* g, int numArgsPushed) { /* Do nothing */ return errNone; } /* void freeSysex(MIDISysexSendRequest* pk) { free(pk->data); free(pk); } */ int prSendSysex(VMGlobals* g, int numArgsPushed) { lock_guard<SC_Lock> mulo(gPmStreamMutex); int err, uid; PyrSlot* args = g->sp - 2; // args[1] contains the uid and args[2] contains the array err = slotIntVal(&args[1], &uid); if (err) return err; if (!isKindOfSlot(&args[2], s_int8array->u.classobj)) return errWrongType; PyrInt8Array* packet = slotRawInt8Array(&args[2]); if (gMIDIOutStreams[uid]) { PmError result = Pm_WriteSysEx(gMIDIOutStreams[uid], 0, packet->b); if (result != pmNoError) return errFailed; else return errNone; } return errFailed; } /* ------------------------------------------------------------- */ int prSendMIDIOut(struct VMGlobals* g, int numArgsPushed) { lock_guard<SC_Lock> mulo(gPmStreamMutex); // port, uid, len, hiStatus, loStatus, a, b, latency // PyrSlot *m = g->sp - 8; PyrSlot* p = g->sp - 7; PyrSlot* u = g->sp - 6; PyrSlot* l = g->sp - 5; PyrSlot* his = g->sp - 4; PyrSlot* los = g->sp - 3; PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* plat = g->sp; int err, outputIndex, uid, length, hiStatus, loStatus, aval, bval; float late; err = slotIntVal(p, &outputIndex); if (err) return err; if (outputIndex < 0 || outputIndex >= gNumMIDIOutPorts) return errIndexOutOfRange; err = slotIntVal(u, &uid); if (err) return err; err = slotIntVal(l, &length); if (err) return err; err = slotIntVal(his, &hiStatus); if (err) return err; err = slotIntVal(los, &loStatus); if (err) return err; err = slotIntVal(a, &aval); if (err) return err; err = slotIntVal(b, &bval); if (err) return err; err = slotFloatVal(plat, &late); if (err) return err; Pm_WriteShort(gMIDIOutStreams[uid], 0, Pm_Message((hiStatus & 0xF0) | (loStatus & 0x0F), aval, bval)); return errNone; } // not needed in PortMIDI: int initMIDIClient() { return errNone; } int prInitMIDIClient(struct VMGlobals* g, int numArgsPushed) { return initMIDIClient(); } void initMIDIPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; s_midiin = getsym("MIDIIn"); s_domidiaction = getsym("doAction"); s_midiNoteOnAction = getsym("doNoteOnAction"); s_midiNoteOffAction = getsym("doNoteOffAction"); s_midiTouchAction = getsym("doTouchAction"); s_midiControlAction = getsym("doControlAction"); s_midiPolyTouchAction = getsym("doPolyTouchAction"); s_midiProgramAction = getsym("doProgramAction"); s_midiBendAction = getsym("doBendAction"); s_midiSysexAction = getsym("doSysexAction"); s_midiInvalidSysexAction = getsym("doInvalidSysexAction"); // client can handle incorrect case s_midiSysrtAction = getsym("doSysrtAction"); s_midiSMPTEAction = getsym("doSMPTEaction"); s_numMIDIDev = getsym("prSetNumberOfDevices"); s_midiclient = getsym("MIDIClient"); definePrimitive(base, index++, "_ListMIDIEndpoints", prListMIDIEndpoints, 1, 0); definePrimitive(base, index++, "_InitMIDI", prInitMIDI, 3, 0); definePrimitive(base, index++, "_InitMIDIClient", prInitMIDIClient, 1, 0); definePrimitive(base, index++, "_ConnectMIDIIn", prConnectMIDIIn, 3, 0); definePrimitive(base, index++, "_DisconnectMIDIIn", prDisconnectMIDIIn, 3, 0); definePrimitive(base, index++, "_DisposeMIDIClient", prDisposeMIDIClient, 1, 0); definePrimitive(base, index++, "_RestartMIDI", prRestartMIDI, 1, 0); definePrimitive(base, index++, "_SendMIDIOut", prSendMIDIOut, 9, 0); definePrimitive(base, index++, "_SendSysex", prSendSysex, 3, 0); midiCleanUp(); } void deinitMIDIPrimitives() { midiCleanUp(); }
27,567
C++
.cpp
700
30.864286
119
0.585967
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
29,867
SC_LinkClock.cpp
supercollider_supercollider/lang/LangPrimSource/SC_LinkClock.cpp
#ifdef SC_ABLETON_LINK # include "SC_LinkClock.hpp" inline std::chrono::microseconds hrToLinkTime(double secs) { auto time = std::chrono::duration<double>(secs); return std::chrono::duration_cast<std::chrono::microseconds>(time) + LinkClock::GetInitTime(); } inline double linkToHrTime(std::chrono::microseconds micros) { return DurToFloat(micros - LinkClock::GetInitTime()); } std::chrono::microseconds LinkClock::InitTime; LinkClock::LinkClock(VMGlobals* vmGlobals, PyrObject* tempoClockObj, double tempo, double baseBeats, double baseSeconds): TempoClock(vmGlobals, tempoClockObj, tempo, baseBeats, baseSeconds), mLink(tempo * 60.) { // quantum = beatsPerBar int err = slotDoubleVal(&tempoClockObj->slots[2], &mQuantum); if (err) throw err; mLatency = 0.; // default, user should override mLink.enable(true); mLink.enableStartStopSync(true); mLink.setTempoCallback([this](double bpm) { OnTempoChanged(bpm); }); mLink.setStartStopCallback([this](bool isPlaying) { OnStartStop(isPlaying); }); mLink.setNumPeersCallback([this](std::size_t numPeers) { OnNumPeersChanged(numPeers); }); auto sessionState = mLink.captureAppSessionState(); auto linkTime = hrToLinkTime(baseSeconds); sessionState.requestBeatAtTime(baseBeats, linkTime, mQuantum); mLink.commitAppSessionState(sessionState); } void LinkClock::Init() { InitTime = ableton::link::platform::Clock().micros(); } void LinkClock::SetAll(double tempo, double inBeats, double inSeconds) { auto sessionState = mLink.captureAppSessionState(); auto linkTime = hrToLinkTime(inSeconds); sessionState.setTempo(tempo * 60., linkTime); sessionState.requestBeatAtTime(inBeats, linkTime, mQuantum); CommitTempo(sessionState, tempo); } double LinkClock::BeatsToSecs(double beats) const { if (std::isinf(beats)) return beats; auto sessionState = mLink.captureAppSessionState(); double secs = linkToHrTime(sessionState.timeAtBeat(beats, mQuantum)) - mLatency; return secs; } double LinkClock::SecsToBeats(double secs) const { if (std::isinf(secs)) return secs; auto sessionState = mLink.captureAppSessionState(); double beats = sessionState.beatAtTime(hrToLinkTime(secs + mLatency), mQuantum); return beats; } void LinkClock::SetTempoAtBeat(double tempo, double inBeats) { auto sessionState = mLink.captureAppSessionState(); auto time = sessionState.timeAtBeat(inBeats, mQuantum); sessionState.setTempo(tempo * 60., time); CommitTempo(sessionState, tempo); } void LinkClock::SetTempoAtTime(double tempo, double inSeconds) { auto sessionState = mLink.captureAppSessionState(); sessionState.setTempo(tempo * 60., hrToLinkTime(inSeconds)); CommitTempo(sessionState, tempo); } void LinkClock::OnTempoChanged(double bpm) { double secs = elapsedTime(); double tempo = bpm / 60.; auto sessionState = mLink.captureAppSessionState(); double beats = sessionState.beatAtTime(hrToLinkTime(secs), mQuantum); mTempo = tempo; mBeatDur = 1. / tempo; mCondition.notify_one(); // call sclang callback gLangMutex.lock(); g->canCallOS = false; ++g->sp; SetObject(g->sp, mTempoClockObj); ++g->sp; SetFloat(g->sp, mTempo); ++g->sp; SetFloat(g->sp, beats); ++g->sp; SetFloat(g->sp, secs); ++g->sp; SetObject(g->sp, mTempoClockObj); runInterpreter(g, getsym("prTempoChanged"), 5); g->canCallOS = false; gLangMutex.unlock(); } // Primitives ------------------------------------------------------------------------------------- LinkClock* getLinkClock(PyrSlot* clockSlot) { auto* clock = static_cast<LinkClock*>(slotRawPtr(slotRawObject(clockSlot)->slots + 1)); if (!clock) { error("clock is not running.\n"); } return clock; } int prLinkClock_NumPeers(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (auto* clock = getLinkClock(a)) { SetInt(a, clock->NumPeers()); return errNone; } else { return errFailed; } } int prLinkClock_GetQuantum(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (auto* clock = getLinkClock(a)) { SetFloat(a, clock->GetQuantum()); return errNone; } else { return errFailed; } } int prLinkClock_SetQuantum(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (auto* clock = getLinkClock(a)) { double quantum; int err = slotDoubleVal(b, &quantum); if (err) return errWrongType; clock->SetQuantum(quantum); return errNone; } else { return errFailed; } } int prLinkClock_GetLatency(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (auto* clock = getLinkClock(a)) { SetFloat(a, clock->GetLatency()); return errNone; } else { return errFailed; } } int prLinkClock_SetLatency(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (auto* clock = getLinkClock(a)) { double latency; int err = slotDoubleVal(b, &latency); if (err) return errWrongType; clock->SetLatency(latency); return errNone; } else { return errFailed; } } void initLinkPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_LinkClock_New", prClock_New<LinkClock>, 4, 0); definePrimitive(base, index++, "_LinkClock_SetBeats", prClock_SetBeats<LinkClock>, 2, 0); definePrimitive(base, index++, "_LinkClock_SetTempoAtBeat", prClock_SetTempoAtBeat<LinkClock>, 3, 0); definePrimitive(base, index++, "_LinkClock_SetTempoAtTime", prClock_SetTempoAtTime<LinkClock>, 3, 0); definePrimitive(base, index++, "_LinkClock_SetAll", prClock_SetAll<LinkClock>, 4, 0); definePrimitive(base, index++, "_LinkClock_NumPeers", prLinkClock_NumPeers, 1, 0); definePrimitive(base, index++, "_LinkClock_GetQuantum", prLinkClock_GetQuantum, 1, 0); definePrimitive(base, index++, "_LinkClock_SetQuantum", prLinkClock_SetQuantum, 2, 0); definePrimitive(base, index++, "_LinkClock_GetLatency", prLinkClock_GetLatency, 1, 0); definePrimitive(base, index++, "_LinkClock_SetLatency", prLinkClock_SetLatency, 2, 0); } #endif
6,425
C++
.cpp
163
34.306748
118
0.682935
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
29,868
SC_AlsaMIDI.cpp
supercollider_supercollider/lang/LangPrimSource/SC_AlsaMIDI.cpp
/* Alsa MIDI/Sequencer support. Copyright (c) 2004 stefan kersten. ==================================================================== 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 "SCBase.h" #include "VMGlobals.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSched.h" #include "GC.h" #include "SC_LanguageClient.h" #include <atomic> #include <thread> PyrSymbol* s_midiin; PyrSymbol* s_domidiaction; PyrSymbol* s_midiNoteOnAction; PyrSymbol* s_midiNoteOffAction; PyrSymbol* s_midiTouchAction; PyrSymbol* s_midiControlAction; PyrSymbol* s_midiPolyTouchAction; PyrSymbol* s_midiProgramAction; PyrSymbol* s_midiBendAction; PyrSymbol* s_midiSysexAction; PyrSymbol* s_midiSysrtAction; PyrSymbol* s_midiSMPTEAction; const int kMaxMidiPorts = 128; bool gMIDIInitialized = false; extern bool compiledOK; // ===================================================================== // Platform declarations (interface routines) // ===================================================================== static int initClient(); static int initMIDI(int numIn, int numOut); static int disposeMIDI(); static int restartMIDI(); static void cleanUpMIDI(); static int listMIDIEndpoints(struct VMGlobals* g, PyrSlot* a); static int connectMIDIIn(int inputIndex, int uid); static int disconnectMIDIIn(int inputIndex, int uid); static int connectMIDIOut(int outputIndex, int uid); static int disconnectMIDIOut(int outputIndex, int uid); static int sendMIDI(int port, int destId, int length, int hiStatus, int loStatus, int aval, int bval, float late); static int sendMIDISysex(int port, int destId, int length, uint8* data); // ===================================================================== // Platform declarations (ALSA) // ===================================================================== #include <alsa/asoundlib.h> #include <vector> #include <string.h> static const size_t kAlsaMaxPacketSize = 3; static const size_t kAlsaMaxPortNameLen = 256; // MIDI packet struct SC_AlsaMidiPacket { uint8 data[kAlsaMaxPacketSize]; }; // MIDI client state struct SC_AlsaMidiClient { snd_seq_t* mHandle; int mQueue; int mNumInPorts; int mInPorts[kMaxMidiPorts]; int mNumOutPorts; int mOutPorts[kMaxMidiPorts]; snd_midi_event_t* mEventToMidi; snd_midi_event_t* mMidiToEvent; std::thread mInputThread; std::atomic_bool mShouldBeRunning { false }; int startInputThread() { mShouldBeRunning = true; try { std::thread inputThread([this] { inputThreadFunc(); }); mInputThread = std::move(inputThread); return errNone; } catch (...) { post("MIDI (ALSA): could not start input thread\n"); return errFailed; } } void joinInputThread() { mShouldBeRunning = false; if (mInputThread.joinable()) mInputThread.join(); } void inputThreadFunc(); void processEvent(snd_seq_event_t* evt); int connectInput(int inputIndex, int uid, int (*action)(snd_seq_t*, snd_seq_port_subscribe_t*), const char* actionName); int connectOutput(int outputIndex, int uid, int (*action)(snd_seq_t*, snd_seq_port_subscribe_t*), const char* actionName); int sendEvent(int outputIndex, int uid, snd_seq_event_t* evt, float late = 0.f); int mClientID; }; static SC_AlsaMidiClient gMIDIClient; // Port description struct SC_AlsaMidiPort { SC_AlsaMidiPort(): uid(0) { *name = 0; *device = 0; } char name[kAlsaMaxPortNameLen]; char device[kAlsaMaxPortNameLen]; int32 uid; }; // ===================================================================== // Platform implementation (ALSA) // ===================================================================== static inline int SC_AlsaMakeUID(int clientID, int portID) { return (clientID << 16) | (portID & 0xFFFF); } static inline void SC_AlsaParseUID(int uid, int& clientID, int& portID) { clientID = uid >> 16; portID = uid & 0xFFFF; } void SC_AlsaMidiClient::processEvent(snd_seq_event_t* evt) { int status = lockLanguageOrQuit(mShouldBeRunning); if (status == EINTR) return; if (status) { postfl("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; PyrInt8Array* sysexArray; SC_AlsaMidiPacket pkt; g->canCallOS = false; // cannot call the OS // class MIDIIn ++g->sp; SetObject(g->sp, s_midiin->u.classobj); // source ++g->sp; SetInt(g->sp, SC_AlsaMakeUID(evt->source.client, evt->source.port)); switch (evt->type) { // midi events case SND_SEQ_EVENT_NOTEOFF: // noteOff ++g->sp; SetInt(g->sp, evt->data.note.channel); ++g->sp; SetInt(g->sp, evt->data.note.note); ++g->sp; SetInt(g->sp, evt->data.note.velocity); runInterpreter(g, s_midiNoteOffAction, 5); break; case SND_SEQ_EVENT_NOTEON: // noteOn ++g->sp; SetInt(g->sp, evt->data.note.channel); ++g->sp; SetInt(g->sp, evt->data.note.note); ++g->sp; SetInt(g->sp, evt->data.note.velocity); // runInterpreter(g, evt->data.note.velocity ? s_midiNoteOnAction : s_midiNoteOffAction, 5); runInterpreter(g, s_midiNoteOnAction, 5); break; case SND_SEQ_EVENT_KEYPRESS: // polytouch ++g->sp; SetInt(g->sp, evt->data.note.channel); ++g->sp; SetInt(g->sp, evt->data.note.note); ++g->sp; SetInt(g->sp, evt->data.note.velocity); runInterpreter(g, s_midiPolyTouchAction, 5); break; case SND_SEQ_EVENT_CONTROLLER: // control ++g->sp; SetInt(g->sp, evt->data.control.channel); ++g->sp; SetInt(g->sp, evt->data.control.param); ++g->sp; SetInt(g->sp, evt->data.control.value); runInterpreter(g, s_midiControlAction, 5); break; case SND_SEQ_EVENT_PGMCHANGE: // program ++g->sp; SetInt(g->sp, evt->data.control.channel); ++g->sp; SetInt(g->sp, evt->data.control.value); runInterpreter(g, s_midiProgramAction, 4); break; case SND_SEQ_EVENT_CHANPRESS: // touch ++g->sp; SetInt(g->sp, evt->data.control.channel); ++g->sp; SetInt(g->sp, evt->data.control.value); runInterpreter(g, s_midiTouchAction, 4); break; case SND_SEQ_EVENT_PITCHBEND: // bend ++g->sp; SetInt(g->sp, evt->data.control.channel); ++g->sp; SetInt(g->sp, evt->data.control.value + 8192); runInterpreter(g, s_midiBendAction, 4); break; // system common events case SND_SEQ_EVENT_QFRAME: // mtc quarter frame { int index = evt->data.control.value >> 4; int data = evt->data.control.value & 0xf; #if 0 post( "mtc qframe: byte 0x%x index 0x%x data 0x%x\n", evt->data.control.value, index, data ); #endif switch (index) { case 1: case 3: case 5: case 7: data = data << 4; } ++g->sp; SetInt(g->sp, index); ++g->sp; SetInt(g->sp, data); } runInterpreter(g, s_midiSMPTEAction, 4); break; case SND_SEQ_EVENT_SONGPOS: // song ptr ++g->sp; SetInt(g->sp, 0x2); ++g->sp; // note: this differs from the corresponding sections // of SC_CoreMIDI.cpp and SC_PortMIDI.cpp. // Empirically I found that data.control.value has already been // decoded from the two 7-bit values -- the bitwise ops are not necessary here SetInt(g->sp, evt->data.control.value); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_SONGSEL: // song sel ++g->sp; SetInt(g->sp, 0x3); ++g->sp; SetInt(g->sp, evt->data.control.param); runInterpreter(g, s_midiSysrtAction, 4); break; // system realtime events case SND_SEQ_EVENT_TUNE_REQUEST: // tuning request ++g->sp; SetInt(g->sp, 0x6); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_CLOCK: // clock ++g->sp; SetInt(g->sp, 0x8); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_TICK: // tick ++g->sp; SetInt(g->sp, 0x9); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_START: // start ++g->sp; SetInt(g->sp, 0xA); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_CONTINUE: // continue ++g->sp; SetInt(g->sp, 0xB); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_STOP: // stop ++g->sp; SetInt(g->sp, 0xC); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_SENSING: // active sensing ++g->sp; SetInt(g->sp, 0xE); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; case SND_SEQ_EVENT_RESET: // system reset ++g->sp; SetInt(g->sp, 0xF); ++g->sp; SetInt(g->sp, 0); runInterpreter(g, s_midiSysrtAction, 4); break; // sysex events case SND_SEQ_EVENT_SYSEX: // sysex sysexArray = newPyrInt8Array(g->gc, evt->data.ext.len, 0, true); memcpy(sysexArray->b, evt->data.ext.ptr, evt->data.ext.len); sysexArray->size = evt->data.ext.len; ++g->sp; SetObject(g->sp, (PyrObject*)sysexArray); runInterpreter(g, s_midiSysexAction, 3); break; default: // unknown: convert to midi packet snd_midi_event_reset_decode(mEventToMidi); memset(pkt.data, 0, kAlsaMaxPacketSize); if (snd_midi_event_decode(mEventToMidi, pkt.data, kAlsaMaxPacketSize, evt) > 0) { for (size_t i = 0; i < kAlsaMaxPacketSize; i++) { ++g->sp; SetInt(g->sp, pkt.data[i]); } runInterpreter(g, s_domidiaction, 2 + kAlsaMaxPacketSize); } else { g->sp -= 2; } } g->canCallOS = false; } gLangMutex.unlock(); } void SC_AlsaMidiClient::inputThreadFunc() { int npfd = snd_seq_poll_descriptors_count(mHandle, POLLIN); struct pollfd pfd[npfd]; snd_seq_poll_descriptors(mHandle, pfd, npfd, POLLIN); while (mShouldBeRunning.load(std::memory_order_relaxed)) { if (poll(pfd, npfd, 2000) > 0) { // 2s timeout for (int i = 0; i < npfd; i++) { if (pfd[i].revents > 0) { do { snd_seq_event_t* evt = nullptr; int status = snd_seq_event_input(mHandle, &evt); if (status > 0) { assert(evt); processEvent(evt); snd_seq_free_event(evt); } } while (snd_seq_event_input_pending(mHandle, 0) > 0); } } } } } int SC_AlsaMidiClient::connectInput(int inputIndex, int uid, int (*action)(snd_seq_t*, snd_seq_port_subscribe_t*), const char* actionName) { snd_seq_t* seq = mHandle; snd_seq_client_info_t* cinfo; snd_seq_port_subscribe_t* subs; snd_seq_addr_t src, dst; int cid, pid; if ((inputIndex < 0) || (inputIndex >= mNumInPorts)) return errIndexOutOfRange; snd_seq_client_info_alloca(&cinfo); if (snd_seq_get_client_info(seq, cinfo) < 0) { post("MIDI (ALSA): could not get client info: %s\n", snd_strerror(errno)); return errFailed; } dst.client = snd_seq_client_info_get_client(cinfo); dst.port = mInPorts[inputIndex]; SC_AlsaParseUID(uid, cid, pid); src.client = cid; src.port = pid; // post("MIDI (ALSA): connect ndx %d uid %u dst %d:%d src %d:%d\n", inputIndex, uid, dst.client, dst.port, // src.client, src.port); snd_seq_port_subscribe_alloca(&subs); snd_seq_port_subscribe_set_sender(subs, &src); snd_seq_port_subscribe_set_dest(subs, &dst); if ((*action)(seq, subs) < 0) { post("MIDI (ALSA): %s failed (%s)\n", actionName, snd_strerror(errno)); return errFailed; } return errNone; } int SC_AlsaMidiClient::connectOutput(int outputIndex, int uid, int (*action)(snd_seq_t*, snd_seq_port_subscribe_t*), const char* actionName) { snd_seq_t* seq = mHandle; snd_seq_client_info_t* cinfo; snd_seq_port_subscribe_t* subs; snd_seq_addr_t src, dst; int cid, pid; if ((outputIndex < 0) || (outputIndex >= mNumOutPorts)) return errIndexOutOfRange; snd_seq_client_info_alloca(&cinfo); if (snd_seq_get_client_info(seq, cinfo) < 0) { post("MIDI (ALSA): could not get client info: %s\n", snd_strerror(errno)); return errFailed; } src.client = snd_seq_client_info_get_client(cinfo); src.port = mOutPorts[outputIndex]; SC_AlsaParseUID(uid, cid, pid); dst.client = cid; dst.port = pid; // post("MIDI (ALSA): connect ndx %d uid %u dst %d:%d src %d:%d\n", outputIndex, uid, dst.client, dst.port, // src.client, src.port); snd_seq_port_subscribe_alloca(&subs); snd_seq_port_subscribe_set_sender(subs, &src); snd_seq_port_subscribe_set_dest(subs, &dst); if ((*action)(seq, subs) < 0) { post("MIDI (ALSA): %s failed (%s)\n", actionName, snd_strerror(errno)); return errFailed; } return errNone; } int SC_AlsaMidiClient::sendEvent(int outputIndex, int uid, snd_seq_event_t* evt, float late) { snd_seq_real_time time; if ((outputIndex < 0) || (outputIndex >= mNumOutPorts)) return errIndexOutOfRange; snd_seq_ev_set_source(evt, mOutPorts[outputIndex]); if (uid == 0) { // send to all subscribed ports snd_seq_ev_set_subs(evt); } else { // send to specific port int cid, pid; SC_AlsaParseUID(uid, cid, pid); snd_seq_ev_set_dest(evt, cid, pid); } // long latelong; if (late > 0.f) { // latelong = (long) (late * 1000000000); // new time calculation. The old one was not correct // time.tv_sec = (long)(latelong / 1000000000); // seconds // time.tv_nsec = (long)(latelong % 1000000000); // nanoseconds time.tv_sec = (long)(floorf(late)); time.tv_nsec = (long)((late - time.tv_sec) * 1e9f); } else { time.tv_sec = time.tv_nsec = 0; } // evt->flags = evt->flags | SND_SEQ_TIME_STAMP_REAL; // post("MIDI (ALSA): sending event, time %i, %i, late %f, latelong %i\n", time.tv_sec, time.tv_nsec, late, // latelong); snd_seq_ev_schedule_real(evt, mQueue, 1, &time); snd_seq_event_output_direct(mHandle, evt); // snd_seq_event_output(mHandle, evt); // snd_seq_continue_queue(mHandle, mQueue, 0); // snd_seq_drain_output(mHandle); return errNone; } int initMIDI(int numIn, int numOut) { SC_AlsaMidiClient* client = &gMIDIClient; int i; if (client->mHandle) cleanUpMIDI(); if (numIn > kMaxMidiPorts) { printf("MIDI: note that maximum midi in ports is limited to %d.\n", kMaxMidiPorts); } if (numOut > kMaxMidiPorts) { printf("MIDI: note that maximum midi out ports is limited to %d.\n", kMaxMidiPorts); } numIn = sc_clip(numIn, 1, kMaxMidiPorts); numOut = sc_clip(numOut, 1, kMaxMidiPorts); // initialize client handle if (snd_seq_open(&client->mHandle, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { client->mHandle = nullptr; post("MIDI (ALSA): could not open ALSA sequencer: %s\n", snd_strerror(errno)); return errFailed; } snd_seq_set_client_name(client->mHandle, "SuperCollider"); // allocate i/o ports for (i = 0; i < numIn; i++) { char str[32]; int port; sprintf(str, "in%d", i); port = snd_seq_create_simple_port(client->mHandle, str, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_APPLICATION); if (port < 0) { post("MIDI (ALSA): could not create MIDI in port %d: %s\n", i, snd_strerror(errno)); break; } client->mInPorts[i] = port; } client->mNumInPorts = i; for (i = 0; i < numOut; i++) { char str[32]; int port; sprintf(str, "out%d", i); port = snd_seq_create_simple_port(client->mHandle, str, SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ, SND_SEQ_PORT_TYPE_APPLICATION); if (port < 0) { post("MIDI (ALSA): could not create MIDI out port %d: %s\n", i, snd_strerror(errno)); break; } client->mOutPorts[i] = port; } client->mNumOutPorts = i; // initialize queue client->mQueue = snd_seq_alloc_queue(client->mHandle); snd_seq_start_queue(client->mHandle, client->mQueue, nullptr); snd_seq_drain_output(client->mHandle); // snd_seq_set_client_pool_output(seqHandle, ??); // initialize event en-/decoders if (snd_midi_event_new(32, &client->mEventToMidi) < 0) { client->mEventToMidi = nullptr; post("MIDI (ALSA): could not create MIDI decoder\n"); return errFailed; } if (snd_midi_event_new(32, &client->mMidiToEvent) < 0) { client->mMidiToEvent = nullptr; post("MIDI (ALSA): could not create MIDI encoder\n"); return errFailed; } snd_midi_event_no_status(client->mEventToMidi, 1); snd_midi_event_no_status(client->mMidiToEvent, 1); // start input thread return client->startInputThread(); } int initMIDIClient() { SC_AlsaMidiClient* client = &gMIDIClient; if (client->mHandle) return errNone; // initialize client handle if (snd_seq_open(&client->mHandle, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { client->mHandle = nullptr; post("MIDI (ALSA): could not open ALSA sequencer: %s\n", snd_strerror(errno)); return errFailed; } snd_seq_set_client_name(client->mHandle, "SuperCollider"); client->mClientID = snd_seq_client_id(client->mHandle); // initialize queue client->mQueue = snd_seq_alloc_queue(client->mHandle); snd_seq_start_queue(client->mHandle, client->mQueue, nullptr); snd_seq_drain_output(client->mHandle); // snd_seq_set_client_pool_output(seqHandle, ??); // initialize event en-/decoders if (snd_midi_event_new(32, &client->mEventToMidi) < 0) { client->mEventToMidi = nullptr; post("MIDI (ALSA): could not create MIDI decoder\n"); return errFailed; } if (snd_midi_event_new(32, &client->mMidiToEvent) < 0) { client->mMidiToEvent = nullptr; post("MIDI (ALSA): could not create MIDI encoder\n"); return errFailed; } snd_midi_event_no_status(client->mEventToMidi, 1); snd_midi_event_no_status(client->mMidiToEvent, 1); return client->startInputThread(); } int disposeMIDI() { cleanUpMIDI(); return errNone; } int restartMIDI() { return errNone; } void cleanUpMIDI() { SC_AlsaMidiClient* client = &gMIDIClient; if (client->mHandle) { client->joinInputThread(); snd_seq_remove_events_t* revt; snd_seq_remove_events_malloc(&revt); snd_seq_remove_events_set_queue(revt, client->mQueue); snd_seq_remove_events_set_condition(revt, SND_SEQ_REMOVE_OUTPUT | SND_SEQ_REMOVE_IGNORE_OFF); snd_seq_remove_events(client->mHandle, revt); snd_seq_remove_events_free(revt); snd_seq_stop_queue(client->mHandle, client->mQueue, nullptr); snd_seq_free_queue(client->mHandle, client->mQueue); if (client->mEventToMidi) { snd_midi_event_free(client->mEventToMidi); } if (client->mMidiToEvent) { snd_midi_event_free(client->mMidiToEvent); } snd_seq_close(client->mHandle); client->mHandle = nullptr; } } inline static bool SC_AlsaCheckPerm(snd_seq_port_info_t* pinfo, int bits) { int cap = snd_seq_port_info_get_capability(pinfo); return ((cap & bits) == bits) && !(cap & SND_SEQ_PORT_CAP_NO_EXPORT); } int listMIDIEndpoints(struct VMGlobals* g, PyrSlot* a) { snd_seq_t* seq; snd_seq_client_info_t* cinfo; snd_seq_port_info_t* pinfo; if (!gMIDIClient.mHandle) return errFailed; seq = gMIDIClient.mHandle; snd_seq_client_info_alloca(&cinfo); snd_seq_port_info_alloca(&pinfo); snd_seq_client_info_set_client(cinfo, -1); std::vector<SC_AlsaMidiPort> srcPorts; std::vector<SC_AlsaMidiPort> dstPorts; while (snd_seq_query_next_client(seq, cinfo) >= 0) { int cid = snd_seq_client_info_get_client(cinfo); const char* cname = snd_seq_client_info_get_name(cinfo); if ((cid < 0) || (cid > 0xffff)) { post("MIDI (ALSA): client ID out of range.\n"); return errFailed; } snd_seq_port_info_set_client(pinfo, cid); snd_seq_port_info_set_port(pinfo, -1); while (snd_seq_query_next_port(seq, pinfo) >= 0) { int pid = snd_seq_port_info_get_port(pinfo); const char* pname = snd_seq_port_info_get_name(pinfo); if ((pid < 0) || (pid > 0xffff)) { post("MIDI (ALSA): port ID out of range.\n"); return errFailed; } if (SC_AlsaCheckPerm(pinfo, SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ)) { // src port srcPorts.push_back(SC_AlsaMidiPort()); snprintf(srcPorts.back().name, kAlsaMaxPortNameLen, "%s", pname); snprintf(srcPorts.back().device, kAlsaMaxPortNameLen, "%s", cname); srcPorts.back().uid = SC_AlsaMakeUID(cid, pid); // post("MIDI (ALSA): src %s-%s %d:%d %u\n", cname, pname, cid, pid, srcPorts.back().uid); } if (SC_AlsaCheckPerm(pinfo, SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)) { // dst port dstPorts.push_back(SC_AlsaMidiPort()); snprintf(dstPorts.back().name, kAlsaMaxPortNameLen, "%s", pname); snprintf(dstPorts.back().device, kAlsaMaxPortNameLen, "%s", cname); dstPorts.back().uid = SC_AlsaMakeUID(cid, pid); // post("MIDI (ALSA): dst %s-%s %d:%d %u\n", cname, pname, cid, pid, srcPorts.back().uid); } } } int numSrc = srcPorts.size(); int numDst = dstPorts.size(); PyrObject* idarray = newPyrArray(g->gc, 6 * sizeof(PyrObject), 0, true); SetObject(a, idarray); PyrObject* idarraySo = newPyrArray(g->gc, numSrc * sizeof(int32), 0, true); SetObject(idarray->slots + idarray->size++, idarraySo); g->gc->GCWrite(idarray, idarraySo); PyrObject* devarraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarraySo); g->gc->GCWrite(idarray, devarraySo); PyrObject* namearraySo = newPyrArray(g->gc, numSrc * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearraySo); g->gc->GCWrite(idarray, namearraySo); PyrObject* idarrayDe = newPyrArray(g->gc, numDst * sizeof(int32), 0, true); SetObject(idarray->slots + idarray->size++, idarrayDe); g->gc->GCWrite(idarray, idarrayDe); PyrObject* namearrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, namearrayDe); g->gc->GCWrite(idarray, namearrayDe); PyrObject* devarrayDe = newPyrArray(g->gc, numDst * sizeof(PyrObject), 0, true); SetObject(idarray->slots + idarray->size++, devarrayDe); g->gc->GCWrite(idarray, devarrayDe); for (int i = 0; i < numSrc; ++i) { char* name = srcPorts[i].name; char* devicename = srcPorts[i].device; PyrString* string = newPyrString(g->gc, name, 0, true); SetObject(namearraySo->slots + i, string); namearraySo->size++; g->gc->GCWrite(namearraySo, (PyrObject*)string); PyrString* devstring = newPyrString(g->gc, devicename, 0, true); SetObject(devarraySo->slots + i, devstring); devarraySo->size++; g->gc->GCWrite(devarraySo, (PyrObject*)devstring); SetInt(idarraySo->slots + i, srcPorts[i].uid); idarraySo->size++; } for (int i = 0; i < numDst; ++i) { char* name = dstPorts[i].name; char* devicename = dstPorts[i].device; PyrString* string = newPyrString(g->gc, name, 0, true); SetObject(namearrayDe->slots + namearrayDe->size++, string); g->gc->GCWrite(namearrayDe, (PyrObject*)string); PyrString* devstring = newPyrString(g->gc, devicename, 0, true); SetObject(devarrayDe->slots + i, devstring); devarrayDe->size++; g->gc->GCWrite(devarrayDe, (PyrObject*)devstring); SetInt(idarrayDe->slots + i, dstPorts[i].uid); idarrayDe->size++; } return errNone; } int connectMIDIIn(int inputIndex, int uid) { if (!gMIDIClient.mHandle) return errFailed; return gMIDIClient.connectInput(inputIndex, uid, &snd_seq_subscribe_port, "connect"); } int disconnectMIDIIn(int inputIndex, int uid) { if (!gMIDIClient.mHandle) return errFailed; return gMIDIClient.connectInput(inputIndex, uid, &snd_seq_unsubscribe_port, "disconnect"); } int connectMIDIOut(int outputIndex, int uid) { if (!gMIDIClient.mHandle) return errFailed; return gMIDIClient.connectOutput(outputIndex, uid, &snd_seq_subscribe_port, "connect"); } int disconnectMIDIOut(int outputIndex, int uid) { if (!gMIDIClient.mHandle) return errFailed; return gMIDIClient.connectOutput(outputIndex, uid, &snd_seq_unsubscribe_port, "disconnect"); } int sendMIDI(int port, int uid, int length, int hiStatus, int loStatus, int aval, int bval, float late) { if (!gMIDIClient.mHandle) return errFailed; // post("MIDI (ALSA): send %x %x %d %d %i\n", hiStatus>>4, loStatus, aval, bval, gMIDIClient.mMidiToEvent); snd_seq_event_t evt; SC_AlsaMidiPacket pkt; snd_seq_ev_clear(&evt); pkt.data[0] = (hiStatus & 0xF0) | (loStatus & 0x0F); pkt.data[1] = (uint8)aval; pkt.data[2] = (uint8)bval; snd_midi_event_reset_encode(gMIDIClient.mMidiToEvent); if (snd_midi_event_encode(gMIDIClient.mMidiToEvent, pkt.data, length, &evt) < 0) { post("MIDI (ALSA): could not encode midi data: %s\n", snd_strerror(errno)); return errFailed; } return gMIDIClient.sendEvent(port, uid, &evt, late); } int sendMIDISysex(int port, int uid, int length, uint8* data) { if (!gMIDIClient.mHandle) return errFailed; snd_seq_event_t evt; evt.type = SND_SEQ_EVENT_SYSEX; // MIDIOut.sysex patch 2007-01-16 snd_seq_ev_set_variable(&evt, length, data); return gMIDIClient.sendEvent(port, uid, &evt, 0.f); } // ===================================================================== // Primitives // ===================================================================== int prInitMIDI(struct VMGlobals* g, int numArgsPushed); int prInitMIDI(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, numIn, numOut; err = slotIntVal(b, &numIn); if (err) return errWrongType; err = slotIntVal(c, &numOut); if (err) return errWrongType; return initMIDI(numIn, numOut); } int prInitMIDIClient(struct VMGlobals* g, int numArgsPushed); int prInitMIDIClient(struct VMGlobals* g, int numArgsPushed) { return initMIDIClient(); } int prDisposeMIDIClient(VMGlobals* g, int numArgsPushed); int prDisposeMIDIClient(VMGlobals* g, int numArgsPushed) { return disposeMIDI(); } int prRestartMIDI(VMGlobals* g, int numArgsPushed); int prRestartMIDI(VMGlobals* g, int numArgsPushed) { return restartMIDI(); } int prListMIDIEndpoints(struct VMGlobals* g, int numArgsPushed); int prListMIDIEndpoints(struct VMGlobals* g, int numArgsPushed) { return listMIDIEndpoints(g, g->sp); } int prConnectMIDIIn(struct VMGlobals* g, int numArgsPushed); int prConnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; err = slotIntVal(c, &uid); if (err) return err; return connectMIDIIn(inputIndex, uid); } int prDisconnectMIDIIn(struct VMGlobals* g, int numArgsPushed); int prDisconnectMIDIIn(struct VMGlobals* g, int numArgsPushed) { PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; err = slotIntVal(c, &uid); if (err) return err; return disconnectMIDIIn(inputIndex, uid); } int prConnectMIDIOut(struct VMGlobals* g, int numArgsPushed); int prConnectMIDIOut(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; err = slotIntVal(c, &uid); if (err) return err; return connectMIDIOut(inputIndex, uid); } int prDisconnectMIDIOut(struct VMGlobals* g, int numArgsPushed); int prDisconnectMIDIOut(struct VMGlobals* g, int numArgsPushed) { PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int err, inputIndex, uid; err = slotIntVal(b, &inputIndex); if (err) return err; err = slotIntVal(c, &uid); if (err) return err; return disconnectMIDIOut(inputIndex, uid); } int prSendMIDIOut(struct VMGlobals* g, int numArgsPushed); int prSendMIDIOut(struct VMGlobals* g, int numArgsPushed) { // port, uid, len, hiStatus, loStatus, a, b, latency // PyrSlot *m = g->sp - 8; PyrSlot* p = g->sp - 7; PyrSlot* u = g->sp - 6; PyrSlot* l = g->sp - 5; PyrSlot* his = g->sp - 4; PyrSlot* los = g->sp - 3; PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* plat = g->sp; int err, outputIndex, uid, length, hiStatus, loStatus, aval, bval; float late; err = slotIntVal(p, &outputIndex); if (err) return err; err = slotIntVal(u, &uid); if (err) return err; err = slotIntVal(l, &length); if (err) return err; err = slotIntVal(his, &hiStatus); if (err) return err; err = slotIntVal(los, &loStatus); if (err) return err; err = slotIntVal(a, &aval); if (err) return err; err = slotIntVal(b, &bval); if (err) return err; err = slotFloatVal(plat, &late); if (err) return err; return sendMIDI(outputIndex, uid, length, hiStatus, loStatus, aval, bval, late); } int prSendSysex(VMGlobals* g, int numArgsPushed) { int err, uid, outputIndex; PyrInt8Array* packet; // rcvr, uid, packet PyrSlot* args = g->sp - 2; int MIDIOut_port_index = instVarOffset("MIDIOut", "port"); err = slotIntVal(slotRawObject(args)->slots + MIDIOut_port_index, &outputIndex); if (err) return err; err = slotIntVal(args + 1, &uid); if (err) return err; if (!isKindOfSlot(args + 2, s_int8array->u.classobj)) return errWrongType; packet = slotRawInt8Array(&args[2]); return sendMIDISysex(outputIndex, uid, packet->size, packet->b); } int prGetMIDIClientID(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp; if (!gMIDIClient.mHandle) return errFailed; SetInt(args, gMIDIClient.mClientID); return errNone; } void initMIDIPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; s_midiin = getsym("MIDIIn"); s_domidiaction = getsym("doAction"); s_midiNoteOnAction = getsym("doNoteOnAction"); s_midiNoteOffAction = getsym("doNoteOffAction"); s_midiTouchAction = getsym("doTouchAction"); s_midiControlAction = getsym("doControlAction"); s_midiPolyTouchAction = getsym("doPolyTouchAction"); s_midiProgramAction = getsym("doProgramAction"); s_midiBendAction = getsym("doBendAction"); s_midiSysexAction = getsym("doSysexAction"); s_midiSysrtAction = getsym("doSysrtAction"); s_midiSMPTEAction = getsym("doSMPTEaction"); definePrimitive(base, index++, "_InitMIDI", prInitMIDI, 3, 0); definePrimitive(base, index++, "_InitMIDIClient", prInitMIDIClient, 1, 0); definePrimitive(base, index++, "_RestartMIDI", prRestartMIDI, 1, 0); definePrimitive(base, index++, "_DisposeMIDIClient", prDisposeMIDIClient, 1, 0); definePrimitive(base, index++, "_ListMIDIEndpoints", prListMIDIEndpoints, 1, 0); definePrimitive(base, index++, "_ConnectMIDIIn", prConnectMIDIIn, 3, 0); definePrimitive(base, index++, "_DisconnectMIDIIn", prDisconnectMIDIIn, 3, 0); definePrimitive(base, index++, "_ConnectMIDIOut", prConnectMIDIOut, 3, 0); definePrimitive(base, index++, "_DisconnectMIDIOut", prDisconnectMIDIOut, 3, 0); definePrimitive(base, index++, "_SendMIDIOut", prSendMIDIOut, 9, 0); definePrimitive(base, index++, "_SendSysex", prSendSysex, 3, 0); // MIDIOut.sysex patch 2007-01-16 definePrimitive(base, index++, "_GetMIDIClientID", prGetMIDIClientID, 1, 0); cleanUpMIDI(); } void deinitMIDIPrimitives() { cleanUpMIDI(); } // EOF
35,934
C++
.cpp
905
32.081768
117
0.603383
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
29,869
SC_LID.cpp
supercollider_supercollider/lang/LangPrimSource/SC_LID.cpp
/* Linux Input Device support. Copyright (c) 2004 stefan kersten. modifications by Marije Baalman 2006-9 ==================================================================== 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 Linux Input Device interface, 2004 <sk> */ #include <atomic> #include "SCBase.h" #include "VMGlobals.h" #include "PyrSymbolTable.h" #include "PyrInterpreter.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrObjectProto.h" #include "PyrPrimitiveProto.h" #include "PyrKernelProto.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSched.h" #include "GC.h" #include "SC_LanguageClient.h" #if HAVE_LID # include <errno.h> # include <fcntl.h> # include <linux/input.h> # include <stdio.h> # include <string.h> # include <sys/select.h> # include <sys/types.h> # include <unistd.h> # define BITS_PER_LONG (sizeof(long) * 8) # define NBITS(x) ((((x)-1) / BITS_PER_LONG) + 1) # define OFF(x) ((x) % BITS_PER_LONG) # define BIT(x) (1UL << OFF(x)) # define LONG(x) ((x) / BITS_PER_LONG) # define TEST_BIT(array, bit) (((array)[LONG(bit)] >> OFF(bit)) & 1) extern bool compiledOK; static PyrSymbol* s_inputDeviceClass = nullptr; static PyrSymbol* s_inputDeviceInfoClass = nullptr; static PyrSymbol* s_absInfoClass = nullptr; static PyrSymbol* s_handleEvent = nullptr; static PyrSymbol* s_readError = nullptr; // ===================================================================== // SC_LID struct SC_LID { SC_LID(PyrObject* obj); ~SC_LID(); int open(const char* path); int close(); bool isEventTypeSupported(int evtType); bool isEventCodeSupported(int evtType, int evtCode); int getName(char* buf, size_t size); int getInfo(struct input_id* info, char* bufPhys, size_t sizePhys, char* bufUniq, size_t sizeUniq); int getKeyState(int evtCode); int getAbsInfo(int evtCode, struct input_absinfo* info); int setLedState(int evtCode, int evtValue, int evtType); int grab(int flag); void handleEvent(struct input_event& evt, std::atomic<bool> const& shouldBeRunning); void readError(std::atomic<bool> const& shouldBeRunning); static PyrObject* getObject(PyrSlot* slot) { return isKindOfSlot(slot, s_inputDeviceClass->u.classobj) ? slotRawObject(slot) : nullptr; } static SC_LID* getDevice(PyrObject* obj) { return (SC_LID*)slotRawPtr(&obj->slots[0]); } SC_LID* m_next; PyrObject* m_obj; int m_fd; int m_lastEventType; unsigned long m_eventTypeCaps[NBITS(EV_MAX)]; unsigned long m_eventCodeCaps[NBITS(KEY_MAX)]; unsigned long m_keyState[NBITS(KEY_MAX)]; }; // ===================================================================== // SC_LIDManager struct SC_LIDManager { public: static SC_LIDManager& instance(); int start(); int stop(); int add(SC_LID* dev); int remove(SC_LID* dev); private: SC_LIDManager(); ~SC_LIDManager(); enum { kStop, kAdd, kRemove }; struct Command { int id; union { SC_LID* dev; } arg; }; int sendCommand(const Command& cmd); void devicesChanged(); bool asyncAddDevice(SC_LID* dev); bool asyncRemoveDevice(SC_LID* dev); void loop(); static void* threadFunc(void*); pthread_t m_thread; pthread_mutex_t m_mutex; std::atomic<bool> m_running; std::atomic<bool> mShouldBeRunning; int m_cmdFifo[2]; int m_nfds; fd_set m_fds; SC_LID* m_devices; }; // ===================================================================== // SC_LID SC_LID::SC_LID(PyrObject* obj): m_next(nullptr), m_obj(obj), m_fd(-1), m_lastEventType(-1) { SetPtr(obj->slots + 0, this); } SC_LID::~SC_LID() { if (m_fd != -1) ::close(m_fd); } int SC_LID::open(const char* path) { m_fd = ::open(path, O_RDWR); if (m_fd == -1) { error("LID (1): %s\n", strerror(errno)); return errFailed; } memset(m_eventTypeCaps, 0, sizeof(m_eventTypeCaps)); if (ioctl(m_fd, EVIOCGBIT(0, EV_MAX), m_eventTypeCaps) == -1) { error("LID (2): %s\n", strerror(errno)); return errFailed; } memset(m_keyState, 0, sizeof(m_keyState)); if (ioctl(m_fd, EVIOCGKEY(sizeof(m_keyState)), m_keyState) == -1) { error("LID (3): %s\n", strerror(errno)); return errFailed; } return SC_LIDManager::instance().add(this); } int SC_LID::close() { SetNil(m_obj->slots + 0); return SC_LIDManager::instance().remove(this); } bool SC_LID::isEventTypeSupported(int evtType) { return TEST_BIT(m_eventTypeCaps, evtType); } bool SC_LID::isEventCodeSupported(int evtType, int evtCode) { if (evtType != m_lastEventType) { m_lastEventType = evtType; memset(m_eventCodeCaps, 0, sizeof(m_eventCodeCaps)); if (ioctl(m_fd, EVIOCGBIT(evtType, KEY_MAX), m_eventCodeCaps) == -1) { post("LID failed to check event code (error %s)\n", strerror(errno)); return false; } } return TEST_BIT(m_eventCodeCaps, evtCode); } int SC_LID::getName(char* buf, size_t size) { if (ioctl(m_fd, EVIOCGNAME(size), buf) == -1) { error("LID (5): %s\n", strerror(errno)); return errFailed; } return errNone; } int SC_LID::getInfo(struct input_id* info, char* bufPhys, size_t sizePhys, char* bufUniq, size_t sizeUniq) { if (ioctl(m_fd, EVIOCGID, info) == -1) { error("LID (6): %s\n", strerror(errno)); return errFailed; } if (ioctl(m_fd, EVIOCGPHYS(sizePhys), bufPhys) == -1) { // strcpy( sizePhys, strerror(errno)); post("LID could not retrieve physical location (error: %s)\n", strerror(errno)); // return errFailed; } if (ioctl(m_fd, EVIOCGUNIQ(sizeUniq), bufUniq) == -1) { // strcpy( strerror(errno), sizeof( strerror(errno)), sizeUniq ); post("LID could not get unique identifier (error: %s)\n", strerror(errno)); // return errFailed; } return errNone; } int SC_LID::getKeyState(int evtCode) { return TEST_BIT(m_keyState, evtCode); } int SC_LID::getAbsInfo(int evtCode, struct input_absinfo* info) { if (ioctl(m_fd, EVIOCGABS(evtCode), info) == -1) { error("LID (9): %s\n", strerror(errno)); return errFailed; } return errNone; } int SC_LID::setLedState(int evtCode, int evtValue, int evtType) { // added by marije baalman struct input_event ev; // post( "set led state called, putting event" ); ev.code = evtCode; ev.value = evtValue; ev.type = evtType; // post( "m_fd %i", m_fd ); // post( "code %i, value %i ", evtCode, evtValue ); if (write(m_fd, &ev, sizeof(struct input_event)) == -1) { // post( "error writing event" ); return errFailed; } return errNone; } int SC_LID::grab(int flag) { if (ioctl(m_fd, EVIOCGRAB, flag) == -1) { error("LID (10): %s\n", strerror(errno)); return errFailed; } return errNone; } void SC_LID::handleEvent(struct input_event& evt, std::atomic<bool> const& shouldBeRunning) { if (evt.type != EV_SYN) { int status = lockLanguageOrQuit(shouldBeRunning); if (status == EINTR) return; if (status) { postfl("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = false; ++g->sp; SetObject(g->sp, m_obj); ++g->sp; SetInt(g->sp, evt.type); ++g->sp; SetInt(g->sp, evt.code); ++g->sp; SetInt(g->sp, evt.value); runInterpreter(g, s_handleEvent, 4); g->canCallOS = false; } gLangMutex.unlock(); } } void SC_LID::readError(std::atomic<bool> const& shouldBeRunning) { int status = lockLanguageOrQuit(shouldBeRunning); if (status == EINTR) return; if (status) { postfl("error when locking language (%d)\n", status); return; } if (compiledOK) { VMGlobals* g = gMainVMGlobals; g->canCallOS = false; ++g->sp; SetObject(g->sp, m_obj); runInterpreter(g, s_readError, 1); g->canCallOS = false; } gLangMutex.unlock(); } // ===================================================================== // SC_LIDManager SC_LIDManager& SC_LIDManager::instance() { static SC_LIDManager instance; return instance; } SC_LIDManager::SC_LIDManager(): m_running(false), m_devices(nullptr) { if (pipe(m_cmdFifo) == -1) { m_cmdFifo[0] = m_cmdFifo[1] = -1; } devicesChanged(); } SC_LIDManager::~SC_LIDManager() { close(m_cmdFifo[0]); close(m_cmdFifo[1]); } int SC_LIDManager::start() { mShouldBeRunning = true; int err = pthread_create(&m_thread, nullptr, &threadFunc, this); if (err != 0) return errFailed; return errNone; } int SC_LIDManager::stop() { if (m_running == false) return errNone; Command cmd; cmd.id = kStop; int err = sendCommand(cmd); if (err) return err; mShouldBeRunning = false; err = pthread_join(m_thread, nullptr); if (err != 0) return errFailed; return errNone; } int SC_LIDManager::add(SC_LID* dev) { Command cmd; cmd.id = kAdd; cmd.arg.dev = dev; return sendCommand(cmd); } int SC_LIDManager::remove(SC_LID* dev) { Command cmd; cmd.id = kRemove; cmd.arg.dev = dev; return sendCommand(cmd); } int SC_LIDManager::sendCommand(const Command& cmd) { return write(m_cmdFifo[1], &cmd, sizeof(cmd)) == sizeof(cmd) ? errNone : errFailed; } void SC_LIDManager::devicesChanged() { int fdMax = m_cmdFifo[0]; FD_ZERO(&m_fds); FD_SET(fdMax, &m_fds); SC_LID* dev = m_devices; while (dev) { int fd = dev->m_fd; if (fd != -1) { FD_SET(fd, &m_fds); if (fd > fdMax) fdMax = fd; } dev = dev->m_next; } m_nfds = fdMax + 1; } bool SC_LIDManager::asyncAddDevice(SC_LID* dev) { if (dev->m_next) return false; dev->m_next = m_devices; m_devices = dev; devicesChanged(); return true; } bool SC_LIDManager::asyncRemoveDevice(SC_LID* dev) { SC_LID *prev = nullptr, *cur = m_devices; while (cur) { if (cur == dev) { if (prev) prev->m_next = dev->m_next; else m_devices = dev->m_next; dev->m_next = nullptr; delete dev; devicesChanged(); return true; } prev = cur; cur = cur->m_next; } return false; } void* SC_LIDManager::threadFunc(void* arg) { ((SC_LIDManager*)arg)->loop(); return nullptr; } void SC_LIDManager::loop() { m_running = true; post("LID: event loop started\n"); while (true) { fd_set fds; memcpy(&fds, &m_fds, sizeof(fd_set)); int n = select(m_nfds, &fds, nullptr, nullptr, nullptr); if (n == -1) { if (errno == EINTR) continue; post("LID: error in input handler: %s\n", strerror(errno)); goto quit; } else if (n > 0) { if (FD_ISSET(m_cmdFifo[0], &fds)) { Command cmd; --n; int err = read(m_cmdFifo[0], &cmd, sizeof(cmd)); if (err == -1) { if (errno != EINTR) { post("LID: error in input handler: %s\n", strerror(errno)); goto quit; } } else { switch (cmd.id) { case kStop: goto quit; case kAdd: if (asyncAddDevice(cmd.arg.dev)) { post("LID: added device %p\n", cmd.arg); } else { post("LID: cannot add device\n"); } break; case kRemove: if (asyncRemoveDevice(cmd.arg.dev)) { post("LID: removed device %p\n", cmd.arg); } else { post("LID: couldn't remove device\n"); } break; default: post("LID: unknown command in input handler\n"); } } } if (n > 0) { SC_LID* dev = m_devices; while (dev) { int fd = dev->m_fd; if (FD_ISSET(fd, &fds)) { struct input_event evt; if (read(fd, &evt, sizeof(evt)) == sizeof(evt)) { dev->handleEvent(evt, mShouldBeRunning); } else { dev->readError(mShouldBeRunning); } } if (!mShouldBeRunning) goto quit; dev = dev->m_next; } } } } quit: m_running = false; post("LID: event loop stopped\n"); } // ===================================================================== // Primitive Interface int prLID_Open(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; char path[PATH_MAX]; err = slotStrVal(args + 1, path, sizeof(path)); if (err) return err; SC_LID* dev = new SC_LID(obj); err = dev->open(path); if (err) { delete dev; return err; } return errNone; } int prLID_Close(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; return dev->close(); } int prLID_EventTypeSupported(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; int evtType; int err; if (!g->canCallOS) return errCantCallOS; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtType); if (err) return err; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; SetBool(args, dev->isEventTypeSupported(evtType)); return errNone; } int prLID_EventCodeSupported(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 2; int evtType, evtCode; int err; if (!g->canCallOS) return errCantCallOS; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtType); if (err) return err; err = slotIntVal(args + 2, &evtCode); if (err) return err; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; SetBool(args, dev->isEventCodeSupported(evtType, evtCode)); return errNone; } int prLID_GetInfo(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; if (!isKindOfSlot(args + 1, s_inputDeviceInfoClass->u.classobj)) return errWrongType; PyrObject* infoObj = slotRawObject(&args[1]); SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; char name[128]; err = dev->getName(name, sizeof(name)); if (err) return err; struct input_id info; char namePhys[128]; char nameUniq[128]; err = dev->getInfo(&info, namePhys, sizeof(namePhys), nameUniq, sizeof(nameUniq)); if (err) return err; SetSymbol(infoObj->slots + 0, getsym(name)); SetInt(infoObj->slots + 1, info.bustype); SetInt(infoObj->slots + 2, info.vendor); SetInt(infoObj->slots + 3, info.product); SetInt(infoObj->slots + 4, info.version); SetSymbol(infoObj->slots + 5, getsym(namePhys)); SetSymbol(infoObj->slots + 6, getsym(nameUniq)); slotCopy(&args[0], &args[1]); return errNone; } int prLID_GetKeyState(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; int evtCode; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtCode); if (err) return err; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; SetInt(args, dev->getKeyState(evtCode)); return errNone; } int prLID_GetAbsInfo(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 2; int evtCode; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtCode); if (err) return err; if (!isKindOfSlot(args + 2, s_absInfoClass->u.classobj)) return errWrongType; PyrObject* infoObj = slotRawObject(&args[2]); SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; struct input_absinfo info; err = dev->getAbsInfo(evtCode, &info); if (err) return err; SetInt(infoObj->slots + 0, info.value); SetInt(infoObj->slots + 1, info.minimum); SetInt(infoObj->slots + 2, info.maximum); SetInt(infoObj->slots + 3, info.fuzz); SetInt(infoObj->slots + 4, info.flat); slotCopy(&args[0], &args[2]); return errNone; } int prLID_Grab(VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; return dev->grab(IsTrue(args + 1)); } int prLID_Start(VMGlobals* g, int numArgsPushed) { // if (!g->canCallOS) return errCantCallOS; return SC_LIDManager::instance().start(); } int prLID_Stop(VMGlobals* g, int numArgsPushed) { // if (!g->canCallOS) return errCantCallOS; return SC_LIDManager::instance().stop(); } int prLID_SetLedState(VMGlobals* g, int numArgsPushed) { // post( "set led state primitive called" ); PyrSlot* args = g->sp - 2; int evtCode, evtValue; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtCode); if (err) return err; err = slotIntVal(args + 2, &evtValue); if (err) return err; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; SetInt(args, dev->setLedState(evtCode, evtValue, EV_LED)); return errNone; } int prLID_SetMscState(VMGlobals* g, int numArgsPushed) { // post( "set msc state primitive called\n" ); PyrSlot* args = g->sp - 2; int evtCode, evtValue; int err; PyrObject* obj = SC_LID::getObject(args + 0); if (!obj) return errWrongType; err = slotIntVal(args + 1, &evtCode); if (err) return err; err = slotIntVal(args + 2, &evtValue); if (err) return err; SC_LID* dev = SC_LID::getDevice(obj); if (!dev) return errFailed; SetInt(args, dev->setLedState(evtCode, evtValue, EV_MSC)); return errNone; } void SC_LIDInit() { int base, index; s_inputDeviceClass = getsym("LID"); s_inputDeviceInfoClass = getsym("LIDInfo"); s_absInfoClass = getsym("LIDAbsInfo"); s_handleEvent = getsym("prHandleEvent"); s_readError = getsym("prReadError"); base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_LID_Open", prLID_Open, 2, 0); definePrimitive(base, index++, "_LID_Close", prLID_Close, 1, 0); definePrimitive(base, index++, "_LID_EventTypeSupported", prLID_EventTypeSupported, 2, 0); definePrimitive(base, index++, "_LID_EventCodeSupported", prLID_EventCodeSupported, 3, 0); definePrimitive(base, index++, "_LID_GetInfo", prLID_GetInfo, 2, 0); definePrimitive(base, index++, "_LID_GetKeyState", prLID_GetKeyState, 2, 0); definePrimitive(base, index++, "_LID_GetAbsInfo", prLID_GetAbsInfo, 3, 0); definePrimitive(base, index++, "_LID_Grab", prLID_Grab, 2, 0); definePrimitive(base, index++, "_LID_Start", prLID_Start, 1, 0); definePrimitive(base, index++, "_LID_Stop", prLID_Stop, 1, 0); definePrimitive(base, index++, "_LID_SetLedState", prLID_SetLedState, 3, 0); // added by Marije Baalman definePrimitive(base, index++, "_LID_SetMscState", prLID_SetMscState, 3, 0); } #else // !HAVE_LID int prLID_Start(VMGlobals* g, int numArgsPushed) { return errNone; } int prLID_Stop(VMGlobals* g, int numArgsPushed) { return errNone; } void SC_LIDInit() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_LID_Start", prLID_Start, 1, 0); definePrimitive(base, index++, "_LID_Stop", prLID_Stop, 1, 0); } #endif // HAVE_LID void initLIDPrimitives() { SC_LIDInit(); } // EOF
22,118
C++
.cpp
664
26.612952
108
0.585818
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
29,870
PyrUnixPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrUnixPrim.cpp
/* 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 */ /* Primitives for Unix. */ #include <cstring> #include <errno.h> #include <signal.h> #include <boost/date_time/posix_time/posix_time_io.hpp> #include <tuple> #include <vector> #include "PyrObject.h" #include "PyrPrimitive.h" #include "PyrObject.h" #include "PyrKernel.h" #include "PyrSched.h" #include "PyrFilePrim.h" #include "VMGlobals.h" #include "GC.h" #include "SC_RGen.h" #include "SC_Filesystem.hpp" #include "sc_popen.h" #include "SCBase.h" #include "SC_Lock.h" #include <filesystem> #ifdef _WIN32 # include "SC_Win32Utils.h" #else # include <libgen.h> #endif namespace fs = std::filesystem; extern bool compiledOK; PyrSymbol* s_unixCmdAction; int prString_System(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char cmdline[1024]; int err = slotStrVal(a, cmdline, 1023); if (err) return err; int res = system(cmdline); SetInt(a, res); return errNone; } int prString_Basename(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char path[PATH_MAX]; int err = slotStrVal(a, path, PATH_MAX); if (err) return err; char* basename0 = basename(path); int size = strlen(basename0); PyrString* strobj = newPyrStringN(g->gc, size, 0, true); memcpy(strobj->s, basename0, size); SetObject(a, strobj); return errNone; } int prString_Dirname(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char path[PATH_MAX]; int err = slotStrVal(a, path, PATH_MAX); if (err) return err; char* dirname0 = dirname(path); int size = strlen(dirname0); PyrString* strobj = newPyrStringN(g->gc, size, 0, true); memcpy(strobj->s, dirname0, size); SetObject(a, strobj); return errNone; } static void string_popen_thread_func(pid_t pid, FILE* stream, bool postOutput) { char buf[1024]; setvbuf(stream, nullptr, _IONBF, 0); while (postOutput) { char* string = fgets(buf, 1024, stream); if (!string) break; postText(string, strlen(string)); } int res; res = sc_pclose(stream, pid); res = WEXITSTATUS(res); gLangMutex.lock(); if (compiledOK) { VMGlobals* g = gMainVMGlobals; ++g->sp; SetObject(g->sp, class_string); ++g->sp; SetInt(g->sp, res); ++g->sp; SetInt(g->sp, pid); runInterpreter(g, s_unixCmdAction, 3); } gLangMutex.unlock(); } int prString_POpen(struct VMGlobals* g, int numArgsPushed) { PyrSlot* callerSlot = g->sp - 1; PyrSlot* postOutputSlot = g->sp; int error; std::string cmdline; std::tie(error, cmdline) = slotStrStdStrVal(callerSlot); if (error != errNone) return error; #ifdef SC_IPHONE SetInt(a, 0); return errNone; #endif pid_t pid; FILE* stream; std::tie(pid, stream) = sc_popen(std::move(cmdline), "r"); if (stream != nullptr) { SC_Thread thread(std::bind(string_popen_thread_func, pid, stream, IsTrue(postOutputSlot))); thread.detach(); SetInt(callerSlot, pid); return errNone; } else return errFailed; } int prArrayPOpen(struct VMGlobals* g, int numArgsPushed) { PyrSlot* callerSlot = g->sp - 1; PyrSlot* postOutputSlot = g->sp; #ifdef SC_IPHONE SetInt(a, 0); return errNone; #endif if (NotObj(callerSlot)) return errWrongType; PyrObject* argsColl = slotRawObject(callerSlot); // argsColl must be a collection if (!(slotRawInt(&argsColl->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; // collection must contain at least one string: the path of executable to run if (argsColl->size < 1) return errFailed; int error; std::vector<std::string> strings; std::tie(error, strings) = PyrCollToVectorStdString(argsColl); if (error != errNone) return error; pid_t pid; FILE* stream; std::tie(pid, stream) = sc_popen_argv(strings, "r"); if (stream != nullptr) { SC_Thread thread(std::bind(string_popen_thread_func, pid, stream, IsTrue(postOutputSlot))); thread.detach(); SetInt(callerSlot, pid); return errNone; } else { return errFailed; } } int prPidRunning(VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; #ifdef _WIN32 HANDLE handle; handle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, slotRawInt(a)); if (handle) { unsigned long exitCode; if (GetExitCodeProcess(handle, &exitCode) == 0) SetFalse(a); else if (exitCode == STILL_ACTIVE) SetTrue(a); CloseHandle(handle); } else SetFalse(a); #else if (kill(slotRawInt(a), 0) == 0) SetTrue(a); else SetFalse(a); #endif return errNone; } int prUnix_Errno(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetInt(a, errno); return errNone; } #include <time.h> // Set only Date instance variables related to the tm struct: YMD, HMS // and weekday (not rawSeconds) static void fillSlotsFromTimeStruct(PyrSlot* result, struct tm* tm) { PyrSlot* slots = slotRawObject(result)->slots; SetInt(slots + 0, tm->tm_year + 1900); SetInt(slots + 1, tm->tm_mon + 1); // 0 based month SetInt(slots + 2, tm->tm_mday); SetInt(slots + 3, tm->tm_hour); SetInt(slots + 4, tm->tm_min); SetInt(slots + 5, tm->tm_sec); SetInt(slots + 6, tm->tm_wday); } // Set all Date instance variables (including rawSeconds) static void fillAllSlotsFromTime(PyrSlot* result, struct tm* tm, std::chrono::system_clock::time_point const& now) { fillSlotsFromTimeStruct(result, tm); PyrSlot* slots = slotRawObject(result)->slots; using namespace std::chrono; auto const secondsPerTick = static_cast<double>(system_clock::period::num) / system_clock::period::den; SetFloat(slots + 7, duration_cast<system_clock::duration>(now.time_since_epoch()).count() * secondsPerTick); } int prLocalTime(struct VMGlobals* g, int numArgsPushed) { using namespace std::chrono; system_clock::time_point now = system_clock::now(); time_t now_time_t = system_clock::to_time_t(now); struct tm* tm = localtime(&now_time_t); fillAllSlotsFromTime(g->sp, tm, now); return errNone; } int prGMTime(struct VMGlobals* g, int numArgsPushed) { using namespace std::chrono; system_clock::time_point now = system_clock::now(); time_t now_time_t = system_clock::to_time_t(now); struct tm* tm = gmtime(&now_time_t); fillAllSlotsFromTime(g->sp, tm, now); return errNone; } int prDateFromString(struct VMGlobals* g, int numArgsPushed) { PyrSlot* dateObjectSlot = g->sp - 2; PyrSlot* timeSlot = g->sp - 1; PyrSlot* formatSlot = g->sp; const auto len = 1024; char timeString[len]; if (slotStrVal(timeSlot, timeString, len)) return errWrongType; char formatString[len]; if (slotStrVal(formatSlot, formatString, len)) return errWrongType; using namespace boost::posix_time; auto facet = new time_input_facet(); // will be owned/deleted by the locale facet->format(formatString); std::istringstream ss(timeString); ss.imbue(std::locale(ss.getloc(), facet)); ptime pt; if (!(ss >> pt)) { error("time parsing failed\n"); return errFailed; } auto tm0 = to_tm(pt); tm0.tm_isdst = -1; // attempt to determine if Daylight Saving Time in effect auto timePoint = std::chrono::system_clock::from_time_t(mktime(&tm0)); fillAllSlotsFromTime(dateObjectSlot, &tm0, timePoint); return errNone; } // Given a Date structure, calculate and fill in any missing // or invalid properties, ignoring/overwriting the contents of // rawSeconds. If some of the (MD, HMS) instance variables are // nil, give them default values. If year is nil, throw an error. int prDateResolve(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrSlot* slots = slotRawObject(a)->slots; struct tm tm0 {}; if (slotIntVal(slots + 0, &tm0.tm_year)) { error("year must be a valid Integer\n"); return errWrongType; } tm0.tm_year -= 1900; // year in tm is relative to 1900 if (slotIntVal(slots + 1, &tm0.tm_mon)) { tm0.tm_mon = 0; // default to January } else { tm0.tm_mon--; // month in tm is 0-based } if (slotIntVal(slots + 2, &tm0.tm_mday)) { tm0.tm_mday = 1; // default to first of month } if (slotIntVal(slots + 3, &tm0.tm_hour)) { tm0.tm_hour = 0; // default to 0 hours } if (slotIntVal(slots + 4, &tm0.tm_min)) { tm0.tm_min = 0; // default to 0 minutes } if (slotIntVal(slots + 5, &tm0.tm_sec)) { tm0.tm_sec = 0; // default to 0 seconds } tm0.tm_isdst = -1; // attempt to determine if Daylight Saving Time in effect time_t tt = mktime(&tm0); if (tt == -1) { error("no valid time\n"); return errFailed; } // Fill in the missing weekday and rawSeconds fields. // Also, update the other fields, which may have changed if // they were previously outside valid ranges (this allows // for simple date math, such as adding or subtracing day, // years or months, then calling ResolveDate to revalidate). auto timePoint = std::chrono::system_clock::from_time_t(tt); fillAllSlotsFromTime(a, &tm0, timePoint); return errNone; } // Given only the rawSeconds property in a Date structure, calculate // and fill in the rest of its properties (YMD, HMS and dayOfWeek). int prDateResolveFromRawSeconds(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrSlot* slots = slotRawObject(a)->slots; double rawSeconds {}; if (slotDoubleVal(slots + 7, &rawSeconds)) return errWrongType; using namespace std::chrono; // Perform the reverse operation of fillAllSlotsFromTime() // to get the time_point from (double) seconds auto const ticksPerSecond = static_cast<double>(system_clock::period::den) / system_clock::period::num; auto elapsed = system_clock::duration(static_cast<system_clock::rep>(rawSeconds * ticksPerSecond)); auto epoch = system_clock::time_point(); auto timePoint = epoch + elapsed; auto tt = system_clock::to_time_t(timePoint); auto tm = localtime(&tt); // Set everything except rawSeconds fillSlotsFromTimeStruct(a, tm); return errNone; } int prAscTime(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrSlot* slots = slotRawObject(a)->slots; if (IsNil(slots + 0)) { SetNil(a); return errNone; } struct tm tm0; if (slotIntVal(slots + 0, &tm0.tm_year)) return errWrongType; tm0.tm_year -= 1900; if (slotIntVal(slots + 1, &tm0.tm_mon)) return errWrongType; tm0.tm_mon--; if (slotIntVal(slots + 2, &tm0.tm_mday)) return errWrongType; if (slotIntVal(slots + 3, &tm0.tm_hour)) return errWrongType; if (slotIntVal(slots + 4, &tm0.tm_min)) return errWrongType; if (slotIntVal(slots + 5, &tm0.tm_sec)) return errWrongType; if (slotIntVal(slots + 6, &tm0.tm_wday)) return errWrongType; const char* text = asctime(&tm0); int size = strlen(text) - 1; // Discard trailing newline PyrString* strobj = newPyrStringN(g->gc, size, 0, true); memcpy(strobj->s, text, size); SetObject(a, strobj); return errNone; } int prStrFTime(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; PyrSlot* slots = slotRawObject(a)->slots; if (IsNil(slots + 0)) { SetNil(a); return errNone; } struct tm tm0; if (slotIntVal(slots + 0, &tm0.tm_year)) return errWrongType; tm0.tm_year -= 1900; if (slotIntVal(slots + 1, &tm0.tm_mon)) return errWrongType; tm0.tm_mon--; if (slotIntVal(slots + 2, &tm0.tm_mday)) return errWrongType; if (slotIntVal(slots + 3, &tm0.tm_hour)) return errWrongType; if (slotIntVal(slots + 4, &tm0.tm_min)) return errWrongType; if (slotIntVal(slots + 5, &tm0.tm_sec)) return errWrongType; if (slotIntVal(slots + 6, &tm0.tm_wday)) return errWrongType; char format[1024]; if (slotStrVal(b, format, 1024)) return errWrongType; char buffer[1024]; if (strftime(buffer, 1024, format, &tm0) != 0) { int size = strlen(buffer); PyrString* strobj = newPyrStringN(g->gc, size, 0, true); memcpy(strobj->s, buffer, size); SetObject(a, strobj); } else { error("could not convert the date to string with the give format"); return errFailed; } return errNone; } int32 timeseed(); int prTimeSeed(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetInt(a, timeseed()); return errNone; } int prGetPid(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetInt(a, #ifndef _WIN32 getpid() #else GetCurrentProcessId() #endif ); return errNone; } void initUnixPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); s_unixCmdAction = getsym("doUnixCmdAction"); definePrimitive(base, index++, "_String_System", prString_System, 1, 0); definePrimitive(base, index++, "_String_Basename", prString_Basename, 1, 0); definePrimitive(base, index++, "_String_Dirname", prString_Dirname, 1, 0); definePrimitive(base, index++, "_String_POpen", prString_POpen, 2, 0); definePrimitive(base, index++, "_Unix_Errno", prUnix_Errno, 1, 0); definePrimitive(base, index++, "_LocalTime", prLocalTime, 1, 0); definePrimitive(base, index++, "_GMTime", prGMTime, 1, 0); definePrimitive(base, index++, "_Date_FromString", prDateFromString, 3, 0); definePrimitive(base, index++, "_Date_Resolve", prDateResolve, 1, 0); definePrimitive(base, index++, "_Date_ResolveFromRawSeconds", prDateResolveFromRawSeconds, 1, 0); definePrimitive(base, index++, "_AscTime", prAscTime, 1, 0); definePrimitive(base, index++, "_prStrFTime", prStrFTime, 2, 0); definePrimitive(base, index++, "_TimeSeed", prTimeSeed, 1, 0); definePrimitive(base, index++, "_PidRunning", prPidRunning, 1, 0); definePrimitive(base, index++, "_GetPid", prGetPid, 1, 0); definePrimitive(base, index++, "_ArrayPOpen", prArrayPOpen, 2, 0); }
15,362
C++
.cpp
431
30.482599
116
0.663205
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
29,871
PyrSymbolPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrSymbolPrim.cpp
/* 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 */ /* Primitives for Symbol. */ #include <string.h> #include <stdlib.h> #include "PyrPrimitive.h" #include "PyrSymbol.h" #include "VMGlobals.h" #include "PyrKernel.h" #include "SCBase.h" int prSymbolIsPrefix(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int length; a = g->sp - 1; b = g->sp; if (!IsSym(a) || !IsSym(b)) return errWrongType; int32 alen = slotRawSymbol(a)->length; int32 blen = slotRawSymbol(b)->length; length = sc_min(alen, blen); if (memcmp(slotRawSymbol(a)->name, slotRawSymbol(b)->name, length) == 0 && length > 0) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prSymbolClass(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrClass* classobj; // char firstChar; a = g->sp; if (slotRawSymbol(a)->flags & sym_Class) { // firstChar = slotRawSymbol(a)->name[0]; // if (firstChar >= 'A' && firstChar <= 'Z') { classobj = slotRawSymbol(a)->u.classobj; if (classobj) { SetObject(a, classobj); } else { SetNil(a); } } else { SetNil(a); } return errNone; } int prSymbolIsSetter(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (slotRawSymbol(a)->flags & sym_Setter) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prSymbolAsSetter(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; char str[256]; int len; a = g->sp; if (!(slotRawSymbol(a)->flags & sym_Setter)) { if ((slotRawSymbol(a)->flags & sym_Class) || (slotRawSymbol(a)->flags & sym_Primitive)) { error("Cannot convert class names or primitive names to setters.\n"); return errFailed; } if (strlen(slotRawSymbol(a)->name) > 255) { error("symbol name too long.\n"); return errFailed; } strcpy(str, slotRawSymbol(a)->name); len = strlen(str); str[len] = '_'; str[len + 1] = 0; // postfl("prSymbolAsSetter %s\n", str); SetRaw(a, getsym(str)); } return errNone; } int prSymbolAsGetter(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; char str[256]; a = g->sp; if ((slotRawSymbol(a)->flags & sym_Setter)) { if ((slotRawSymbol(a)->flags & sym_Class) || (slotRawSymbol(a)->flags & sym_Primitive)) { error("Cannot convert class names or primitive names to getters.\n"); return errFailed; } strcpy(str, slotRawSymbol(a)->name); str[strlen(str) - 1] = 0; // postfl("prSymbolAsGetter %s\n", str); SetRaw(a, getsym(str)); } return errNone; } int prSymbolIsClassName(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (slotRawSymbol(a)->flags & sym_Class) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prSymbolIsMetaClassName(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (slotRawSymbol(a)->flags & sym_MetaClass) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prSymbol_IsBinaryOp(struct VMGlobals* g, int numArgsPushed) { static const char* binary_op_characters = "!@%&*-+=|<>?/"; PyrSlot* a = g->sp; const char* str = slotRawSymbol(a)->name; if (str[0] == '\0') { // An empty symbol is not a valid binary operator. SetFalse(a); } else if (str[1] == '\0') { // A symbol of length 1 should be any binary operator character except '='. if (str[0] == '=') { SetFalse(a); } else { bool character_is_binary_operator = strchr(binary_op_characters, str[0]); SetBool(a, character_is_binary_operator); } } else { // A symbol of length 2+ must contain only binary operator characters, and must not start // with '//' or '/*'. if (str[0] == '/' && (str[1] == '/' || str[1] == '*')) { SetFalse(a); } else { const int length = strlen(str); SetTrue(a); for (int i = 0; i < length; i++) { bool character_is_binary_operator = strchr(binary_op_characters, str[i]); if (!character_is_binary_operator) { SetFalse(a); break; } } } } return errNone; } int prSymbol_IsIdentifier(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; const char* str = slotRawSymbol(a)->name; // An empty symbol is not a valid identifier. if (str[0] == '\0') { SetFalse(a); // The first character must be a lowercase letter. } else if ('a' <= str[0] && str[0] <= 'z') { int length = strlen(str); SetTrue(a); // All other characters must be alphanumeric or '_'. for (int i = 1; i < length; i++) { char c = str[i]; if (!((c == '_') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9'))) { SetFalse(a); break; } } } else { SetFalse(a); } return errNone; } int prSymbol_AsInteger(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char* str = slotRawSymbol(a)->name; SetInt(a, atoi(str)); return errNone; } int prSymbol_PrimitiveIndex(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetInt(a, slotRawSymbol(a)->u.index); return errNone; } int prSymbol_SpecialIndex(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetInt(a, slotRawSymbol(a)->specialIndex); return errNone; } int prSymbol_AsFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char* str = slotRawSymbol(a)->name; SetFloat(a, atof(str)); return errNone; } // following function lifted from liblo: http://sourceforge.net/projects/liblo/ /* Open SoundControl kit in C++ */ /* Copyright (C) 2002-2004 libOSC++ contributors. See AUTHORS */ /* */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* */ /* This library 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 */ /* Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* */ /* For questions regarding this program contact */ /* Daniel Holth <dholth@fastmail.fm> or visit */ /* http://wiretap.stetson.edu/ */ /* In the sprit of the public domain, my modifications to this file are also */ /* dedicated to the public domain. Daniel Holth, Oct. 2004 */ /* ChangeLog: * * 2004-10-29 Import, convert to C++, begin OSC syntax changes. -dwh * OSC syntax changes are now working, needs more testing. * */ // Original header and syntax: /* * robust glob pattern matcher * ozan s. yigit/dec 1994 * public domain * * glob patterns: * * matches zero or more characters * ? matches any single character * [set] matches any character in the set * [^set] matches any character NOT in the set * where a set is a group of characters or ranges. a range * is written as two characters separated with a hyphen: a-z denotes * all characters between a to z inclusive. * [-set] set matches a literal hypen and any character in the set * []set] matches a literal close bracket and any character in the set * * char matches itself except where char is '*' or '?' or '[' * \char matches char, including any pattern character * * examples: * a*c ac abc abbc ... * a?c acc abc aXc ... * a[a-z]c aac abc acc ... * a[-a-z]c a-c aac abc ... * * $Log$ * Revision 1.1 2004/11/19 23:00:57 theno23 * Added lo_send_timestamped * * Revision 1.3 1995/09/14 23:24:23 oz * removed boring test/main code. * * Revision 1.2 94/12/11 10:38:15 oz * cset code fixed. it is now robust and interprets all * variations of cset [i think] correctly, including [z-a] etc. * * Revision 1.1 94/12/08 12:45:23 oz * Initial revision */ #ifndef lo_NEGATE # define lo_NEGATE '!' #endif #ifndef lo_true # define lo_true 1 #endif #ifndef lo_false # define lo_false 0 #endif inline int lo_pattern_match(const char* str, const char* p) { int negate; int match; char c; while (*p) { if (!*str && *p != '*') return lo_false; switch (c = *p++) { case '*': while (*p == '*' && *p != '/') p++; if (!*p) return lo_true; // if (*p != '?' && *p != '[' && *p != '\\') if (*p != '?' && *p != '[' && *p != '{') while (*str && *p != *str) str++; while (*str) { if (lo_pattern_match(str, p)) return lo_true; str++; } return lo_false; case '?': if (*str) break; return lo_false; /* * set specification is inclusive, that is [a-z] is a, z and * everything in between. this means [z-a] may be interpreted * as a set that contains z, a and nothing in between. */ case '[': if (*p != lo_NEGATE) negate = lo_false; else { negate = lo_true; p++; } match = lo_false; while (!match && (c = *p++)) { if (!*p) return lo_false; if (*p == '-') { /* c-c */ if (!*++p) return lo_false; if (*p != ']') { if (*str == c || *str == *p || (*str > c && *str < *p)) match = lo_true; } else { /* c-] */ if (*str >= c) match = lo_true; break; } } else { /* cc or c] */ if (c == *str) match = lo_true; if (*p != ']') { if (*p == *str) match = lo_true; } else break; } } if (negate == match) return lo_false; /* * if there is a match, skip past the cset and continue on */ while (*p && *p != ']') p++; if (!*p++) /* oops! */ return lo_false; break; /* * {astring,bstring,cstring} */ case '{': { // *p is now first character in the {brace list} const char* place = str; // to backtrack const char* remainder = p; // to forwardtrack // find the end of the brace list while (*remainder && *remainder != '}') remainder++; if (!*remainder++) /* oops! */ return lo_false; c = *p++; while (c) { if (c == ',') { if (lo_pattern_match(str, remainder)) { return lo_true; } else { // backtrack on test string str = place; // continue testing, // skip comma if (!*p++) // oops return lo_false; } } else if (c == '}') { // continue normal pattern matching if (!*p && !*str) return lo_true; str--; // str is incremented again below break; } else if (c == *str) { str++; if (!*str && *remainder) return lo_false; } else { // skip to next comma str = place; while (*p != ',' && *p != '}' && *p) p++; if (*p == ',') p++; else if (*p == '}') { return lo_false; } } c = *p++; } } break; /* Not part of OSC pattern matching case '\\': if (*p) c = *p++; */ default: if (c != *str) return lo_false; break; } str++; } return !*str; } // end: following function lifted from liblo int prSymbol_matchOSCPattern(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; a = g->sp - 1; b = g->sp; if (!IsSym(a) || !IsSym(b)) return errWrongType; // int32 alen = slotRawSymbol(a)->length; // int32 blen = slotRawSymbol(b)->length; // length = sc_min(alen, blen); if (lo_pattern_match(slotRawSymbol(a)->name, slotRawSymbol(b)->name)) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prSymbol_isMap(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char* str = slotRawSymbol(a)->name; if (strlen(str) > 1 && (str[0] == 'a' || str[0] == 'c') && str[1] >= '0' && str[1] <= '9') SetTrue(a); else SetFalse(a); return errNone; } void initSymbolPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_SymbolIsPrefix", prSymbolIsPrefix, 2, 0); definePrimitive(base, index++, "_SymbolClass", prSymbolClass, 1, 0); definePrimitive(base, index++, "_SymbolIsClassName", prSymbolIsClassName, 1, 0); definePrimitive(base, index++, "_SymbolIsMetaClassName", prSymbolIsMetaClassName, 1, 0); definePrimitive(base, index++, "_Symbol_IsIdentifier", prSymbol_IsIdentifier, 1, 0); definePrimitive(base, index++, "_Symbol_IsBinaryOp", prSymbol_IsBinaryOp, 1, 0); definePrimitive(base, index++, "_SymbolIsSetter", prSymbolIsSetter, 1, 0); definePrimitive(base, index++, "_SymbolAsSetter", prSymbolAsSetter, 1, 0); definePrimitive(base, index++, "_SymbolAsGetter", prSymbolAsGetter, 1, 0); definePrimitive(base, index++, "_Symbol_AsInteger", prSymbol_AsInteger, 1, 0); definePrimitive(base, index++, "_Symbol_PrimitiveIndex", prSymbol_PrimitiveIndex, 1, 0); definePrimitive(base, index++, "_Symbol_SpecialIndex", prSymbol_SpecialIndex, 1, 0); definePrimitive(base, index++, "_Symbol_AsFloat", prSymbol_AsFloat, 1, 0); definePrimitive(base, index++, "_Symbol_matchOSCPattern", prSymbol_matchOSCPattern, 2, 0); definePrimitive(base, index++, "_Symbol_IsMap", prSymbol_isMap, 1, 0); }
16,995
C++
.cpp
470
27.621277
110
0.515841
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
29,872
SC_ComPort.cpp
supercollider_supercollider/lang/LangPrimSource/SC_ComPort.cpp
/* 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_BoundsMacros.h" #include "SC_ComPort.h" #include "SC_Endian.h" #include <ctype.h> #include <stdexcept> #include <stdarg.h> #include "SCBase.h" #include <cerrno> #include "PyrSched.h" #include "SC_Lock.h" #include "SC_Msg.h" #include "SC_ReplyImpl.hpp" #include <boost/asio.hpp> #include <boost/typeof/typeof.hpp> #define scprintf printf #include "SC_OscUtils.hpp" #undef scprintf void ProcessOSCPacket(std::unique_ptr<OSC_Packet> inPacket, int inPortNum, double time); void ProcessRawMessage(std::unique_ptr<char[]> inData, size_t inSize, ReplyAddress& replyAddress, int inPortNum, double time); ////////////////////////////////////////////////////////////////////////////////////////////////////////// SC_Thread gAsioThread; boost::asio::io_service ioService; static void asioFunction() { boost::asio::io_service::work work(ioService); ioService.run(); } void startAsioThread() { SC_Thread asioThread(&asioFunction); gAsioThread = std::move(asioThread); } void stopAsioThread() { ioService.stop(); gAsioThread.join(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// // One MessageHandler<> class for each HandlerType. // The signature of handleMessage can differ between handler types, so templatizing the class // allows us to specify a message handler func using e.g. MessageHandler<HandlerType::OSC>::handleMessage template <HandlerType H> struct MessageHandler {}; template <> struct MessageHandler<HandlerType::OSC> { static void handleMessage(Protocol protocol, int replySocket, const boost::asio::ip::address& replyAddress, int replyPort, std::unique_ptr<char[]> data, size_t dataSize, int localPort) { const double timeReceived = elapsedTime(); // get time now to minimize jitter due to lang load auto packet = std::make_unique<OSC_Packet>(OSC_Packet { std::move(data), dataSize, { replyAddress, protocol, replyPort, replySocket, nullptr, // mReplyFunc nullptr // mReplyData } }); ProcessOSCPacket(std::move(packet), localPort, timeReceived); } }; template <> struct MessageHandler<HandlerType::Raw> { static void handleMessage(Protocol protocol, int replySocket, const boost::asio::ip::address& replyAddress, int replyPort, std::unique_ptr<char[]> data, size_t dataSize, int localPort) { const double timeReceived = elapsedTime(); // get time now to minimize jitter due to lang load ReplyAddress addrObject; addrObject.mProtocol = protocol; addrObject.mAddress = replyAddress; addrObject.mSocket = replySocket; addrObject.mPort = replyPort; addrObject.mReplyFunc = nullptr; addrObject.mReplyData = nullptr; ProcessRawMessage(std::move(data), dataSize, addrObject, localPort, timeReceived); } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace Detail { TCPConnection::TCPConnection(boost::asio::io_service& ioService, int portNum, HandlerType handlerType): mSocket(ioService), mOSCMsgLength(0), mPortNum(portNum) { initHandler(handlerType); } void TCPConnection::initHandler(HandlerType handlerType) { switch (handlerType) { case HandlerType::OSC: { using Handler = MessageHandler<HandlerType::OSC>; mHandleFunc = [this](auto data, auto dataSize) { const int replyPort = 0; const boost::asio::ip::address replyAddress; Handler::handleMessage(kTCP, mSocket.native_handle(), replyAddress, replyPort, std::move(data), dataSize, mPortNum); }; return; } case HandlerType::Raw: { using Handler = MessageHandler<HandlerType::Raw>; mHandleFunc = [this](auto data, auto dataSize) { const int replyPort = 0; const boost::asio::ip::address replyAddress; Handler::handleMessage(kTCP, mSocket.native_handle(), replyAddress, replyPort, std::move(data), dataSize, mPortNum); }; return; } } } void TCPConnection::start() { namespace ba = boost::asio; ba::async_read(mSocket, ba::buffer(&mOSCMsgLength, sizeof(mOSCMsgLength)), [receiver = shared_from_this()](auto error, auto bytesTransferred) { receiver->handleLengthReceived(error, bytesTransferred); }); } void TCPConnection::handleLengthReceived(const boost::system::error_code& error, size_t bytes_transferred) { if (error) { return; } namespace ba = boost::asio; // msglen is in network byte order mOSCMsgLength = sc_ntohl(mOSCMsgLength); mData = std::make_unique<char[]>(mOSCMsgLength); ba::async_read(mSocket, ba::buffer(mData.get(), mOSCMsgLength), [receiver = shared_from_this()](auto error, auto bytesReceived) { receiver->handleMsgReceived(error, bytesReceived); }); } void TCPConnection::handleMsgReceived(const boost::system::error_code& error, size_t bytes_transferred) { if (error) { mData.reset(); return; } assert(bytes_transferred == mOSCMsgLength); mHandleFunc(std::move(mData), mOSCMsgLength); start(); } } // namespace Detail ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace InPort { UDP::UDP(int inPortNum, HandlerType handlerType, int portsToCheck): mPortNum(inPortNum), mUdpSocket(ioService) { using namespace boost::asio; BOOST_AUTO(protocol, ip::udp::v4()); mUdpSocket.open(protocol); for (int offset = 0; offset != portsToCheck; ++offset) { try { mUdpSocket.bind(ip::udp::endpoint(protocol, inPortNum + offset)); mPortNum = inPortNum + offset; break; } catch (std::exception const&) { if (offset == (portsToCheck - 1)) throw std::runtime_error("unable to bind udp socket\n"); } } boost::asio::socket_base::send_buffer_size option(65536); mUdpSocket.set_option(option); initHandler(handlerType); startReceiveUDP(); } void UDP::initHandler(HandlerType handlerType) { switch (handlerType) { case HandlerType::OSC: { using Handler = MessageHandler<HandlerType::OSC>; mHandleFunc = [this](auto data, auto dataSize) { Handler::handleMessage(kUDP, mUdpSocket.native_handle(), mRemoteEndpoint.address(), mRemoteEndpoint.port(), std::move(data), dataSize, mPortNum); }; return; } case HandlerType::Raw: { using Handler = MessageHandler<HandlerType::Raw>; mHandleFunc = [this](auto data, auto dataSize) { Handler::handleMessage(kUDP, mUdpSocket.native_handle(), mRemoteEndpoint.address(), mRemoteEndpoint.port(), std::move(data), dataSize, mPortNum); }; return; } } } void UDP::startReceiveUDP() { using namespace boost; mUdpSocket.async_receive_from( asio::buffer(mRecvBuffer), mRemoteEndpoint, [this](auto error, auto bytesTransferred) { handleReceivedUDP(error, bytesTransferred); }); } void UDP::handleReceivedUDP(const boost::system::error_code& error, std::size_t bytesTransferred) { if (error == boost::asio::error::operation_aborted) return; /* we're done */ if (error == boost::asio::error::connection_refused) { // avoid windows error message startReceiveUDP(); return; } if (error) { printf("(sclang) SC_UdpInPort: received error - %s\n", error.message().c_str()); startReceiveUDP(); return; } std::unique_ptr<char[]> data(new char[bytesTransferred]); memcpy(data.get(), mRecvBuffer.data(), bytesTransferred); mHandleFunc(std::move(data), bytesTransferred); startReceiveUDP(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// UDPCustom::UDPCustom(int inPortNum, HandlerType handlerType): UDP(inPortNum, handlerType, 1) {} ////////////////////////////////////////////////////////////////////////////////////////////////////////// TCP::TCP(int inPortNum, int inMaxConnections, int inBacklog, HandlerType handlerType): mAcceptor(ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), inPortNum)), mPortNum(inPortNum), mHandlerType(handlerType) { // FIXME: handle max connections // FIXME: backlog??? startAccept(); } void TCP::startAccept() { const auto newConnection = std::make_shared<Detail::TCPConnection>(ioService, mPortNum, mHandlerType); mAcceptor.async_accept(newConnection->getSocket(), [this, newConnection](auto error) { handleAccept(newConnection, error); }); } void TCP::handleAccept(Detail::TCPConnection::pointer newConnection, const boost::system::error_code& error) { if (!error) newConnection->start(); startAccept(); } } // namespace InPort ////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace OutPort { TCP::TCP(unsigned long inAddress, int inPort, HandlerType handlerType, ClientNotifyFunc notifyFunc, void* clientData): mSocket(ioService), mEndpoint(boost::asio::ip::address_v4(inAddress), inPort), mClientNotifyFunc(notifyFunc), mClientData(clientData) { using namespace boost::asio; boost::system::error_code error; ip::tcp::no_delay noDelayOption(true); mSocket.set_option(noDelayOption, error); mSocket.connect(mEndpoint); initHandler(handlerType); startReceive(); } void TCP::initHandler(HandlerType handlerType) { switch (handlerType) { case HandlerType::OSC: using Handler = MessageHandler<HandlerType::OSC>; mHandleFunc = [this](auto data, auto dataSize) { Handler::handleMessage(kTCP, mSocket.native_handle(), mSocket.remote_endpoint().address(), mSocket.remote_endpoint().port(), std::move(data), dataSize, mSocket.local_endpoint().port()); }; } } void TCP::startReceive() { namespace ba = boost::asio; ba::async_read(mSocket, ba::buffer(&mOSCMsgLength, sizeof(mOSCMsgLength)), [this](auto error, auto bytesTransferred) { handleLengthReceived(error, bytesTransferred); }); } void TCP::handleLengthReceived(const boost::system::error_code& error, size_t bytes_transferred) { if (error == boost::asio::error::connection_aborted) { if (mClientNotifyFunc) (*mClientNotifyFunc)(mClientData); } if (error) return; // msglen is in network byte order mOSCMsgLength = sc_ntohl(mOSCMsgLength); mData = std::make_unique<char[]>(mOSCMsgLength); namespace ba = boost::asio; ba::async_read(mSocket, ba::buffer(mData.get(), mOSCMsgLength), [this](auto error, auto bytesTransferred) { handleMsgReceived(error, bytesTransferred); }); } void TCP::handleMsgReceived(const boost::system::error_code& error, size_t bytes_transferred) { double timeReceived = elapsedTime(); // get time now to minimize jitter due to lang load if (error == boost::asio::error::connection_aborted) { if (mClientNotifyFunc) (*mClientNotifyFunc)(mClientData); } if (error) { mData.reset(); return; } // The mOSCMsgLength read from the message header should match the actual number of bytes available. assert(bytes_transferred == mOSCMsgLength); mHandleFunc(std::move(mData), mOSCMsgLength); startReceive(); } int TCP::Close() { boost::system::error_code error; mSocket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); mSocket.close(); if (error) { if (error != boost::asio::error::not_connected) { ::error("Socket shutdown failed, closed socket anyway. %s", error.message().c_str()); return errFailed; } } return errNone; } } // namespace OutPort
13,588
C++
.cpp
306
36.522876
119
0.617308
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
29,873
PyrSerialPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrSerialPrim.cpp
/* Serial port support. Copyright (c) 2006 stefan kersten. ==================================================================== 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 _WIN32 # include <termios.h> // TIOCEXCL # include <sys/ioctl.h> // ioctl # include <errno.h> // errno # include <system_error> // system_error, error_code, error_category #endif // _WIN32 #include <atomic> #include <stdexcept> #include <sstream> #include "PyrKernel.h" #include "PyrPrimitive.h" #include "PyrSched.h" #include "SCBase.h" #include "SC_Lock.h" #include <boost/asio/use_future.hpp> #include <boost/asio.hpp> #include <boost/bind/bind.hpp> #include <boost/cstdint.hpp> #include <boost/lockfree/spsc_queue.hpp> using boost::uint8_t; using boost::asio::serial_port; extern boost::asio::io_service ioService; // defined in SC_ComPort.cpp /** * \brief Serial port abstraction * * Uses SerialPort::Options for configuration. The port is opened on construction, and destruction * releases all resourses by canceling outstanding TX/RX requests and closing the port. * This class polls the port on a separate thread and immediately reads available data into an * internal buffer. */ class SerialPort { public: // 7, not 6 - the last two options passed in are condensed into flow_control static const int kNumOptions = 7; static const int kBufferSize = 8192; /// Type of the underlying FIFO buffer. using FIFO = boost::lockfree::spsc_queue<uint8_t, boost::lockfree::capacity<kBufferSize>>; /** * \brief Serial port configuration options. * * \note The two SuperCollider options \c xonxoff and \c crtscts are used together to set * Options::flow_control. */ struct Options { /// Whether to request exclusive access to this port. Not implemented on Windows. bool exclusive = false; serial_port::baud_rate baudrate { 9600 }; /// Corresponds to \c databits in SC code serial_port::character_size charsize { 8 }; /// Number of stop bits to send. In SC code, true = 2, false = 1 serial_port::stop_bits::type stop_bits { serial_port::stop_bits::two }; serial_port::parity::type parity { serial_port::parity::none }; /// Whether to use XON/XOFF signals (software), RTS/CTS signals (hardware), or neither. serial_port::flow_control::type flow_control { serial_port::flow_control::hardware }; }; static PyrSymbol* s_dataAvailable; static PyrSymbol* s_doneAction; public: /** * \brief Opens port, sets options, and starts polling thread * * May throw \c std::system_error or \c boost::system::system_error during creation if opening * the port fails or if setting options fails. */ SerialPort(PyrObject* obj, const char* serialport, const Options& options): m_obj(obj), m_port(ioService, serialport), m_options(options), m_rxErrors(0) { using namespace boost::asio; m_port.set_option(options.baudrate); m_port.set_option(serial_port::parity(options.parity)); m_port.set_option(options.charsize); m_port.set_option(serial_port::stop_bits(options.stop_bits)); setFlowControl(options.flow_control); setExclusive(options.exclusive); m_readThread = SC_Thread { &SerialPort::doRead, this }; } ~SerialPort() { m_readThread.join(); } const Options& options() const { return m_options; } /// Blocking single-byte write. Returns whether the write was successful. bool put(uint8_t byte) { boost::system::error_code ec {}; m_port.write_some(boost::asio::buffer(&byte, sizeof(byte)), ec); return !ec; } /// Non-blocking single-byte read. Returns whether the read was successful. bool get(uint8_t* byte) { uint8_t ret; bool success = m_rxfifo.pop(ret); if (!success) return false; *byte = ret & 0xFF; return true; } /// The number of read errors since the last time this method was called. /** * A read error occurs when the FIFO is too full to receive data; the extra bytes are lost. */ int rxErrorsSinceLastQuery() { return m_rxErrors.exchange(0); } /// Cancels all outstanding reads and writes and closes the port. void stop() { m_port.cancel(); m_port.close(); } private: /// Sets this serial port to exclusive mode. Has no effect on Windows. Throws \c system_error /// on failure. void setExclusive(bool); /// Sets flow control behavior. Throws \c system_error if mode is not supported or if failure /// occurs during set. void setFlowControl(serial_port::flow_control::type control); /// Calls a one-arg SuperCollider command on this object. void runCommand(PyrSymbol* cmd) { gLangMutex.lock(); if (m_obj) { VMGlobals* g = gMainVMGlobals; g->canCallOS = true; ++g->sp; SetObject(g->sp, m_obj); runInterpreter(g, cmd, 1); g->canCallOS = false; } gLangMutex.unlock(); } /// Runs the doneAction callback function on the SuperCollider \c SerialPort object. void doneAction() { runCommand(s_doneAction); } /// Notifies the object that data is available, unblocking any blocking reads. void dataAvailable() { runCommand(s_dataAvailable); } /// Reads endlessly from port until an error is encountered, at which point the SerialPort /// object's `doneAction` runs. void doRead() { auto const&& buf = boost::asio::buffer(m_rxbuffer, kBufferSize); while (true) { auto txFuture = m_port.async_read_some(buf, boost::asio::use_future); try { // blocks until read completes auto bytesTransferred = txFuture.get(); for (std::size_t index = 0; index != bytesTransferred; ++index) { uint8_t byte = m_rxbuffer[index]; bool putSuccessful = m_rxfifo.push(byte); if (!putSuccessful) m_rxErrors++; } if (bytesTransferred > 0) { dataAvailable(); } } catch (const boost::system::system_error& e) { // TODO: pass info on error to sclang? ignore spurious errors? doneAction(); return; } } } PyrObject* m_obj; ///< Language object representing this port. boost::asio::serial_port m_port; ///< Port object. Options m_options; ///< Serial interface options. SC_Thread m_readThread; ///< Polling thread. /// Count of read errors since last query std::atomic<int> m_rxErrors; /// I/O buffer FIFO m_rxfifo; /// Temp buffer for reads uint8_t m_rxbuffer[kBufferSize]; }; PyrSymbol* SerialPort::s_dataAvailable = nullptr; PyrSymbol* SerialPort::s_doneAction = nullptr; void SerialPort::setFlowControl(serial_port::flow_control::type control) { /* FIXME backported from 3.9 impl -- boost.asio doesn't correctly detect support for these features * on macOS and possibly Linux (https://github.com/boostorg/asio/issues/65). Remove this if that issue * is ever solved and we upgrade to that as minimum version. */ #if !defined(_WIN32) && (!defined(_POSIX_C_SOURCE) || defined(__USE_MISC)) int fd = m_port.native_handle(); termios toptions; if (::tcgetattr(fd, &toptions) < 0) { throw std::system_error(std::error_code(errno, std::system_category())); } if (control == serial_port::flow_control::hardware) { toptions.c_cflag &= ~CRTSCTS; } else { toptions.c_cflag |= CRTSCTS; } if (control == serial_port::flow_control::hardware) { toptions.c_iflag |= (IXON | IXOFF | IXANY); } else { toptions.c_iflag &= ~(IXON | IXOFF | IXANY); } if (::tcsetattr(fd, TCSAFLUSH, &toptions) < 0) { throw std::system_error(std::error_code(errno, std::system_category())); } #else // !_WIN32 && ( !_POSIX_C_SOURCE || __USE_MISC ) m_port.set_option(serial_port::flow_control(control)); #endif // !_WIN32 && ( !_POSIX_C_SOURCE || __USE_MISC ) } void SerialPort::setExclusive(bool b) { #ifndef _WIN32 if (!b) { return; } int fd = m_port.native_handle(); if (ioctl(fd, TIOCEXCL) == -1) { throw std::system_error(std::error_code(errno, std::system_category())); } #endif // _WIN32 } // ================================================================================================ // helpers static SerialPort* getSerialPort(PyrSlot* slot) { if (NotPtr(&slotRawObject(slot)->slots[0])) return nullptr; return (SerialPort*)slotRawPtr(&slotRawObject(slot)->slots[0]); } /// Translates between SC parity IDs and boost::asio::serial_port parity types. static serial_port::parity::type asParityType(int i) { using parity = serial_port::parity; switch (i) { case 0: return parity::none; case 1: return parity::even; case 2: return parity::odd; default: printf("*** WARNING: SerialPort: unknown parity: %d. Defaulting to none.\n", i); return parity::none; } } /// Translates between SC xonxoff/crtscts args and boost::asio::serial_port flow_control types. /** * \note Throws std::runtime_error if both arguments are true. */ static serial_port::flow_control::type asFlowControlType(bool hardware, bool software) { using flow_control = serial_port::flow_control; if (hardware && software) { throw std::runtime_error("SerialPort: xonxoff and crtscts cannot both be true"); } else if (hardware) { return flow_control::hardware; } else if (software) { return flow_control::software; } else { return flow_control::none; } } // ================================================================================================ // primitives static int prSerialPort_Open(struct VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1 - SerialPort::kNumOptions; int err; PyrSlot* self = args + 0; if (getSerialPort(self)) return errFailed; char portName[PATH_MAX]; err = slotStrVal(args + 1, portName, sizeof(portName)); if (err) return err; SerialPort::Options options {}; SerialPort* port = nullptr; options.exclusive = IsTrue(args + 2); int baudrate; err = slotIntVal(args + 3, &baudrate); if (err) return err; options.baudrate = serial_port::baud_rate { static_cast<unsigned int>(baudrate) }; int charsize; err = slotIntVal(args + 4, &charsize); if (err) return err; options.charsize = serial_port::character_size { static_cast<unsigned int>(charsize) }; options.stop_bits = IsTrue(args + 5) ? serial_port::stop_bits::two : serial_port::stop_bits::one; int parity; err = slotIntVal(args + 6, &parity); if (err) return err; options.parity = asParityType(parity); // crtscts = use hardware signals for control flow bool useHardware = IsTrue(args + 7); // xonxoff = use XON/XOFF message bytes for control flow bool useSoftware = IsTrue(args + 8); options.flow_control = asFlowControlType(useHardware, useSoftware); try { port = new SerialPort(slotRawObject(self), portName, options); } catch (boost::system::system_error& e) { delete port; if (e.code().value() == boost::system::errc::no_such_file_or_directory) { throw std::runtime_error(std::string("SerialPort: port '") + portName + "' does not exist"); } else { throw; } } catch (std::exception& e) { delete port; // TODO: check error types to provide better messages, such as when port doesn't exist throw; } SetPtr(slotRawObject(self)->slots + 0, port); return errNone; } /** \brief Stop a SerialPort object. * * When `close` is triggered, a complex sequence of events happens: * 1. Port is closed and SerialPort object is marked as closed * 2. This SC thread eventually yields, allowing the SerialPort's doneAction to run via read thread * 3. That doneAction causes a deferred call to `prSerialPort_Cleanup` and then yields * 4. `Cleanup` sets the dataptr to nil and destroys the C++ object, causing the read thread to join */ static int prSerialPort_Close(struct VMGlobals* g, int numArgsPushed) { PyrSlot* self = g->sp; SerialPort* port = getSerialPort(self); if (!port) return errFailed; port->stop(); return errNone; } static int prSerialPort_Cleanup(struct VMGlobals* g, int numArgsPushed) { PyrSlot* self = g->sp; SerialPort* port = getSerialPort(self); if (!port) return errFailed; delete port; SetNil(slotRawObject(self)->slots + 0); return errNone; } static int prSerialPort_Next(struct VMGlobals* g, int numArgsPushed) { PyrSlot* self = g->sp; SerialPort* port = getSerialPort(self); if (!port) return errFailed; uint8_t byte; if (port->get(&byte)) { SetInt(self, byte); } else { SetNil(self); } return errNone; } static int prSerialPort_Put(struct VMGlobals* g, int numArgsPushed) { PyrSlot* args = g->sp - 1; PyrSlot* self = args + 0; SerialPort* port = getSerialPort(self); if (!port) return errFailed; PyrSlot* src = args + 1; int val; if (IsChar(src)) { val = slotRawChar(src); } else { int err = slotIntVal(src, &val); if (err) return err; } bool res = port->put(val & 0xFF); SetBool(self, res); return errNone; } static int prSerialPort_RXErrors(struct VMGlobals* g, int numArgsPushed) { PyrSlot* self = g->sp; SerialPort* port = getSerialPort(self); if (!port) return errFailed; SetInt(self, port->rxErrorsSinceLastQuery()); return errNone; } void initSerialPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_SerialPort_Open", prSerialPort_Open, 2 + SerialPort::kNumOptions, 0); definePrimitive(base, index++, "_SerialPort_Close", prSerialPort_Close, 1, 0); definePrimitive(base, index++, "_SerialPort_Next", prSerialPort_Next, 1, 0); definePrimitive(base, index++, "_SerialPort_Put", prSerialPort_Put, 2, 0); definePrimitive(base, index++, "_SerialPort_RXErrors", prSerialPort_RXErrors, 1, 0); definePrimitive(base, index++, "_SerialPort_Cleanup", prSerialPort_Cleanup, 1, 0); SerialPort::s_dataAvailable = getsym("prDataAvailable"); SerialPort::s_doneAction = getsym("prDoneAction"); }
15,664
C++
.cpp
393
33.826972
106
0.645257
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
29,874
PyrBitPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrBitPrim.cpp
/* 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 */ /* Primitives for some bit operations. */ #include "PyrPrimitive.h" #include "VMGlobals.h" #include "clz.h" int prNumBits(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetRaw(a, NUMBITS(slotRawInt(a))); return errNone; } int prLog2Ceil(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetRaw(a, LOG2CEIL(slotRawInt(a))); return errNone; } int prCLZ(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetRaw(a, CLZ(slotRawInt(a))); return errNone; } int prCTZ(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetRaw(a, CTZ(slotRawInt(a))); return errNone; } int prNextPowerOfTwo(VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetRaw(a, NEXTPOWEROFTWO(slotRawInt(a))); return errNone; } int prIsPowerOfTwo(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; SetBool(a, ISPOWEROFTWO(slotRawInt(a))); return errNone; } int prBinaryGrayCode(VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetRaw(a, GRAYCODE(slotRawInt(a))); return errNone; } int prSetBit(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; int32 bit, mask; int err = slotIntVal(b, &bit); if (err) return err; bit = bit & 31; mask = 1L << bit; if (IsFalse(c)) { SetRaw(a, slotRawInt(a) & ~mask); } else { SetRaw(a, slotRawInt(a) | mask); } return errNone; } int prHammingDistance(VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (NotInt(a) || NotInt(b)) return errWrongType; int aInt = slotRawInt(a); int bInt = slotRawInt(b); int count = 0, mask = 1; for (int i = 0; i < 32; i++) { if ((aInt & mask) != (bInt & mask)) count = count + 1; mask = mask << 1; } SetRaw(a, count); return errNone; } void initBitPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_NextPowerOfTwo", prNextPowerOfTwo, 1, 0); definePrimitive(base, index++, "_IsPowerOfTwo", prIsPowerOfTwo, 1, 0); definePrimitive(base, index++, "_CLZ", prCLZ, 1, 0); definePrimitive(base, index++, "_CTZ", prCTZ, 1, 0); definePrimitive(base, index++, "_NumBits", prNumBits, 1, 0); definePrimitive(base, index++, "_Log2Ceil", prLog2Ceil, 1, 0); definePrimitive(base, index++, "_SetBit", prSetBit, 3, 0); definePrimitive(base, index++, "_BinaryGrayCode", prBinaryGrayCode, 1, 0); definePrimitive(base, index++, "_HammingDistance", prHammingDistance, 2, 0); }
3,536
C++
.cpp
105
29.180952
81
0.664806
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
29,875
PyrSched.cpp
supercollider_supercollider/lang/LangPrimSource/PyrSched.cpp
/* 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 "PyrKernel.h" #include "PyrSched.h" #include "GC.h" #include "PyrPrimitive.h" #include "PyrSymbol.h" #ifdef __APPLE__ # include <CoreAudio/HostTime.h> #endif #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits> #include <functional> #if defined(__APPLE__) || defined(__linux__) # include <pthread.h> #endif #include "SCBase.h" #include "SC_Lock.h" #include "SC_Clock.hpp" #include "SC_LinkClock.hpp" #include <boost/sync/semaphore.hpp> #include <boost/sync/support/std_chrono.hpp> // FIXME: These includes needs to be last on Windows, otherwise Ableton build breaks // (Windows header include ordering dependencies) #include "SC_Win32Utils.h" #ifdef _MSC_VER # include "wintime.h" #else # include <sys/time.h> #endif static const double dInfinity = std::numeric_limits<double>::infinity(); void runAwakeMessage(VMGlobals* g); bool addheap(VMGlobals* g, PyrObject* heapArg, double schedtime, PyrSlot* task) { PyrHeap* heap = (PyrHeap*)heapArg; #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif if (heap->size >= ARRAYMAXINDEXSIZE(heap)) return false; assert(heap->size); // post("->addheap\n"); // dumpheap(heapArg); /* parent and sibling in the heap, not in the task hierarchy */ int mom = heap->size - 1; PyrSlot* pme = heap->slots + mom; int stabilityCount = slotRawInt(&heap->count); SetRaw(&heap->count, stabilityCount + 1); for (; mom > 0;) { /* percolate up heap */ int newMom = ((mom - 3) / 2); mom = newMom - newMom % 3; /// LATER: we could avoid the division by using 4 slots per element PyrSlot* pmom = heap->slots + mom; if (schedtime < slotRawFloat(pmom)) { assert(slotRawInt(pmom + 2) < stabilityCount); slotCopy(&pme[0], &pmom[0]); slotCopy(&pme[1], &pmom[1]); slotCopy(&pme[2], &pmom[2]); pme = pmom; } else break; } SetFloat(&pme[0], schedtime); slotCopy(&pme[1], task); SetInt(&pme[2], stabilityCount); g->gc->GCWrite(heap, task); heap->size += 3; #ifdef GC_SANITYCHECK g->gc->SanityCheck(); #endif // dumpheap(heapArg); // post("<-addheap %g\n", schedtime); return true; } bool lookheap(PyrObject* heap, double* schedtime, PyrSlot* task) { if (heap->size > 1) { *schedtime = slotRawFloat(&heap->slots[0]); slotCopy(task, &heap->slots[1]); return true; } else return false; } bool getheap(VMGlobals* g, PyrObject* heapArg, double* schedtime, PyrSlot* task) { PyrHeap* heap = (PyrHeap*)heapArg; PyrGC* gc = g->gc; bool isPartialScanObj = gc->IsPartialScanObject(heapArg); assert(heap->size); // post("->getheap\n"); // dumpheap(heapArg); if (heap->size > 1) { *schedtime = slotRawFloat(&heap->slots[0]); slotCopy(task, &heap->slots[1]); heap->size -= 3; int size = heap->size - 1; slotCopy(&heap->slots[0], &heap->slots[size]); slotCopy(&heap->slots[1], &heap->slots[size + 1]); slotCopy(&heap->slots[2], &heap->slots[size + 2]); /* parent and sibling in the heap, not in the task hierarchy */ int mom = 0; int me = 3; PyrSlot* pmom = heap->slots + mom; PyrSlot* pme = heap->slots + me; PyrSlot* pend = heap->slots + size; double timetemp = slotRawFloat(&pmom[0]); int stabilityCountTemp = slotRawInt(&pmom[2]); PyrSlot tasktemp; slotCopy(&tasktemp, &pmom[1]); for (; pme < pend;) { /* demote heap */ if (pme + 3 < pend && ((slotRawFloat(&pme[0]) > slotRawFloat(&pme[3])) || ((slotRawFloat(&pme[0]) == slotRawFloat(&pme[3])) && (slotRawInt(&pme[2]) > slotRawInt(&pme[5]))))) { me += 3; pme += 3; } if (timetemp > slotRawFloat(&pme[0]) || (timetemp == slotRawFloat(&pme[0]) && stabilityCountTemp > slotRawInt(&pme[2]))) { slotCopy(&pmom[0], &pme[0]); slotCopy(&pmom[1], &pme[1]); slotCopy(&pmom[2], &pme[2]); if (isPartialScanObj) { gc->GCWriteBlack(pmom + 1); } pmom = pme; me = ((mom = me) * 2) + 3; pme = heap->slots + me; } else break; } SetRaw(&pmom[0], timetemp); slotCopy(&pmom[1], &tasktemp); SetRaw(&pmom[2], stabilityCountTemp); if (isPartialScanObj) gc->GCWriteBlack(pmom + 1); if (size == 0) SetInt(&heap->count, 0); // dumpheap(heapArg); // post("<-getheap true\n"); return true; } else { // post("<-getheap false\n"); return false; } } void offsetheap(VMGlobals* g, PyrObject* heap, double offset) { long i; for (i = 0; i < heap->size; i += 2) { SetRaw(&heap->slots[i], slotRawFloat(&heap->slots[i]) + offset); // post("%3d %9.2f %9.2f\n", i>>1, heap->slots[i].uf, offset); } } void dumpheap(PyrObject* heapArg) { PyrHeap* heap = (PyrHeap*)heapArg; double mintime = slotRawFloat(&heap->slots[0]); int count = slotRawFloat(&heap->slots[2]); int heapSize = heap->size - 1; post("SCHED QUEUE (%d)\n", heapSize); for (int i = 0; i < heapSize; i += 3) { post("%3d(%3d) %9.2f %p %d\n", i / 3, i, slotRawFloat(&heap->slots[i]), slotRawObject(&heap->slots[i + 1]), slotRawInt(&heap->slots[i + 2])); if ((slotRawFloat(&heap->slots[i]) < mintime) || (slotRawFloat(&heap->slots[i]) == mintime && slotRawInt(&heap->slots[i + 2]) < count)) post("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"); } } bool gRunSched = false; static std::thread gSchedThread; static std::thread gResyncThread; static boost::sync::semaphore gResyncThreadSemaphore; std::condition_variable_any gSchedCond; std::timed_mutex gLangMutex; int64 gHostOSCoffset = 0; int64 gHostStartNanos = 0; int64 gElapsedOSCoffset = 0; const int32 kSECONDS_FROM_1900_to_1970 = (int32)2208988800UL; /* 17 leap years */ static void syncOSCOffsetWithTimeOfDay(); void resyncThread(); // Use the highest resolution clock available for monotonic clock time using monotonic_clock = std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock>::type; static std::chrono::high_resolution_clock::time_point hrTimeOfInitialization; SCLANG_DLLEXPORT_C void schedInit() { using namespace std::chrono; hrTimeOfInitialization = high_resolution_clock::now(); #ifdef SC_ABLETON_LINK LinkClock::Init(); #endif syncOSCOffsetWithTimeOfDay(); gResyncThread = std::thread(resyncThread); gHostStartNanos = duration_cast<nanoseconds>(hrTimeOfInitialization.time_since_epoch()).count(); gElapsedOSCoffset = (int64)(gHostStartNanos * kNanosToOSC) + gHostOSCoffset; } SCLANG_DLLEXPORT_C void schedCleanup() { gResyncThreadSemaphore.post(); gResyncThread.join(); } double elapsedTime() { return DurToFloat(std::chrono::high_resolution_clock::now() - hrTimeOfInitialization); } double monotonicClockTime() { return DurToFloat(monotonic_clock::now().time_since_epoch()); } int64 ElapsedTimeToOSC(double elapsed) { return (int64)(elapsed * kSecondsToOSC) + gElapsedOSCoffset; } double OSCToElapsedTime(int64 oscTime) { return (double)(oscTime - gElapsedOSCoffset) * kOSCtoSecs; } void ElapsedTimeToChrono(double elapsed, std::chrono::system_clock::time_point& out_time_point) { int64 oscTime = ElapsedTimeToOSC(elapsed); int64 secs = ((oscTime >> 32) - kSECONDS_FROM_1900_to_1970); int32 nano_secs = (int32)((oscTime & 0xFFFFFFFF) * kOSCtoNanos); using namespace std::chrono; #if 0 // TODO: check system_clock precision system_clock::time_point time_point = system_clock::time_point(seconds(secs) + nanoseconds(nano_secs)); #else int32 usecs = nano_secs / 1000; system_clock::time_point time_point = system_clock::time_point(seconds(secs) + microseconds(usecs)); #endif out_time_point = time_point; } int64 OSCTime() { return ElapsedTimeToOSC(elapsedTime()); } void syncOSCOffsetWithTimeOfDay() { // generate a value gHostOSCoffset such that // (gHostOSCoffset + systemTimeInOSCunits) // is equal to gettimeofday time in OSCunits. // Then if this machine is synced via NTP, we are synced with the world. // more accurate way to do this?? using namespace std::chrono; struct timeval tv; nanoseconds systemTimeBefore, systemTimeAfter; int64 diff, minDiff = 0x7fffFFFFffffFFFFLL; // take best of several tries const int numberOfTries = 8; int64 newOffset = gHostOSCoffset; for (int i = 0; i < numberOfTries; ++i) { systemTimeBefore = high_resolution_clock::now().time_since_epoch(); gettimeofday(&tv, nullptr); systemTimeAfter = high_resolution_clock::now().time_since_epoch(); diff = (systemTimeAfter - systemTimeBefore).count(); if (diff < minDiff) { minDiff = diff; // assume that gettimeofday happens halfway between high_resolution_clock::now() calls int64 systemTimeBetween = systemTimeBefore.count() + diff / 2; int64 systemTimeInOSCunits = (int64)((double)systemTimeBetween * kNanosToOSC); int64 timeOfDayInOSCunits = ((int64)(tv.tv_sec + kSECONDS_FROM_1900_to_1970) << 32) + (int64)(tv.tv_usec * kMicrosToOSC); newOffset = timeOfDayInOSCunits - systemTimeInOSCunits; } } gHostOSCoffset = newOffset; // postfl("gHostOSCoffset %016llX\n", gHostOSCoffset); } void schedAdd(VMGlobals* g, PyrObject* inQueue, double inSeconds, PyrSlot* inTask) { // gLangMutex must be locked double prevTime = inQueue->size > 1 ? slotRawFloat(inQueue->slots + 1) : -1e10; bool added = addheap(g, inQueue, inSeconds, inTask); if (!added) post("scheduler queue is full.\n"); else { if (isKindOfSlot(inTask, class_thread)) { SetFloat(&slotRawThread(inTask)->nextBeat, inSeconds); } if (slotRawFloat(inQueue->slots + 1) != prevTime) { gSchedCond.notify_all(); } } } SCLANG_DLLEXPORT_C void schedStop() { // printf("->schedStop\n"); gLangMutex.lock(); if (gRunSched) { gRunSched = false; gLangMutex.unlock(); gSchedCond.notify_all(); gSchedThread.join(); } else { gLangMutex.unlock(); } // printf("<-schedStop\n"); } void schedClearUnsafe(); SCLANG_DLLEXPORT_C void schedClear() { gLangMutex.lock(); schedClearUnsafe(); gLangMutex.unlock(); } void schedClearUnsafe() { // postfl("->schedClear %d\n", gRunSched); if (gRunSched) { VMGlobals* g = gMainVMGlobals; PyrObject* inQueue = slotRawObject(&g->process->sysSchedulerQueue); inQueue->size = 1; gSchedCond.notify_all(); } // postfl("<-schedClear %d\n", gRunSched); } void post(const char* fmt, ...); void resyncThread() { while (true) { if (gResyncThreadSemaphore.wait_for(std::chrono::seconds(20))) return; syncOSCOffsetWithTimeOfDay(); gElapsedOSCoffset = (int64)(gHostStartNanos * kNanosToOSC) + gHostOSCoffset; } } extern bool gTraceInterpreter; static void schedRunFunc() { using namespace std::chrono; unique_lock<timed_mutex> lock(gLangMutex); // The scheduler may have already been stopped by the time we acquire this // lock, so we need to check the condition now. if (!gRunSched) { return; } VMGlobals* g = gMainVMGlobals; PyrObject* inQueue = slotRawObject(&g->process->sysSchedulerQueue); // dumpObject(inQueue); while (true) { assert(inQueue->size); // postfl("wait until there is something in scheduler\n"); // wait until there is something in scheduler while (inQueue->size == 1) { // postfl("wait until there is something in scheduler\n"); gSchedCond.wait(lock); if (!gRunSched) goto leave; } // postfl("wait until an event is ready\n"); // wait until an event is ready high_resolution_clock::duration schedSecs; high_resolution_clock::time_point now, schedPoint; do { now = high_resolution_clock::now(); schedSecs = duration_cast<high_resolution_clock::duration>(duration<double>(slotRawFloat(inQueue->slots + 1))); schedPoint = hrTimeOfInitialization + schedSecs; if (now >= schedPoint) break; // postfl("wait until an event is ready\n"); gSchedCond.wait_until(lock, schedPoint); if (!gRunSched) goto leave; // postfl("time diff %g\n", elapsedTime() - inQueue->slots->uf); } while (inQueue->size > 1); // postfl("perform all events that are ready %d %.9f\n", inQueue->size, elapsed); // perform all events that are ready // postfl("perform all events that are ready\n"); while ((inQueue->size > 1) && now >= hrTimeOfInitialization + duration_cast<high_resolution_clock::duration>( duration<double>(slotRawFloat(inQueue->slots + 1)))) { double schedtime, delta; PyrSlot task; // postfl("while %.6f >= %.6f\n", elapsed, inQueue->slots->uf); getheap(g, inQueue, &schedtime, &task); if (isKindOfSlot(&task, class_thread)) { SetNil(&slotRawThread(&task)->nextBeat); } slotCopy((++g->sp), &task); SetFloat(++g->sp, schedtime); SetFloat(++g->sp, schedtime); ++g->sp; SetObject(g->sp, s_systemclock->u.classobj); runAwakeMessage(g); long err = slotDoubleVal(&g->result, &delta); if (!err) { // add delta time and reschedule double time = schedtime + delta; schedAdd(g, inQueue, time, &task); } } // postfl("loop\n"); } // postfl("exitloop\n"); leave: return; } #ifdef __APPLE__ # include <mach/mach.h> # include <mach/thread_policy.h> // Polls a (non-realtime) thread to find out how it is scheduled // Results are undefined of an error is returned. Otherwise, the // priority is returned in the address pointed to by the priority // parameter, and whether or not the thread uses timeshare scheduling // is returned at the address pointed to by the isTimeShare parameter kern_return_t GetStdThreadSchedule(mach_port_t machThread, int* priority, boolean_t* isTimeshare) { kern_return_t result = 0; thread_extended_policy_data_t timeShareData; thread_precedence_policy_data_t precedenceData; mach_msg_type_number_t structItemCount; boolean_t fetchDefaults = false; memset(&timeShareData, 0, sizeof(thread_extended_policy_data_t)); memset(&precedenceData, 0, sizeof(thread_precedence_policy_data_t)); if (0 == machThread) machThread = mach_thread_self(); if (NULL != isTimeshare) { structItemCount = THREAD_EXTENDED_POLICY_COUNT; result = thread_policy_get(machThread, THREAD_EXTENDED_POLICY, (integer_t*)&timeShareData, &structItemCount, &fetchDefaults); *isTimeshare = timeShareData.timeshare; if (0 != result) return result; } if (NULL != priority) { fetchDefaults = false; structItemCount = THREAD_PRECEDENCE_POLICY_COUNT; result = thread_policy_get(machThread, THREAD_PRECEDENCE_POLICY, (integer_t*)&precedenceData, &structItemCount, &fetchDefaults); *priority = precedenceData.importance; } return result; } // Reschedules the indicated thread according to new parameters: // // machThread The mach thread id. Pass 0 for the current thread. // newPriority The desired priority. // isTimeShare false for round robin (fixed) priority, // true for timeshare (normal) priority // // A standard new thread usually has a priority of 0 and uses the // timeshare scheduling scheme. Use pthread_mach_thread_np() to // to convert a pthread id to a mach thread id kern_return_t RescheduleStdThread(mach_port_t machThread, int newPriority, boolean_t isTimeshare) { kern_return_t result = 0; thread_extended_policy_data_t timeShareData; thread_precedence_policy_data_t precedenceData; // Set up some variables that we need for the task precedenceData.importance = newPriority; timeShareData.timeshare = isTimeshare; if (0 == machThread) machThread = mach_thread_self(); // Set the scheduling flavor. We want to do this first, since doing so // can alter the priority result = thread_policy_set(machThread, THREAD_EXTENDED_POLICY, (integer_t*)&timeShareData, THREAD_EXTENDED_POLICY_COUNT); if (0 != result) return result; // Now set the priority return thread_policy_set(machThread, THREAD_PRECEDENCE_POLICY, (integer_t*)&precedenceData, THREAD_PRECEDENCE_POLICY_COUNT); } #endif // __APPLE__ #ifdef __linux__ # include <string.h> static void SC_LinuxSetRealtimePriority(pthread_t thread, int priority) { int policy; struct sched_param param; pthread_getschedparam(thread, &policy, &param); policy = SCHED_FIFO; const int minprio = sched_get_priority_min(policy); const int maxprio = sched_get_priority_max(policy); param.sched_priority = sc_clip(priority, minprio, maxprio); int err = pthread_setschedparam(thread, policy, &param); if (err != 0) { post("Couldn't set realtime scheduling priority %d: %s\n", param.sched_priority, strerror(err)); } } #endif // __linux__ SCLANG_DLLEXPORT_C void schedRun() { // gLangMutex must be locked gRunSched = true; SC_Thread thread(schedRunFunc); gSchedThread = std::move(thread); #ifdef __APPLE__ int policy; struct sched_param param; // pthread_t thread = pthread_self (); pthread_getschedparam(gSchedThread.native_handle(), &policy, &param); // post("param.sched_priority %d\n", param.sched_priority); policy = SCHED_RR; // round-robin, AKA real-time scheduling int machprio; boolean_t timeshare; GetStdThreadSchedule(pthread_mach_thread_np(gSchedThread.native_handle()), &machprio, &timeshare); // post("mach priority %d timeshare %d\n", machprio, timeshare); // what priority should gSchedThread use? RescheduleStdThread(pthread_mach_thread_np(gSchedThread.native_handle()), 62, false); GetStdThreadSchedule(pthread_mach_thread_np(gSchedThread.native_handle()), &machprio, &timeshare); // post("mach priority %d timeshare %d\n", machprio, timeshare); // param.sched_priority = 70; // you'll have to play with this to see what it does // pthread_setschedparam (gSchedThread, policy, &param); pthread_getschedparam(gSchedThread.native_handle(), &policy, &param); // post("param.sched_priority %d\n", param.sched_priority); #endif // __APPLE__ #ifdef __linux__ SC_LinuxSetRealtimePriority(gSchedThread.native_handle(), 1); #endif // __linux__ } /* unscheduled events: startup, receive OSC, mouse, keyboard, MIDI all these happen in the main thread. */ /* new clock: create destroy wake up at time x. unschedule awake reschedules. */ TempoClock* TempoClock::sAll = nullptr; void TempoClock_stopAll(void) { // printf("->TempoClock_stopAll %p\n", TempoClock::sAll); auto* clock = TempoClock::GetAll(); while (clock) { auto* next = clock->GetNext(); clock->Stop(); // printf("delete\n"); delete clock; clock = next; } // printf("<-TempoClock_stopAll %p\n", TempoClock::sAll); TempoClock::InitAll(); } TempoClock::TempoClock(VMGlobals* inVMGlobals, PyrObject* inTempoClockObj, double inTempo, double inBaseBeats, double inBaseSeconds): g(inVMGlobals), mTempoClockObj(inTempoClockObj), mTempo(inTempo), mBeatDur(1. / inTempo), mBaseSeconds(inBaseSeconds), mBaseBeats(inBaseBeats), mRun(true), mPrev(nullptr), mNext(sAll) { if (sAll) sAll->mPrev = this; sAll = this; mQueue = (PyrHeap*)slotRawObject(&mTempoClockObj->slots[0]); mQueue->size = 1; SetInt(&mQueue->count, 0); SC_Thread thread(std::bind(&TempoClock::Run, this)); mThread = std::move(thread); #ifdef __APPLE__ int machprio; boolean_t timeshare; GetStdThreadSchedule(pthread_mach_thread_np(mThread.native_handle()), &machprio, &timeshare); // post("mach priority %d timeshare %d\n", machprio, timeshare); // what priority should gSchedThread use? RescheduleStdThread(pthread_mach_thread_np(mThread.native_handle()), 10, false); GetStdThreadSchedule(pthread_mach_thread_np(mThread.native_handle()), &machprio, &timeshare); // post("mach priority %d timeshare %d\n", machprio, timeshare); // param.sched_priority = 70; // you'll have to play with this to see what it does // pthread_setschedparam (mThread, policy, &param); #endif // __APPLE__ #ifdef __linux__ SC_LinuxSetRealtimePriority(mThread.native_handle(), 1); #endif // __linux__ } void TempoClock::StopReq() { // printf("->TempoClock::StopReq\n"); SC_Thread stopThread(std::bind(&TempoClock::StopAndDelete, this)); stopThread.detach(); // printf("<-TempoClock::StopReq\n"); } void TempoClock::Stop() { // printf("->TempoClock::Stop\n"); { lock_guard<timed_mutex> lock(gLangMutex); // printf("Stop mRun %d\n", mRun); if (mRun) { mRun = false; // unlink if (mPrev) mPrev->mNext = mNext; else sAll = mNext; if (mNext) mNext->mPrev = mPrev; mCondition.notify_all(); } } mThread.join(); // printf("<-TempoClock::Stop\n"); } void TempoClock::SetAll(double inTempo, double inBeats, double inSeconds) { mBaseSeconds = inSeconds; mBaseBeats = inBeats; mTempo = inTempo; mBeatDur = 1. / mTempo; mCondition.notify_one(); } void TempoClock::SetTempoAtBeat(double inTempo, double inBeats) { mBaseSeconds = BeatsToSecs(inBeats); mBaseBeats = inBeats; mTempo = inTempo; mBeatDur = 1. / mTempo; mCondition.notify_one(); } void TempoClock::SetTempoAtTime(double inTempo, double inSeconds) { mBaseBeats = SecsToBeats(inSeconds); mBaseSeconds = inSeconds; mTempo = inTempo; mBeatDur = 1. / mTempo; mCondition.notify_one(); } double TempoClock::ElapsedBeats() { return SecsToBeats(elapsedTime()); } void* TempoClock::Run() { using namespace std::chrono; // printf("->TempoClock::Run\n"); unique_lock<timed_mutex> lock(gLangMutex); while (mRun) { assert(mQueue->size); // printf("tempo %g dur %g beats %g\n", mTempo, mBeatDur, mBeats); // printf("wait until there is something in scheduler\n"); // wait until there is something in scheduler while (mQueue->size == 1) { // printf("wait until there is something in scheduler\n"); mCondition.wait(gLangMutex); // printf("mRun a %d\n", mRun); if (!mRun) goto leave; } // printf("wait until an event is ready\n"); // wait until an event is ready double elapsedBeats; high_resolution_clock::duration schedSecs; high_resolution_clock::time_point schedPoint; do { elapsedBeats = ElapsedBeats(); if (elapsedBeats >= slotRawFloat(mQueue->slots)) break; // printf("event ready at %g . elapsed beats %g\n", mQueue->slots->uf, elapsedBeats); double wakeTime = BeatsToSecs(slotRawFloat(mQueue->slots)); schedSecs = duration_cast<high_resolution_clock::duration>(duration<double>(wakeTime)); schedPoint = hrTimeOfInitialization + schedSecs; // printf("wait until an event is ready. wake %g now %g\n", wakeTime, elapsedTime()); mCondition.wait_until(lock, schedPoint); // printf("mRun b %d\n", mRun); if (!mRun) goto leave; // printf("time diff %g\n", elapsedTime() - mQueue->slots->uf); } while (mQueue->size > 1); // printf("perform all events that are ready %d %.9f\n", mQueue->size, elapsedBeats); // perform all events that are ready // printf("perform all events that are ready\n"); while (mQueue->size > 1 && elapsedBeats >= slotRawFloat(mQueue->slots)) { double delta; PyrSlot task; // printf("while %.6f >= %.6f\n", elapsedBeats, mQueue->slots->uf); getheap(g, (PyrObject*)mQueue, &mBeats, &task); if (isKindOfSlot(&task, class_thread)) { SetNil(&slotRawThread(&task)->nextBeat); } slotCopy((++g->sp), &task); SetFloat(++g->sp, mBeats); SetFloat(++g->sp, BeatsToSecs(mBeats)); ++g->sp; SetObject(g->sp, mTempoClockObj); runAwakeMessage(g); long err = slotDoubleVal(&g->result, &delta); if (!err) { // add delta time and reschedule double beats = mBeats + delta; Add(beats, &task); } } } leave: // printf("<-TempoClock::Run\n"); return nullptr; } /* void TempoClock::Flush() { while (mQueue->size && elapsedBeats >= mQueue->slots->uf) { double delta; PyrSlot task; //printf("while %.6f >= %.6f\n", elapsedBeats, mQueue->slots->uf); getheap(g, mQueue, &mBeats, &task); slotCopy((++g->sp), &task); (++g->sp)->uf = mBeats; (++g->sp)->uf = BeatsToSecs(mBeats); ++g->sp; SetObject(g->sp, mTempoClockObj); runAwakeMessage(g); long err = slotDoubleVal(&g->result, &delta); if (!err) { // add delta time and reschedule double beats = mBeats + delta; Add(beats, &task); } } } */ void TempoClock::Add(double inBeats, PyrSlot* inTask) { double prevBeats = mQueue->size > 1 ? slotRawFloat(mQueue->slots) : -1e10; bool added = addheap(g, (PyrObject*)mQueue, inBeats, inTask); if (!added) post("scheduler queue is full.\n"); else { if (isKindOfSlot(inTask, class_thread)) { SetFloat(&slotRawThread(inTask)->nextBeat, inBeats); } if (slotRawFloat(mQueue->slots) != prevBeats) mCondition.notify_one(); } } void TempoClock::Clear() { if (mRun) { mQueue->size = 1; mCondition.notify_one(); } } void TempoClock::Dump() { post("mTempo %g\n", mTempo); post("mBeatDur %g\n", mBeatDur); post("mBeats %g\n", mBeats); post("seconds %g\n", BeatsToSecs(mBeats)); post("mBaseSeconds %g\n", mBaseSeconds); post("mBaseBeats %g\n", mBaseBeats); } int prTempoClock_Free(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) return errNone; // not running SetNil(slotRawObject(a)->slots + 1); clock->StopReq(); return errNone; } int prTempoClock_Clear(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (clock) clock->Clear(); return errNone; } int prTempoClock_Dump(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (clock) clock->Dump(); return errNone; } int prTempoClock_Tempo(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } SetFloat(a, clock->GetTempo()); return errNone; } int prTempoClock_BeatDur(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } SetFloat(a, clock->GetBeatDur()); return errNone; } int prTempoClock_ElapsedBeats(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } SetFloat(a, clock->ElapsedBeats()); return errNone; } int prTempoClock_Beats(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; double beats, seconds; if (SlotEq(&g->thread->clock, a)) { int err = slotDoubleVal(&g->thread->beats, &beats); if (err) return errWrongType; } else { TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } int err = slotDoubleVal(&g->thread->seconds, &seconds); if (err) return errWrongType; beats = clock->SecsToBeats(seconds); } SetFloat(a, beats); return errNone; } int prTempoClock_Sched(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; double delta, beats; int err; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } if (SlotEq(&g->thread->clock, a)) { err = slotDoubleVal(&g->thread->beats, &beats); if (err) return errNone; // return nil OK, just don't schedule } else { double seconds; err = slotDoubleVal(&g->thread->seconds, &seconds); if (err) return errNone; beats = clock->SecsToBeats(seconds); } err = slotDoubleVal(b, &delta); if (err) return errNone; // return nil OK, just don't schedule beats += delta; if (beats == dInfinity) return errNone; // return nil OK, just don't schedule clock->Add(beats, c); return errNone; } int prTempoClock_SchedAbs(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double beats; int err = slotDoubleVal(b, &beats) || (beats == dInfinity); if (err) return errNone; // return nil OK, just don't schedule clock->Add(beats, c); return errNone; } int prTempoClock_BeatsToSecs(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double beats; int err = slotDoubleVal(b, &beats); if (err) return errFailed; SetFloat(a, clock->BeatsToSecs(beats)); return errNone; } int prTempoClock_SecsToBeats(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; TempoClock* clock = (TempoClock*)slotRawPtr(&slotRawObject(a)->slots[1]); if (!clock) { error("clock is not running.\n"); return errFailed; } double secs; int err = slotDoubleVal(b, &secs); if (err) return errFailed; SetFloat(a, clock->SecsToBeats(secs)); return errNone; } int prSystemClock_Clear(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp; schedClearUnsafe(); return errNone; } int prSystemClock_Sched(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; double delta, seconds; int err = slotDoubleVal(b, &delta); if (err) return errNone; // return nil OK, just don't schedule err = slotDoubleVal(&g->thread->seconds, &seconds); if (err) return errNone; // return nil OK, just don't schedule seconds += delta; if (seconds == dInfinity) return errNone; // return nil OK, just don't schedule PyrObject* inQueue = slotRawObject(&g->process->sysSchedulerQueue); schedAdd(g, inQueue, seconds, c); return errNone; } int prSystemClock_SchedAbs(struct VMGlobals* g, int numArgsPushed) { // PyrSlot *a = g->sp - 2; PyrSlot* b = g->sp - 1; PyrSlot* c = g->sp; double time; int err = slotDoubleVal(b, &time) || (time == dInfinity); if (err) return errNone; // return nil OK, just don't schedule PyrObject* inQueue = slotRawObject(&g->process->sysSchedulerQueue); schedAdd(g, inQueue, time, c); return errNone; } int prElapsedTime(struct VMGlobals* g, int numArgsPushed) { SetFloat(g->sp, elapsedTime()); return errNone; } int prmonotonicClockTime(struct VMGlobals* g, int numArgsPushed) { SetFloat(g->sp, monotonicClockTime()); return errNone; } void initSchedPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_TempoClock_New", prClock_New<TempoClock>, 4, 0); definePrimitive(base, index++, "_TempoClock_Free", prTempoClock_Free, 1, 0); definePrimitive(base, index++, "_TempoClock_Clear", prTempoClock_Clear, 1, 0); definePrimitive(base, index++, "_TempoClock_Dump", prTempoClock_Dump, 1, 0); definePrimitive(base, index++, "_TempoClock_Sched", prTempoClock_Sched, 3, 0); definePrimitive(base, index++, "_TempoClock_SchedAbs", prTempoClock_SchedAbs, 3, 0); definePrimitive(base, index++, "_TempoClock_Tempo", prTempoClock_Tempo, 1, 0); definePrimitive(base, index++, "_TempoClock_BeatDur", prTempoClock_BeatDur, 1, 0); definePrimitive(base, index++, "_TempoClock_ElapsedBeats", prTempoClock_ElapsedBeats, 1, 0); definePrimitive(base, index++, "_TempoClock_Beats", prTempoClock_Beats, 1, 0); definePrimitive(base, index++, "_TempoClock_SetBeats", prClock_SetBeats<TempoClock>, 2, 0); definePrimitive(base, index++, "_TempoClock_SetTempoAtBeat", prClock_SetTempoAtBeat<TempoClock>, 3, 0); definePrimitive(base, index++, "_TempoClock_SetTempoAtTime", prClock_SetTempoAtTime<TempoClock>, 3, 0); definePrimitive(base, index++, "_TempoClock_SetAll", prClock_SetAll<TempoClock>, 4, 0); definePrimitive(base, index++, "_TempoClock_BeatsToSecs", prTempoClock_BeatsToSecs, 2, 0); definePrimitive(base, index++, "_TempoClock_SecsToBeats", prTempoClock_SecsToBeats, 2, 0); definePrimitive(base, index++, "_SystemClock_Clear", prSystemClock_Clear, 1, 0); definePrimitive(base, index++, "_SystemClock_Sched", prSystemClock_Sched, 3, 0); definePrimitive(base, index++, "_SystemClock_SchedAbs", prSystemClock_SchedAbs, 3, 0); definePrimitive(base, index++, "_ElapsedTime", prElapsedTime, 1, 0); definePrimitive(base, index++, "_monotonicClockTime", prmonotonicClockTime, 1, 0); }
36,864
C++
.cpp
942
32.487261
120
0.634849
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
29,876
PyrCharPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrCharPrim.cpp
/* 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 */ /* Primitives for Char. */ #include <ctype.h> #include "PyrPrimitive.h" #include "VMGlobals.h" int prToLower(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetRawChar(a, tolower(slotRawChar(a))); return errNone; } int prToUpper(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetRawChar(a, toupper(slotRawChar(a))); return errNone; } int prIsLower(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (islower(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsUpper(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (isupper(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsAlpha(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (isalpha(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsAlphaNum(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (isalnum(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsControl(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (iscntrl(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsDigit(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (isdigit(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsPrint(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (isprint(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsPunct(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (ispunct(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prIsSpace(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; if (isspace(slotRawChar(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } int prAsciiValue(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetTagRaw(a, tagInt); return errNone; } int prDigitValue(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; char c; a = g->sp; c = slotRawChar(a); if (c >= '0' && c <= '9') { SetInt(a, c - '0'); } else if (c >= 'a' && c <= 'z') { SetInt(a, c - 'a' + 10); } else if (c >= 'A' && c <= 'Z') { SetInt(a, c - 'A' + 10); } else { return errFailed; } return errNone; } int prAsAscii(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetChar(a, slotRawInt(a) & 255); return errNone; } int prAsDigit(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; int c; a = g->sp; c = slotRawInt(a); if (c >= 0 && c <= 9) { SetChar(a, slotRawInt(a) + '0'); } else if (c >= 10 && c <= 35) { SetChar(a, slotRawInt(a) + 'A' - 10); } else { return errFailed; } return errNone; } void initCharPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_AsciiValue", prAsciiValue, 1, 0); definePrimitive(base, index++, "_DigitValue", prDigitValue, 1, 0); definePrimitive(base, index++, "_AsAscii", prAsAscii, 1, 0); definePrimitive(base, index++, "_AsDigit", prAsDigit, 1, 0); definePrimitive(base, index++, "_ToLower", prToLower, 1, 0); definePrimitive(base, index++, "_ToUpper", prToUpper, 1, 0); definePrimitive(base, index++, "_IsLower", prIsLower, 1, 0); definePrimitive(base, index++, "_IsUpper", prIsUpper, 1, 0); definePrimitive(base, index++, "_IsAlpha", prIsAlpha, 1, 0); definePrimitive(base, index++, "_IsAlphaNum", prIsAlphaNum, 1, 0); definePrimitive(base, index++, "_IsPrint", prIsPrint, 1, 0); definePrimitive(base, index++, "_IsPunct", prIsPunct, 1, 0); definePrimitive(base, index++, "_IsControl", prIsControl, 1, 0); definePrimitive(base, index++, "_IsSpace", prIsSpace, 1, 0); definePrimitive(base, index++, "_IsDecDigit", prIsDigit, 1, 0); }
5,275
C++
.cpp
183
23.781421
81
0.624403
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
29,877
PyrPlatformPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrPlatformPrim.cpp
/* 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 */ /* Primitives for platform dependent directories, constants etc. */ #include "SC_Filesystem.hpp" // getDirectory #include "SC_Filesystem.hpp" // path_to_utf8_str #include "SC_LanguageConfig.hpp" // getIdeName #include "PyrPrimitive.h" #include "PyrKernel.h" #include "SCBase.h" // getsym #ifdef _WIN32 # include "SC_Win32Utils.h" # include "Shlobj.h" #endif #include <filesystem> #include <boost/predef/architecture.h> namespace fs = std::filesystem; using DirName = SC_Filesystem::DirName; static inline int prPlatform_getDirectory(const struct VMGlobals* g, const DirName dirname) { PyrSlot* a = g->sp; const fs::path& p = SC_Filesystem::instance().getDirectory(dirname); PyrString* string = newPyrString(g->gc, SC_Codecvt::path_to_utf8_str(p).c_str(), 0, true); SetObject(a, string); return errNone; } static int prPlatform_userHomeDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::UserHome); } static int prPlatform_systemAppSupportDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::SystemAppSupport); } static int prPlatform_userAppSupportDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::UserAppSupport); } static int prPlatform_systemExtensionDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::SystemExtension); } static int prPlatform_userExtensionDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::UserExtension); } static int prPlatform_userConfigDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::UserConfig); } static int prPlatform_resourceDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::Resource); } #ifdef _WIN32 static int prWinPlatform_myDocumentsDir(struct VMGlobals* g, int numArgsPushed) { return prPlatform_getDirectory(g, DirName::MyDocuments); } #endif static int prPlatform_ideName(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrString* string = newPyrString(g->gc, SC_Filesystem::instance().getIdeName().c_str(), 0, true); SetObject(a, string); return errNone; } int prPlatform_hasQt(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; #ifdef SC_QT SetBool(a, true); #else SetBool(a, false); #endif return errNone; } int prPlatform_hasQtWebEngine(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; #ifdef SC_USE_QTWEBENGINE SetBool(a, true); #else SetBool(a, false); #endif return errNone; } int prPlatform_architecture(struct VMGlobals* g, int numArgsPushed) { // See discussion at https://github.com/supercollider/supercollider/pull/4524 #if defined(BOOST_ARCH_ARM) && defined(__aarch64__) SetSymbol(g->sp, getsym("AArch64")); #elif BOOST_ARCH_ARM SetSymbol(g->sp, getsym("AArch32")); #elif BOOST_ARCH_IA64 SetSymbol(g->sp, getsym("Itanium64")); #elif BOOST_ARCH_X86_32 SetSymbol(g->sp, getsym("i386")); #elif BOOST_ARCH_X86_64 SetSymbol(g->sp, getsym("x86_64")); #elif BOOST_ARCH_PPC SetSymbol(g->sp, getsym("PowerPC")); #else # warning "Unknown platform architecture: please submit a pull request to add yours!" SetSymbol(g->sp, getsym("unknown")); #endif return errNone; } int prPlatform_hasBelaSupport(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; #ifdef SC_AUDIO_API_BELA SetBool(a, true); #else SetBool(a, false); #endif return errNone; } void initPlatformPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_Platform_userHomeDir", prPlatform_userHomeDir, 1, 0); definePrimitive(base, index++, "_Platform_systemAppSupportDir", prPlatform_systemAppSupportDir, 1, 0); definePrimitive(base, index++, "_Platform_userAppSupportDir", prPlatform_userAppSupportDir, 1, 0); definePrimitive(base, index++, "_Platform_systemExtensionDir", prPlatform_systemExtensionDir, 1, 0); definePrimitive(base, index++, "_Platform_userExtensionDir", prPlatform_userExtensionDir, 1, 0); definePrimitive(base, index++, "_Platform_userConfigDir", prPlatform_userConfigDir, 1, 0); definePrimitive(base, index++, "_Platform_resourceDir", prPlatform_resourceDir, 1, 0); definePrimitive(base, index++, "_Platform_ideName", prPlatform_ideName, 1, 0); definePrimitive(base, index++, "_Platform_hasQt", prPlatform_hasQt, 1, 0); definePrimitive(base, index++, "_Platform_hasQtWebEngine", prPlatform_hasQtWebEngine, 1, 0); definePrimitive(base, index++, "_Platform_architecture", prPlatform_architecture, 1, 0); definePrimitive(base, index++, "_Platform_hasBelaSupport", prPlatform_hasBelaSupport, 1, 0); #ifdef _WIN32 definePrimitive(base, index++, "_WinPlatform_myDocumentsDir", prWinPlatform_myDocumentsDir, 1, 0); #endif } // EOF
5,820
C++
.cpp
139
38.755396
106
0.748541
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
29,878
PyrArrayPrimitives.cpp
supercollider_supercollider/lang/LangPrimSource/PyrArrayPrimitives.cpp
/* 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 */ /* Primitives for Arrays. */ #include "GC.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "SCBase.h" #include "SC_InlineBinaryOp.h" #include "SC_Constants.h" #include "SC_Levenshtein.h" #include <cstring> #include <vector> // Primitives that work with Arrays. Most of these are used in ArrayedCollection and Array. int basicSize(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrObject* obj; a = g->sp; if (NotObj(a)) { SetInt(a, 0); return errNone; } obj = slotRawObject(a); SetInt(a, obj->size); return errNone; } int basicMaxSize(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrObject* obj; int maxsize; a = g->sp; if (NotObj(a)) { SetInt(a, 0); return errNone; } obj = slotRawObject(a); maxsize = MAXINDEXSIZE(obj); SetInt(a, maxsize); return errNone; } int basicSwap(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, tempi, tempj; int i, j; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotObj(a)) return errWrongType; if (NotInt(b)) return errIndexNotAnInteger; if (NotInt(c)) return errIndexNotAnInteger; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; i = slotRawInt(b); j = slotRawInt(c); if (i < 0 || i >= obj->size) return errIndexOutOfRange; if (j < 0 || j >= obj->size) return errIndexOutOfRange; getIndexedSlot(obj, &tempi, i); getIndexedSlot(obj, &tempj, j); putIndexedSlot(g, obj, &tempi, j); putIndexedSlot(g, obj, &tempj, i); // in case it is partial scan obj g->gc->GCWrite(obj, &tempi); g->gc->GCWrite(obj, &tempj); return errNone; } int getIndexedInt(PyrObject* obj, int index, int* value); void DumpBackTrace(VMGlobals* g); int basicAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index; PyrObject* obj; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; obj = slotRawObject(a); if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; int err = slotIntVal(b, &index); if (!err) { if (index < 0 || index >= obj->size) { slotCopy(a, &o_nil); } else { getIndexedSlot(obj, a, index); } } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = indexArray->size; PyrObject* outArray = newPyrArray(g->gc, size, 0, true); PyrSlot* outArraySlots = outArray->slots; for (int i = 0; i < size; ++i) { int err = getIndexedInt(indexArray, i, &index); if (err) return err; if (index < 0 || index >= obj->size) { slotCopy(&outArraySlots[i], &o_nil); } else { getIndexedSlot(obj, outArraySlots + i, index); } } outArray->size = size; SetObject(a, outArray); } else { return errIndexNotAnInteger; } return errNone; } int basicRemoveAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index, length, elemsize; PyrObject* obj; void* ptr; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (err) return errWrongType; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (index < 0 || index >= obj->size) return errIndexOutOfRange; switch (obj->obj_format) { default: case obj_slot: ptr = obj->slots + index; slotCopy(a, (PyrSlot*)ptr); break; case obj_double: ptr = obj->slots + index; SetFloat(a, *(double*)ptr); break; case obj_float: ptr = ((float*)(obj->slots)) + index; SetFloat(a, *(float*)ptr); break; case obj_int32: ptr = ((int32*)(obj->slots)) + index; SetInt(a, *(int32*)ptr); break; case obj_int16: ptr = ((int16*)(obj->slots)) + index; SetInt(a, *(int16*)ptr); break; case obj_int8: ptr = ((int8*)(obj->slots)) + index; SetInt(a, *(int8*)ptr); break; case obj_symbol: ptr = ((int*)(obj->slots)) + index; SetSymbol(a, *(PyrSymbol**)ptr); break; case obj_char: ptr = ((unsigned char*)(obj->slots)) + index; SetChar(a, *(unsigned char*)ptr); break; } length = obj->size - index - 1; if (length > 0) { elemsize = gFormatElemSize[obj->obj_format]; memmove(ptr, (char*)ptr + elemsize, length * elemsize); if (obj->obj_format <= obj_slot) { // might be partial scan object g->gc->GCWrite(obj, obj->slots + index); } } obj->size--; return errNone; } int basicTakeAt(struct VMGlobals* g, int numArgsPushed); int basicTakeAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index, lastIndex; PyrObject* obj; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (err) return errWrongType; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; lastIndex = obj->size - 1; if (index < 0 || index >= obj->size) return errIndexOutOfRange; switch (obj->obj_format) { case obj_slot: { PyrSlot* ptr = obj->slots + index; PyrSlot* lastptr = obj->slots + lastIndex; slotCopy(a, ptr); *ptr = *lastptr; // might be partial scan obj g->gc->GCWrite(obj, ptr); } break; case obj_double: { PyrSlot* ptr = obj->slots + index; PyrSlot* lastptr = obj->slots + lastIndex; SetFloat(a, *(double*)ptr); *ptr = *lastptr; // might be partial scan obj g->gc->GCWrite(obj, ptr); } break; case obj_float: { float* ptr = ((float*)(obj->slots)) + index; float* lastptr = ((float*)(obj->slots)) + lastIndex; SetFloat(a, *(float*)ptr); *ptr = *lastptr; } break; case obj_int32: { int32* ptr = ((int32*)(obj->slots)) + index; int32* lastptr = ((int32*)(obj->slots)) + lastIndex; SetInt(a, *(int32*)ptr); *ptr = *lastptr; } break; case obj_int16: { int16* ptr = ((int16*)(obj->slots)) + index; int16* lastptr = ((int16*)(obj->slots)) + lastIndex; SetInt(a, *(int16*)ptr); *ptr = *lastptr; } break; case obj_int8: { int8* ptr = ((int8*)(obj->slots)) + index; int8* lastptr = ((int8*)(obj->slots)) + lastIndex; SetInt(a, *(int8*)ptr); *ptr = *lastptr; } break; case obj_symbol: { int32* ptr = ((int32*)(obj->slots)) + index; int32* lastptr = ((int32*)(obj->slots)) + lastIndex; SetSymbol(a, *(PyrSymbol**)ptr); *ptr = *lastptr; } break; case obj_char: { unsigned char* ptr = ((unsigned char*)(obj->slots)) + index; unsigned char* lastptr = ((unsigned char*)(obj->slots)) + lastIndex; SetChar(a, *(unsigned char*)ptr); *ptr = *lastptr; } break; } obj->size--; return errNone; } int basicWrapAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index; PyrObject* obj; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; obj = slotRawObject(a); if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (obj->size == 0) { SetNil(a); return errNone; } int err = slotIntVal(b, &index); if (!err) { index = sc_mod((int)index, (int)obj->size); getIndexedSlot(obj, a, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = indexArray->size; PyrObject* outArray = newPyrArray(g->gc, size, 0, true); PyrSlot* outArraySlots = outArray->slots; for (int i = 0; i < size; ++i) { int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_mod((int)index, (int)obj->size); getIndexedSlot(obj, outArraySlots + i, index); } outArray->size = size; SetObject(a, outArray); } else return errIndexNotAnInteger; return errNone; } int basicFoldAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index; PyrObject* obj; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; obj = slotRawObject(a); if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (obj->size == 0) { SetNil(a); return errNone; } int err = slotIntVal(b, &index); if (!err) { index = sc_fold(index, 0, obj->size - 1); getIndexedSlot(obj, a, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = indexArray->size; PyrObject* outArray = newPyrArray(g->gc, size, 0, true); PyrSlot* outArraySlots = outArray->slots; for (int i = 0; i < size; ++i) { int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_fold(index, 0, obj->size - 1); getIndexedSlot(obj, outArraySlots + i, index); } outArray->size = size; SetObject(a, outArray); } else return errIndexNotAnInteger; return errNone; } int basicClipAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int index; PyrObject* obj; a = g->sp - 1; b = g->sp; if (NotObj(a)) return errWrongType; obj = slotRawObject(a); if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (obj->size == 0) { SetNil(a); return errNone; } int err = slotIntVal(b, &index); if (!err) { index = sc_clip(index, 0, obj->size - 1); getIndexedSlot(obj, a, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = indexArray->size; PyrObject* outArray = newPyrArray(g->gc, size, 0, true); PyrSlot* outArraySlots = outArray->slots; for (int i = 0; i < size; ++i) { int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_clip(index, 0, obj->size - 1); getIndexedSlot(obj, outArraySlots + i, index); } outArray->size = size; SetObject(a, outArray); } else return errIndexNotAnInteger; return errNone; } int basicPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int index; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (!err) { if (index < 0 || index >= obj->size) return errIndexOutOfRange; return putIndexedSlot(g, obj, c, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = slotRawObject(b)->size; for (int i = 0; i < size; ++i) { int index; int err = getIndexedInt(indexArray, i, &index); if (err) return err; if (index < 0 || index >= obj->size) return errIndexOutOfRange; err = putIndexedSlot(g, obj, c, index); if (err) return err; } return errNone; } else return errIndexNotAnInteger; } int basicClipPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int index; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (!err) { index = sc_clip(index, 0, obj->size - 1); return putIndexedSlot(g, obj, c, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = slotRawObject(b)->size; for (int i = 0; i < size; ++i) { int index; int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_clip(index, 0, obj->size - 1); err = putIndexedSlot(g, obj, c, index); if (err) return err; } return errNone; } else return errIndexNotAnInteger; } int basicWrapPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int index; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (!err) { index = sc_mod((int)index, (int)obj->size); return putIndexedSlot(g, obj, c, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = slotRawObject(b)->size; for (int i = 0; i < size; ++i) { int index; int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_mod((int)index, (int)obj->size); err = putIndexedSlot(g, obj, c, index); if (err) return err; } return errNone; } else return errIndexNotAnInteger; } int basicFoldPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int index; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (NotObj(a)) return errWrongType; int err = slotIntVal(b, &index); if (!err) { index = sc_fold(index, 0, obj->size - 1); return putIndexedSlot(g, obj, c, index); } else if (isKindOfSlot(b, class_arrayed_collection)) { PyrObject* indexArray = slotRawObject(b); int size = slotRawObject(b)->size; for (int i = 0; i < size; ++i) { int index; int err = getIndexedInt(indexArray, i, &index); if (err) return err; index = sc_fold(index, 0, obj->size - 1); err = putIndexedSlot(g, obj, c, index); if (err) return err; } return errNone; } else return errIndexNotAnInteger; } int prArrayPutEach(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; PyrObject* obj; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; if (!(slotRawInt(&obj->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (!isKindOfSlot(b, class_arrayed_collection)) return errWrongType; if (!isKindOfSlot(c, class_arrayed_collection)) return errWrongType; PyrSlot* indices = slotRawObject(b)->slots; PyrSlot* values = slotRawObject(c)->slots; int size = slotRawObject(b)->size; int valsize = slotRawObject(c)->size; for (int i = 0; i < size; ++i) { int index; int err = slotIntVal(indices + i, &index); if (err) return err; if (index < 0 || index >= obj->size) return errIndexOutOfRange; int valindex = sc_mod(i, valsize); err = putIndexedSlot(g, obj, values + valindex, index); if (err) return err; } return errNone; } int prArrayAssocAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject* obj; bool found = false; a = g->sp - 1; b = g->sp; obj = slotRawObject(a); int size = obj->size; if (obj->obj_format == obj_slot) { PyrSlot* slots = obj->slots; for (int i = 0; i < size; i += 2) { if (SlotEq(slots + i, b)) { if (i + 1 >= size) return errFailed; slotCopy(a, &slots[i + 1]); found = true; break; } } } else { PyrSlot slot; for (int i = 0; i < size; i += 2) { getIndexedSlot(obj, &slot, i); if (SlotEq(&slot, b)) { if (i + 1 >= size) return errFailed; getIndexedSlot(obj, &slot, i + 1); slotCopy(a, &slot); found = true; break; } } } if (!found) SetNil(a); return errNone; } int prArrayAssocPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; PyrObject* obj; bool found = false; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj = slotRawObject(a); if (obj->IsImmutable()) return errImmutableObject; int size = obj->size; if (obj->obj_format == obj_slot) { PyrSlot* slots = obj->slots; for (int i = 0; i < size; i += 2) { if (SlotEq(slots + i, b)) { if (i + 1 >= size) return errFailed; slotCopy(&slots[i + 1], c); g->gc->GCWrite(obj, c); found = true; break; } } } else { PyrSlot slot; for (int i = 0; i < size; i += 2) { getIndexedSlot(obj, &slot, i); if (SlotEq(&slot, b)) { if (i + 1 >= size) return errFailed; putIndexedSlot(g, obj, &slot, i + 1); g->gc->GCWrite(obj, c); found = true; break; } } } if (!found) SetNil(a); return errNone; } int prArrayIndexOf(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject* obj; bool found = false; a = g->sp - 1; b = g->sp; obj = slotRawObject(a); int size = obj->size; if (obj->obj_format == obj_slot) { PyrSlot* slots = obj->slots; for (int i = 0; i < size; ++i) { if (SlotEq(slots + i, b)) { SetInt(a, i); found = true; break; } } } else { PyrSlot slot; for (int i = 0; i < size; ++i) { getIndexedSlot(obj, &slot, i); if (SlotEq(&slot, b)) { SetInt(a, i); found = true; break; } } } if (!found) SetNil(a); return errNone; } int prArrayPutSeries(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *d, *e; a = g->sp - 4; b = g->sp - 3; c = g->sp - 2; d = g->sp - 1; e = g->sp; PyrObject* inobj = slotRawObject(a); if (inobj->IsImmutable()) return errImmutableObject; int size = inobj->size; if (NotInt(b) && NotNil(b)) return errWrongType; if (NotInt(c) && NotNil(c)) return errWrongType; if (NotInt(d) && NotNil(d)) return errWrongType; int first = IsInt(b) ? slotRawInt(b) : 0; int last = IsInt(d) ? slotRawInt(d) : size - 1; int second = IsInt(c) ? slotRawInt(c) : (first < last ? first + 1 : first - 1); int step = second - first; first = sc_clip(first, 0, size - 1); last = sc_clip(last, 0, size - 1); int err = errNone; if (step == 0) return errFailed; if (step == 1) { for (int i = first; i <= last; ++i) { err = putIndexedSlot(g, inobj, e, i); if (err) return err; } } else if (step == -1) { for (int i = last; i >= first; --i) { err = putIndexedSlot(g, inobj, e, i); if (err) return err; } } else if (step > 0) { int length = (last - first) / step + 1; for (int i = first, j = 0; j < length; i += step, ++j) { err = putIndexedSlot(g, inobj, e, i); if (err) return err; } } else if (step < 0) { int length = (first - last) / -step + 1; for (int i = first, j = 0; j < length; i += step, ++j) { err = putIndexedSlot(g, inobj, e, i); if (err) return err; } } return errNone; } int prArrayAdd(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; int maxelems, elemsize, format, tag, numbytes; int err, ival; double fval; a = g->sp - 1; b = g->sp; PyrObject* array = slotRawObject(a); if (array->IsImmutable()) return errImmutableObject; format = slotRawObject(a)->obj_format; tag = gFormatElemTag[format]; /*if (tag > 0) { if (GetTag(b) != tag) return errWrongType; } else if (tag == 0) { if (NotFloat(b)) return errWrongType; } // else format is obj_slot, any tag is acceptable*/ elemsize = gFormatElemSize[format]; maxelems = MAXINDEXSIZE(array); if (array->size >= maxelems || array->IsImmutable()) { numbytes = sizeof(PyrSlot) << (array->obj_sizeclass + 1); array = g->gc->New(numbytes, 0, format, true); array->classptr = slotRawObject(a)->classptr; array->size = slotRawObject(a)->size; memcpy(array->slots, slotRawObject(a)->slots, slotRawObject(a)->size * elemsize); SetRaw(a, array); } slots = array->slots; switch (format) { case obj_slot: slotCopy(&slots[array->size++], b); g->gc->GCWrite(array, b); break; case obj_int32: err = slotIntVal(b, &ival); if (err) return err; ((int32*)slots)[array->size++] = ival; break; case obj_int16: err = slotIntVal(b, &ival); if (err) return err; ((int16*)slots)[array->size++] = ival; break; case obj_int8: err = slotIntVal(b, &ival); if (err) return err; ((int8*)slots)[array->size++] = ival; break; case obj_char: if (NotChar(b)) return errWrongType; ((char*)slots)[array->size++] = slotRawChar(b); break; case obj_symbol: if (NotSym(b)) return errWrongType; ((PyrSymbol**)slots)[array->size++] = slotRawSymbol(b); break; case obj_float: err = slotDoubleVal(b, &fval); if (err) return err; ((float*)slots)[array->size++] = fval; break; case obj_double: err = slotDoubleVal(b, &fval); if (err) return err; ((double*)slots)[array->size++] = fval; break; } return errNone; } int prArrayInsert(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *slots1, *slots2; PyrObject *array, *oldarray; int err, ival; double fval; a = g->sp - 2; // array b = g->sp - 1; // index c = g->sp; // value if (NotInt(b)) return errWrongType; array = slotRawObject(a); const int format = slotRawObject(a)->obj_format; const int size = array->size; int index = slotRawInt(b); index = sc_clip(index, 0, size); const int remain = size - index; const int elemsize = gFormatElemSize[format]; const int maxelems = MAXINDEXSIZE(array); if (size + 1 > maxelems || array->IsImmutable()) { oldarray = array; const int numbytes = sizeof(PyrSlot) << (array->obj_sizeclass + 1); array = g->gc->New(numbytes, 0, format, true); array->classptr = oldarray->classptr; array->size = size + 1; SetRaw(a, array); slots1 = array->slots; slots2 = oldarray->slots; if (index) memcpy(slots1, slots2, index * elemsize); switch (format) { case obj_slot: slotCopy(&slots1[index], c); if (remain) memcpy(slots1 + index + 1, slots2 + index, remain * elemsize); if (!g->gc->ObjIsGrey(array)) g->gc->ToGrey(array); break; case obj_int32: err = slotIntVal(c, &ival); if (err) return err; ((int32*)slots1)[index] = ival; if (remain) { memcpy((int*)slots1 + index + 1, (int*)slots2 + index, remain * elemsize); } break; case obj_int16: err = slotIntVal(c, &ival); if (err) return err; ((int16*)slots1)[index] = ival; if (remain) { memcpy((short*)slots1 + index + 1, (short*)slots2 + index, remain * elemsize); } break; case obj_int8: err = slotIntVal(c, &ival); if (err) return err; ((int8*)slots1)[index] = ival; if (remain) { memcpy((char*)slots1 + index + 1, (char*)slots2 + index, remain * elemsize); } break; case obj_char: if (NotChar(c)) return errWrongType; ((char*)slots1)[index] = slotRawInt(c); if (remain) { memcpy((char*)slots1 + index + 1, (char*)slots2 + index, remain * elemsize); } break; case obj_symbol: if (NotSym(c)) return errWrongType; ((PyrSymbol**)slots1)[index] = slotRawSymbol(c); if (remain) { memcpy((int*)slots1 + index + 1, (int*)slots2 + index, remain * elemsize); } break; case obj_float: err = slotDoubleVal(c, &fval); if (err) return err; ((float*)slots1)[index] = fval; if (remain) { memcpy((float*)slots1 + index + 1, (float*)slots2 + index, remain * elemsize); } break; case obj_double: err = slotDoubleVal(c, &fval); if (err) return err; ((double*)slots1)[index] = fval; if (remain) { memcpy((double*)slots1 + index + 1, (double*)slots2 + index, remain * elemsize); } break; } } else { array->size = size + 1; slots1 = array->slots; switch (format) { case obj_slot: if (remain) memmove(slots1 + index + 1, slots1 + index, remain * elemsize); slotCopy(&slots1[index], c); if (!g->gc->ObjIsGrey(array)) g->gc->ToGrey(array); break; case obj_int32: if (remain) { memmove((int*)slots1 + index + 1, (int*)slots1 + index, remain * elemsize); } err = slotIntVal(c, &ival); if (err) return err; ((int32*)slots1)[index] = ival; break; case obj_int16: if (remain) { memmove((short*)slots1 + index + 1, (short*)slots1 + index, remain * elemsize); } err = slotIntVal(c, &ival); if (err) return err; ((int16*)slots1)[index] = ival; break; case obj_int8: if (remain) { memmove((char*)slots1 + index + 1, (char*)slots1 + index, remain * elemsize); } err = slotIntVal(c, &ival); if (err) return err; ((int8*)slots1)[index] = ival; break; case obj_char: if (remain) { memmove((char*)slots1 + index + 1, (char*)slots1 + index, remain * elemsize); } if (NotChar(c)) return errWrongType; ((char*)slots1)[index] = slotRawInt(c); break; case obj_symbol: if (remain) { memmove((int*)slots1 + index + 1, (int*)slots1 + index, remain * elemsize); } if (NotSym(c)) return errWrongType; ((PyrSymbol**)slots1)[index] = slotRawSymbol(c); break; case obj_float: if (remain) { memmove((float*)slots1 + index + 1, (float*)slots1 + index, remain * elemsize); } err = slotDoubleVal(c, &fval); if (err) return err; ((float*)slots1)[index] = fval; break; case obj_double: if (remain) { memmove((double*)slots1 + index + 1, (double*)slots1 + index, remain * elemsize); } err = slotDoubleVal(c, &fval); if (err) return err; ((double*)slots1)[index] = fval; break; } } return errNone; } int prArrayFill(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject* array; PyrSymbol* sym; int i; int format; int err, ival; double fval; a = g->sp - 1; b = g->sp; array = slotRawObject(a); format = slotRawObject(a)->obj_format; /*int tag = gFormatElemTag[format]; if (tag > 0) { if (GetTag(b) != tag) return errWrongType; } else if (tag == 0) { if (NotFloat(b)) return errWrongType; } // else format is obj_slot, any tag is acceptable*/ slots = array->slots; switch (format) { case obj_slot: if (array->IsImmutable()) return errImmutableObject; for (i = 0; i < array->size; ++i) { slotCopy(&slots[i], b); } g->gc->GCWrite(array, b); break; case obj_int32: err = slotIntVal(b, &ival); if (err) return err; for (i = 0; i < array->size; ++i) { ((int32*)slots)[i] = ival; } break; case obj_int16: err = slotIntVal(b, &ival); if (err) return err; for (i = 0; i < array->size; ++i) { ((int16*)slots)[i] = ival; } break; case obj_int8: err = slotIntVal(b, &ival); if (err) return err; for (i = 0; i < array->size; ++i) { ((int8*)slots)[i] = ival; } break; case obj_char: if (NotChar(b)) return errWrongType; ival = slotRawInt(b); for (i = 0; i < array->size; ++i) { ((char*)slots)[i] = ival; } break; case obj_symbol: if (NotSym(b)) return errWrongType; sym = slotRawSymbol(b); for (i = 0; i < array->size; ++i) { ((PyrSymbol**)slots)[i] = sym; } break; case obj_float: err = slotDoubleVal(b, &fval); if (err) return err; for (i = 0; i < array->size; ++i) { ((float*)slots)[i] = fval; } break; case obj_double: err = slotDoubleVal(b, &fval); if (err) return err; for (i = 0; i < array->size; ++i) { ((double*)slots)[i] = fval; } break; } return errNone; } int prArrayPop(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots; PyrObject* array; int z; int format; PyrSymbol* sym; a = g->sp; array = slotRawObject(a); if (array->IsImmutable()) return errImmutableObject; if (array->size > 0) { format = array->obj_format; slots = array->slots; switch (format) { case obj_slot: slotCopy(a, &slots[--array->size]); break; case obj_int32: z = ((int32*)slots)[--array->size]; SetInt(a, z); break; case obj_int16: z = ((int16*)slots)[--array->size]; SetInt(a, z); break; case obj_int8: z = ((int8*)slots)[--array->size]; SetInt(a, z); break; case obj_char: z = ((char*)slots)[--array->size]; SetChar(a, z); break; case obj_symbol: sym = ((PyrSymbol**)slots)[--array->size]; SetSymbol(a, sym); break; case obj_float: SetFloat(a, ((float*)slots)[--array->size]); break; case obj_double: SetFloat(a, slotRawFloat(&slots[--array->size])); break; } } else { slotCopy(a, &o_nil); } return errNone; } int prArrayExtend(struct VMGlobals* g, int numArgsPushed) { int numbytes, elemsize, format; int err; PyrSlot* a = g->sp - 2; // array PyrSlot* b = g->sp - 1; // size PyrSlot* c = g->sp; // filler item if (NotInt(b)) return errWrongType; PyrObject* aobj = slotRawObject(a); if (slotRawInt(b) <= aobj->size) { aobj->size = slotRawInt(b); return errNone; } format = aobj->obj_format; if (slotRawInt(b) > MAXINDEXSIZE(aobj) || aobj->IsImmutable()) { elemsize = gFormatElemSize[format]; numbytes = slotRawInt(b) * elemsize; PyrObject* obj = g->gc->New(numbytes, 0, format, true); obj->classptr = aobj->classptr; obj->size = aobj->size; memcpy(obj->slots, aobj->slots, aobj->size * elemsize); aobj = obj; SetRaw(a, aobj); } int fillSize = slotRawInt(b) - aobj->size; int32 ival; float fval; double dval; PyrSlot* slots = aobj->slots; switch (format) { case obj_slot: fillSlots(slots + aobj->size, fillSize, c); g->gc->GCWrite(aobj, c); break; case obj_int32: { int32* ptr = (int32*)slots + aobj->size; err = slotIntVal(c, &ival); if (err) return err; for (int i = 0; i < fillSize; ++i) ptr[i] = ival; } break; case obj_int16: { int16* ptr = (int16*)slots + aobj->size; err = slotIntVal(c, &ival); if (err) return err; for (int i = 0; i < fillSize; ++i) ptr[i] = ival; } break; case obj_int8: { int8* ptr = (int8*)slots + aobj->size; err = slotIntVal(c, &ival); if (err) return err; for (int i = 0; i < fillSize; ++i) ptr[i] = ival; } break; case obj_char: { char* ptr = (char*)slots + aobj->size; if (NotChar(c)) return errWrongType; ival = slotRawChar(c); for (int i = 0; i < fillSize; ++i) ptr[i] = ival; } break; case obj_symbol: { PyrSymbol** ptr = (PyrSymbol**)slots + aobj->size; if (NotSym(c)) return errWrongType; PyrSymbol* sym = slotRawSymbol(c); for (int i = 0; i < fillSize; ++i) ptr[i] = sym; } break; case obj_float: { float* ptr = (float*)slots + aobj->size; err = slotFloatVal(c, &fval); for (int i = 0; i < fillSize; ++i) ptr[i] = fval; } break; case obj_double: { double* ptr = (double*)slots + aobj->size; err = slotDoubleVal(c, &dval); for (int i = 0; i < fillSize; ++i) ptr[i] = dval; } break; } aobj->size = slotRawInt(b); return errNone; } int prArrayGrow(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject *obj, *aobj; int numbytes, elemsize, format; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; if (slotRawInt(b) <= 0) return errNone; aobj = slotRawObject(a); if (aobj->size + slotRawInt(b) <= MAXINDEXSIZE(aobj)) return errNone; format = aobj->obj_format; elemsize = gFormatElemSize[format]; numbytes = ((aobj->size + slotRawInt(b)) * elemsize); obj = g->gc->New(numbytes, 0, format, true); obj->classptr = aobj->classptr; obj->size = aobj->size; memcpy(obj->slots, aobj->slots, aobj->size * elemsize); SetRaw(a, obj); return errNone; } int prArrayGrowClear(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject *obj, *aobj; int numbytes, elemsize, format; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; if (slotRawInt(b) <= 0) return errNone; aobj = slotRawObject(a); if (aobj->size + slotRawInt(b) <= MAXINDEXSIZE(aobj) && aobj->IsMutable()) { obj = aobj; } else { format = aobj->obj_format; elemsize = gFormatElemSize[format]; numbytes = ((aobj->size + slotRawInt(b)) * elemsize); obj = g->gc->New(numbytes, 0, format, true); obj->classptr = aobj->classptr; memcpy(obj->slots, aobj->slots, aobj->size * elemsize); } if (obj->obj_format == obj_slot) { nilSlots(obj->slots + aobj->size, slotRawInt(b)); } else { memset((char*)(obj->slots) + aobj->size * gFormatElemSize[format], 0, slotRawInt(b) * gFormatElemSize[format]); } obj->size = aobj->size + slotRawInt(b); SetRaw(a, obj); return errNone; } int prArrayCat(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject *obj, *aobj, *bobj; int elemsize, size; int numbytes, format; a = g->sp - 1; b = g->sp; if (NotObj(b) || slotRawObject(a)->classptr != slotRawObject(b)->classptr) return errWrongType; aobj = slotRawObject(a); bobj = slotRawObject(b); size = aobj->size + bobj->size; format = aobj->obj_format; assert(aobj->obj_format == bobj->obj_format); elemsize = gFormatElemSize[format]; numbytes = (size * elemsize); obj = g->gc->New(numbytes, 0, format, true); obj->classptr = aobj->classptr; obj->size = size; memcpy(obj->slots, aobj->slots, aobj->size * elemsize); memcpy((char*)obj->slots + aobj->size * elemsize, bobj->slots, bobj->size * elemsize); SetObject(a, obj); return errNone; } int prArrayAddAll(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject *obj, *aobj; int elemsize, newindexedsize, newsizebytes, asize, bsize; int format; a = g->sp - 1; b = g->sp; if (NotObj(b) || slotRawObject(a)->classptr != slotRawObject(b)->classptr) return errWrongType; aobj = slotRawObject(a); format = aobj->obj_format; elemsize = gFormatElemSize[format]; asize = aobj->size; bsize = slotRawObject(b)->size; newindexedsize = asize + bsize; newsizebytes = newindexedsize * elemsize; if (newindexedsize > MAXINDEXSIZE(aobj) || aobj->IsImmutable()) { obj = g->gc->New(newsizebytes, 0, format, true); obj->classptr = aobj->classptr; memcpy(obj->slots, aobj->slots, asize * elemsize); SetObject(a, obj); } else { obj = aobj; if (format == obj_slot && !g->gc->ObjIsGrey(obj)) g->gc->ToGrey(obj); } obj->size = newindexedsize; memcpy((char*)obj->slots + asize * elemsize, slotRawObject(b)->slots, bsize * elemsize); return errNone; } int prArrayOverwrite(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; PyrObject *obj, *aobj; int err, elemsize, newindexedsize, newsizebytes, pos, asize, bsize; int format; a = g->sp - 2; b = g->sp - 1; c = g->sp; // pos if (NotObj(b) || slotRawObject(a)->classptr != slotRawObject(b)->classptr) return errWrongType; err = slotIntVal(c, &pos); if (err) return errWrongType; if (pos < 0 || pos > slotRawObject(a)->size) return errIndexOutOfRange; aobj = slotRawObject(a); format = aobj->obj_format; elemsize = gFormatElemSize[format]; asize = aobj->size; bsize = slotRawObject(b)->size; newindexedsize = pos + bsize; newindexedsize = sc_max(asize, newindexedsize); newsizebytes = newindexedsize * elemsize; if (newindexedsize > MAXINDEXSIZE(aobj) || aobj->IsImmutable()) { obj = g->gc->New(newsizebytes, 0, format, true); obj->classptr = aobj->classptr; memcpy(obj->slots, aobj->slots, asize * elemsize); SetObject(a, obj); } else { obj = aobj; if (format == obj_slot && !g->gc->ObjIsGrey(obj)) g->gc->ToGrey(obj); } obj->size = newindexedsize; memcpy((char*)(obj->slots) + pos * elemsize, slotRawObject(b)->slots, bsize * elemsize); return errNone; } int prArrayReverse(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots1, *slots2; PyrObject *obj1, *obj2; int i, j, size; a = g->sp; obj1 = slotRawObject(a); size = obj1->size; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); slots1 = obj1->slots; slots2 = obj2->slots; for (i = 0, j = size - 1; i < size; ++i, --j) { slotCopy(&slots2[j], &slots1[i]); } obj2->size = size; SetRaw(a, obj2); return errNone; } int prArrayScramble(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots1, *slots2, temp; PyrObject *obj1, *obj2; int i, j, k, m, size; a = g->sp; obj1 = slotRawObject(a); size = obj1->size; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); slots1 = obj1->slots; slots2 = obj2->slots; memcpy(slots2, slots1, size * sizeof(PyrSlot)); if (size > 1) { k = size; for (i = 0, m = k; i < k - 1; ++i, --m) { j = i + g->rgen->irand(m); slotCopy(&temp, &slots2[i]); slotCopy(&slots2[i], &slots2[j]); slotCopy(&slots2[j], &temp); } } obj2->size = size; SetRaw(a, obj2); return errNone; } int prArrayRotate(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject *obj1, *obj2; int i, j, n, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; obj1 = slotRawObject(a); size = obj1->size; n = sc_mod((int)slotRawInt(b), (int)size); slots = obj1->slots; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); for (i = 0, j = n; i < size; ++i) { slotCopy(&obj2->slots[j], &slots[i]); if (++j >= size) j = 0; } obj2->size = size; SetRaw(a, obj2); return errNone; } int prArrayDupEach(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots1, *slots2; PyrObject *obj1, *obj2; int i, j, k, m, n, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; obj1 = slotRawObject(a); n = slotRawInt(b); m = obj1->size; size = m * n; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); slots1 = obj1->slots; slots2 = obj2->slots; for (i = 0, j = 0; i < m; ++i) { for (k = 0; k < n; ++k, ++j) { slotCopy(&slots2[j], &slots1[i]); } } obj2->size = size; SetRaw(a, obj2); return errNone; } int prArrayMirror(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots; PyrObject *obj1, *obj2; int i, j, k, size; a = g->sp; obj1 = slotRawObject(a); slots = obj1->slots; size = std::max(obj1->size * 2 - 1, 0); obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; // copy first part of list memcpy(obj2->slots, slots, obj1->size * sizeof(PyrSlot)); // copy second part k = size / 2; for (i = 0, j = size - 1; i < k; ++i, --j) { slotCopy(&obj2->slots[j], &slots[i]); } SetRaw(a, obj2); return errNone; } int prArrayMirror1(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots; PyrObject *obj1, *obj2; int i, j, k, size; a = g->sp; obj1 = slotRawObject(a); slots = obj1->slots; size = std::max(obj1->size * 2 - 2, obj1->size); obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; memcpy(obj2->slots, slots, obj1->size * sizeof(PyrSlot)); // copy second part k = size / 2; for (i = 1, j = size - 1; i < k; ++i, --j) { slotCopy(&obj2->slots[j], &slots[i]); } SetRaw(a, obj2); return errNone; } int prArrayMirror2(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots; PyrObject *obj1, *obj2; int i, j, k, size; a = g->sp; obj1 = slotRawObject(a); slots = obj1->slots; size = obj1->size * 2; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; // copy first part of list memcpy(obj2->slots, slots, obj1->size * sizeof(PyrSlot)); // copy second part k = size / 2; for (i = 0, j = size - 1; i < k; ++i, --j) { slotCopy(&obj2->slots[j], &slots[i]); } SetRaw(a, obj2); return errNone; } int prArrayExtendWrap(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject *obj1, *obj2; int i, j, m, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; size = slotRawInt(b); if (size < 0) return errFailed; obj1 = slotRawObject(a); if (obj1->size > 0) { obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; slots = obj2->slots; // copy first part of list memcpy(slots, obj1->slots, sc_min(size, obj1->size) * sizeof(PyrSlot)); if (size > obj1->size) { // copy second part m = obj1->size; for (i = 0, j = m; j < size; ++i, ++j) { slotCopy(&slots[j], &slots[i]); } } } else { obj2 = instantiateObject(g->gc, obj1->classptr, size, true, true); } SetRaw(a, obj2); return errNone; } int prArrayExtendFold(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject *obj1, *obj2; int i, j, m, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; size = slotRawInt(b); if (size < 0) return errFailed; obj1 = slotRawObject(a); if (obj1->size > 0) { obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; slots = obj2->slots; // copy first part of list memcpy(slots, obj1->slots, sc_min(size, obj1->size) * sizeof(PyrSlot)); if (size > obj1->size) { // copy second part m = obj1->size; for (i = 0, j = m; j < size; ++i, ++j) { slotCopy(&slots[j], &slots[sc_fold(j, 0, m - 1)]); } } } else { obj2 = instantiateObject(g->gc, obj1->classptr, size, true, true); } SetRaw(a, obj2); return errNone; } int prArrayExtendLast(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots, last; PyrObject *obj1, *obj2; int i, j, m, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; size = slotRawInt(b); if (size < 0) return errFailed; obj1 = slotRawObject(a); if (obj1->size > 0) { obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; slots = obj2->slots; // copy first part of list memcpy(slots, obj1->slots, sc_min(size, obj1->size) * sizeof(PyrSlot)); if (size > obj1->size) { // copy second part m = obj1->size; slotCopy(&last, &slots[m - 1]); for (i = 0, j = m; j < size; ++i, ++j) slotCopy(&slots[j], &last); } } else { obj2 = instantiateObject(g->gc, obj1->classptr, size, true, true); } SetRaw(a, obj2); return errNone; } int prArrayPermute(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots1, *slots2, temp; PyrObject *obj1, *obj2; int i, j, m, z, size; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; obj1 = slotRawObject(a); size = obj1->size; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); obj2->size = size; slots1 = obj1->slots; slots2 = obj2->slots; memcpy(slots2, slots1, size * sizeof(PyrSlot)); z = slotRawInt(b); for (i = 0, m = size; i < size - 1; ++i, --m) { j = i + sc_mod((int)z, (int)(size - i)); z = sc_div(z, size - i); slotCopy(&temp, &slots2[i]); slotCopy(&slots2[i], &slots2[j]); slotCopy(&slots2[j], &temp); } SetRaw(a, obj2); return errNone; } int prArrayAllTuples(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots1, *slots2, *slots3, *slotToCopy; PyrObject *obj1, *obj2, *obj3; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; int maxSize = slotRawInt(b); obj1 = slotRawObject(a); slots1 = obj1->slots; int newSize = 1; int tupSize = obj1->size; for (int i = 0; i < tupSize; ++i) { if (isKindOfSlot(slots1 + i, class_array)) { newSize *= slotRawObject(&slots1[i])->size; } } if (newSize > maxSize) newSize = maxSize; obj2 = instantiateObject(g->gc, obj1->classptr, newSize, false, true); slots2 = obj2->slots; SetObject(b, obj2); // store reference on stack, so both source and destination objects can be reached by the gc for (int i = 0; i < newSize; ++i) { int k = i; obj3 = instantiateObject(g->gc, obj1->classptr, tupSize, false, true); slots3 = obj3->slots; for (int j = tupSize - 1; j >= 0; --j) { if (isKindOfSlot(slots1 + j, class_array)) { PyrObject* obj4 = slotRawObject(&slots1[j]); slotToCopy = &obj4->slots[k % obj4->size]; slotCopy(&slots3[j], slotToCopy); g->gc->GCWrite(obj3, slotToCopy); k /= obj4->size; } else { slotToCopy = &slots1[j]; slotCopy(&slots3[j], slotToCopy); g->gc->GCWrite(obj3, slotToCopy); } } obj3->size = tupSize; SetObject(obj2->slots + i, obj3); g->gc->GCWriteNew(obj2, obj3); obj2->size++; } SetRaw(a, obj2); return errNone; } int prArrayPyramid(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject *obj1, *obj2; int i, j, k, n, m, numslots, x; a = g->sp - 1; b = g->sp; if (NotInt(b)) return errWrongType; obj1 = slotRawObject(a); slots = obj1->slots; m = sc_clip(slotRawInt(b), 1, 10); x = numslots = obj1->size; switch (m) { case 1: n = (x * x + x) / 2; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = 0; j <= i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 2: n = (x * x + x) / 2; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = numslots - 1 - i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 3: n = (x * x + x) / 2; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = 0; j <= numslots - 1 - i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 4: n = (x * x + x) / 2; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 5: n = x * x; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = 0; j <= i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 0; i < numslots - 1; ++i) { for (j = 0; j <= numslots - 2 - i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 6: n = x * x; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = numslots - 1 - i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 0; i < numslots - 1; ++i) { for (j = i + 1; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 7: n = x * x + x - 1; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = 0; j <= numslots - 1 - i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 1; i < numslots; ++i) { for (j = 0; j <= i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 8: n = x * x + x - 1; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 1; i < numslots; ++i) { for (j = numslots - 1 - i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 9: n = x * x; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = 0; j <= i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 0; i < numslots - 1; ++i) { for (j = i + 1; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; case 10: n = x * x; obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = 0, k = 0; i < numslots; ++i) { for (j = numslots - 1 - i; j <= numslots - 1; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } for (i = 0; i < numslots - 1; ++i) { for (j = 0; j <= numslots - 2 - i; ++j, ++k) { slotCopy(&obj2->slots[k], &slots[j]); } } obj2->size = k; break; } SetRaw(a, obj2); return errNone; } int prArraySlide(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *slots; PyrObject *obj1, *obj2; int h, i, j, k, numslots, numwin; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotInt(b)) return errWrongType; if (NotInt(c)) return errWrongType; obj1 = slotRawObject(a); slots = obj1->slots; int m = slotRawInt(b); int n = slotRawInt(c); if (n <= 0) return errFailed; numwin = (obj1->size + n - m) / n; numslots = numwin * m; obj2 = instantiateObject(g->gc, obj1->classptr, numslots, false, true); for (i = h = k = 0; i < numwin; ++i, h += n) { for (j = h; j < m + h; ++j) slotCopy(&obj2->slots[k++], &slots[j]); } obj2->size = k; SetRaw(a, obj2); return errNone; } int prArrayLace(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots, *slot; PyrObject *obj1, *obj2, *obj3; int i, j, k, n, m, numLists, len; a = g->sp - 1; b = g->sp; obj1 = slotRawObject(a); slots = obj1->slots; numLists = obj1->size; if (IsNil(b)) { // If length argument is unspecified, compute length as the multiple of // the length of the shortest sub-array and the number of sub-arrays. for (j = 0; j < numLists; ++j) { slot = slots + j; if (isKindOfSlot(slot, class_list)) { obj2 = slotRawObject(slot); slot = &obj2->slots[0]; } if (isKindOfSlot(slot, class_array)) { len = slotRawObject(slot)->size; if (j == 0 || n > len) { n = len; } } else { // If not an array we assume a max per-element length of one. n = 1; break; } } n = n * numLists; } else if (IsInt(b)) { n = slotRawInt(b); } else { return errWrongType; } n = sc_max(1, n); if (obj1->size > 0) { obj2 = instantiateObject(g->gc, obj1->classptr, n, false, true); for (i = j = k = 0; i < n; ++i) { if (IsObj(&slots[k])) { obj3 = slotRawObject(&slots[k]); if (isKindOf(obj3, class_list)) { obj3 = slotRawObject(&obj3->slots[0]); // get the list's array } if (obj3 && isKindOf(obj3, class_array)) { if (obj3->size > 0) { m = j % obj3->size; slotCopy(&obj2->slots[i], &obj3->slots[m]); } else { SetNil(&obj2->slots[i]); } } else { slotCopy(&obj2->slots[i], &slots[k]); } } else { slotCopy(&obj2->slots[i], &slots[k]); } k = (k + 1) % obj1->size; if (k == 0) j++; } obj2->size = n; } else { if (isKindOf(obj1, class_array)) { obj2 = newPyrArray(g->gc, 0, 0, true); } else { obj2 = instantiateObject(g->gc, obj1->classptr, n, true, true); obj2->size = n; } } SetRaw(a, obj2); return errNone; } int prArrayContainsSeqColl(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slot, *endptr; PyrObject* obj; int size; a = g->sp; obj = slotRawObject(a); size = obj->size; slot = obj->slots - 1; endptr = slot + size; while (slot < endptr) { ++slot; if (IsObj(slot)) { if (isKindOf(slotRawObject(slot), class_sequenceable_collection)) { SetTrue(a); return errNone; } } } SetFalse(a); return errNone; } int prArrayNormalizeSum(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots2; PyrObject *obj1, *obj2; int i, size, err; double w, sum, rsum; a = g->sp; obj1 = slotRawObject(a); size = obj1->size; obj2 = instantiateObject(g->gc, obj1->classptr, size, false, true); slots2 = obj2->slots; sum = 0.0; for (i = 0; i < size; ++i) { err = getIndexedDouble(obj1, i, &w); if (err) return err; sum += w; SetFloat(&slots2[i], w); } rsum = 1. / sum; for (i = 0; i < size; ++i) { double d = slotRawFloat(&slots2[i]); SetRaw(&slots2[i], d * rsum); } obj2->size = size; SetRaw(a, obj2); return errNone; } int prArrayWIndex(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slots; PyrObject* obj; int i, j, size, err; double r, w, sum; a = g->sp; sum = 0.0; r = g->rgen->frand(); obj = slotRawObject(a); size = obj->size; j = size - 1; slots = obj->slots; for (i = 0; i < size; ++i) { err = getIndexedDouble(obj, i, &w); if (err) return err; sum += w; if (sum >= r) { j = i; break; } } SetInt(a, j); return errNone; } enum { shape_Step, shape_Linear, shape_Exponential, shape_Sine, shape_Welch, shape_Curve, shape_Squared, shape_Cubed, shape_Hold }; enum { kEnv_initLevel, kEnv_numStages, kEnv_releaseNode, kEnv_loopNode }; int prArrayEnvAt(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; PyrObject* env = slotRawObject(a); PyrSlot* slots = env->slots; // Env:asArray always gives at least 8 array elements if (env->size < 8) return errFailed; double time; int err = slotDoubleVal(b, &time); if (err) return err; double begLevel; err = slotDoubleVal(slots + kEnv_initLevel, &begLevel); if (err) return err; int numStages; err = slotIntVal(slots + kEnv_numStages, &numStages); if (err) return err; double begTime = 0.; double endTime = 0.; for (int i = 0; i < numStages; ++i) { double dur, endLevel; slots += 4; err = slotDoubleVal(slots + 0, &endLevel); if (err) return err; err = slotDoubleVal(slots + 1, &dur); if (err) return err; endTime += dur; // post("%d %g %g %g %g %g\n", i, time, begTime, endTime, dur, endLevel); if (time < endTime) { int shape; double curve; err = slotIntVal(slots + 2, &shape); if (err) return err; double level; double pos = (time - begTime) / dur; // post(" shape %d pos %g\n", shape, pos); switch (shape) { case shape_Step: level = endLevel; break; case shape_Hold: level = begLevel; break; case shape_Linear: default: level = pos * (endLevel - begLevel) + begLevel; break; case shape_Exponential: level = begLevel * pow(endLevel / begLevel, pos); break; case shape_Sine: level = begLevel + (endLevel - begLevel) * (-cos(pi * pos) * 0.5 + 0.5); break; case shape_Welch: { if (begLevel < endLevel) level = begLevel + (endLevel - begLevel) * sin(pi2 * pos); else level = endLevel - (endLevel - begLevel) * sin(pi2 - pi2 * pos); break; } case shape_Curve: err = slotDoubleVal(slots + 3, &curve); if (err) return err; if (fabs(curve) < 0.0001) { level = pos * (endLevel - begLevel) + begLevel; } else { double denom = 1. - exp(curve); double numer = 1. - exp(pos * curve); level = begLevel + (endLevel - begLevel) * (numer / denom); } break; case shape_Squared: { double sqrtBegLevel = sqrt(begLevel); double sqrtEndLevel = sqrt(endLevel); double sqrtLevel = pos * (sqrtEndLevel - sqrtBegLevel) + sqrtBegLevel; level = sqrtLevel * sqrtLevel; break; } case shape_Cubed: { double cbrtBegLevel = pow(begLevel, 0.3333333); double cbrtEndLevel = pow(endLevel, 0.3333333); double cbrtLevel = pos * (cbrtEndLevel - cbrtBegLevel) + cbrtBegLevel; level = cbrtLevel * cbrtLevel * cbrtLevel; break; } } SetFloat(a, level); return errNone; } begTime = endTime; begLevel = endLevel; } SetFloat(a, begLevel); return errNone; } int prArrayIndexOfGreaterThan(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *slots; PyrObject* obj; int i, size, err; double s, w; a = g->sp - 1; b = g->sp; obj = slotRawObject(a); size = obj->size; slots = obj->slots; err = slotDoubleVal(b, &s); if (err) return err; for (i = 0; i < size; ++i) { err = getIndexedDouble(obj, i, &w); if (err) return err; if (w > s) { SetInt(a, i); return errNone; } } SetNil(a); return errNone; } int prArrayUnlace(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *slots, *slots2, *slots3; PyrObject *obj1, *obj2, *obj3; int i, j, k, clump, numLists, size, size3, err; a = g->sp - 2; b = g->sp - 1; c = g->sp; obj1 = slotRawObject(a); slots = obj1->slots; size = obj1->size; err = slotIntVal(b, &numLists); if (err) return err; err = slotIntVal(c, &clump); if (err) return err; obj2 = instantiateObject(g->gc, obj1->classptr, numLists, false, true); slots2 = obj2->slots; SetObject(b, obj2); // store reference on stack, so both source and destination objects can be reached by the gc size3 = size / numLists; size3 = size3 - (size3 % clump); if (size3 < 1) return errFailed; for (i = 0; i < numLists; ++i) { obj3 = instantiateObject(g->gc, obj1->classptr, size3, false, true); obj3->size = size3; slots3 = obj3->slots; for (j = 0; j < size3; j += clump) { for (k = 0; k < clump; ++k) { slotCopy(&slots3[j + k], &slots[i * clump + k + j * numLists]); } } SetObject(slots2 + i, obj3); g->gc->GCWriteNew(obj2, obj3); // we know obj3 is white so we can use GCWriteNew obj2->size++; } SetRaw(a, obj2); return errNone; } template <typename T> int levenshteinDistanceImpl( PyrSlot* result, const PyrObject* a, const PyrObject* b, std::function<bool(const T&, const T&)> compareFunc = [](const T& a, const T& b) { return a == b; }) { size_t distance = levenshteinDistance<T>()(reinterpret_cast<const T*>(a->slots), a->size, reinterpret_cast<const T*>(b->slots), b->size, compareFunc); SetInt(result, static_cast<int>(distance)); return errNone; } int arrayLevenshteinDistance(PyrSlot* result, const PyrObject* thisArray, const PyrObject* thatArray) { // if they're both the same format we can compare them.. if (thisArray->obj_format == thatArray->obj_format) { switch (thisArray->obj_format) { // if they're raw arrays, compare as such case obj_char: return levenshteinDistanceImpl<char>(result, thisArray, thatArray); case obj_double: return levenshteinDistanceImpl<double>(result, thisArray, thatArray); case obj_float: return levenshteinDistanceImpl<float>(result, thisArray, thatArray); case obj_int16: return levenshteinDistanceImpl<int16>(result, thisArray, thatArray); case obj_int32: return levenshteinDistanceImpl<int32>(result, thisArray, thatArray); case obj_int8: return levenshteinDistanceImpl<int8>(result, thisArray, thatArray); case obj_symbol: // pass them in as slots, compare as raw symbols return levenshteinDistanceImpl<PyrSlot>( result, thisArray, thatArray, [](const PyrSlot& a, const PyrSlot& b) { return slotRawSymbol(&a) == slotRawSymbol(&b); }); case obj_slot: // if it is slotted, compare identities // this will handle polymorphic arrays in a predictable way return levenshteinDistanceImpl<PyrSlot>(result, thisArray, thatArray, [](const PyrSlot& a, const PyrSlot& b) { return SlotEq(&a, &b); }); default: return errWrongType; } } else { return errWrongType; } } int prArrayLevenshteinDistance(struct VMGlobals* g, int numArgsPushed) { auto* slotThatArray = g->sp; auto* slotThisArray = g->sp - 1; if (NotObj(slotThisArray) || NotObj(slotThatArray)) return errWrongType; auto* objThisArray = slotRawObject(slotThisArray); auto* objThatArray = slotRawObject(slotThatArray); if (!(slotRawInt(&objThisArray->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; if (!(slotRawInt(&objThatArray->classptr->classFlags) & classHasIndexableInstances)) return errNotAnIndexableObject; return arrayLevenshteinDistance(slotThisArray, objThisArray, objThatArray); } struct IsRectangularResult { // an int with three special values // -1: depth first searching the array has reached something isn't an array (nesting terminator), // this is a 'truthy' result. // -2: the array is not rectangular, a valid false result. // -3: one of the children was a Collection, but not an arrayed collection. An error. [[nodiscard]] static constexpr IsRectangularResult make_size(int sz) { assert(sz >= 0); return IsRectangularResult(sz); } [[nodiscard]] static constexpr IsRectangularResult make_nesting_terminator() { return IsRectangularResult(-1); } [[nodiscard]] static constexpr IsRectangularResult make_false_result() { return IsRectangularResult(-2); } [[nodiscard]] static constexpr IsRectangularResult make_type_error() { return IsRectangularResult(-3); } [[nodiscard]] constexpr bool is_valid() const noexcept { return m_value >= 0 || m_value == make_nesting_terminator(); } [[nodiscard]] constexpr bool is_type_error() const noexcept { return m_value == make_type_error(); } // implicitly converts to int. constexpr operator int() const noexcept { return m_value; } private: constexpr explicit IsRectangularResult(int i) noexcept: m_value(i) {} int m_value; }; // Does a depth first check of the size and shape. // On left most path, inserts the size. inline IsRectangularResult is_rectangular(const PyrSlot* a, std::vector<IsRectangularResult>& expected_size, uint32_t depth, bool is_left_most) { // no Lists, only derived classes of ArrayedCollection! if (isKindOfSlot(a, class_sequenceable_collection) && !isKindOfSlot(a, class_arrayed_collection)) { return IsRectangularResult::make_type_error(); } // 'a' is not an array if (!IsObj(a) || !isKindOfSlot(a, class_arrayed_collection)) { // has not reached this depth before if (expected_size.size() < depth + 1) { if (!is_left_most) return IsRectangularResult::make_false_result(); // did not match // ensure other nested array always terminates at this depth expected_size.push_back(IsRectangularResult::make_nesting_terminator()); } return expected_size[depth] != IsRectangularResult::make_nesting_terminator() ? IsRectangularResult::make_false_result() : IsRectangularResult::make_nesting_terminator(); } // 'a' is an array. const PyrObject* obj = slotRawObject(a); const int size = obj->size; if (expected_size.size() < depth + 1) { if (!is_left_most) return IsRectangularResult::make_false_result(); expected_size.push_back(IsRectangularResult::make_size(size)); } // mismatch if (size != expected_size[depth]) return IsRectangularResult::make_false_result(); // raw arrays are functors over exactly one type, which is always a c++ scalar type // (https://en.cppreference.com/w/cpp/types/is_scalar) // therefore the size can be returned without checking if (isKindOf(obj, class_rawarray)) return IsRectangularResult::make_size(size); // early return for no children if (size <= 0) return IsRectangularResult::make_size(0); // iterator over the children const PyrSlot* item_at_index = obj->slots; // left most path, inserts expected_size const auto first_sz = is_rectangular(item_at_index, expected_size, depth + 1, is_left_most); if (!first_sz.is_valid()) return first_sz; for (int i = 1; i < size; ++i) { const auto this_sz = is_rectangular(item_at_index + i, expected_size, depth + 1, false); if (!this_sz.is_valid()) return this_sz; else if (this_sz != first_sz) return IsRectangularResult::make_false_result(); else continue; } return IsRectangularResult::make_size(size); } int prArrayIsRectangular(struct VMGlobals* g, int numArgsPushed) { // checks array's sub arrays all have the same size, recurs on those sub arrays to check them PyrSlot* array = g->sp; if (!isKindOfSlot(array, class_arrayed_collection)) return errWrongType; std::vector<IsRectangularResult> expected_shape; const auto r = is_rectangular(array, expected_shape, 0, true); if (r.is_type_error()) { post("Subarray was not an instance of ArrayedCollection.\n"); SetNil(array); return errWrongType; } else { SetBool(array, r.is_valid()); return errNone; } } void initArrayPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_BasicSize", basicSize, 1, 0); definePrimitive(base, index++, "_BasicMaxSize", basicMaxSize, 1, 0); definePrimitive(base, index++, "_BasicSwap", basicSwap, 3, 0); definePrimitive(base, index++, "_BasicAt", basicAt, 2, 0); definePrimitive(base, index++, "_BasicRemoveAt", basicRemoveAt, 2, 0); definePrimitive(base, index++, "_BasicTakeAt", basicTakeAt, 2, 0); definePrimitive(base, index++, "_BasicClipAt", basicClipAt, 2, 0); definePrimitive(base, index++, "_BasicWrapAt", basicWrapAt, 2, 0); definePrimitive(base, index++, "_BasicFoldAt", basicFoldAt, 2, 0); definePrimitive(base, index++, "_BasicPut", basicPut, 3, 0); definePrimitive(base, index++, "_BasicClipPut", basicClipPut, 3, 0); definePrimitive(base, index++, "_BasicWrapPut", basicWrapPut, 3, 0); definePrimitive(base, index++, "_BasicFoldPut", basicFoldPut, 3, 0); definePrimitive(base, index++, "_ArrayExtend", prArrayExtend, 3, 0); definePrimitive(base, index++, "_ArrayGrow", prArrayGrow, 2, 0); definePrimitive(base, index++, "_ArrayGrowClear", prArrayGrowClear, 2, 0); definePrimitive(base, index++, "_ArrayAdd", prArrayAdd, 2, 0); definePrimitive(base, index++, "_ArrayInsert", prArrayInsert, 3, 0); definePrimitive(base, index++, "_ArrayFill", prArrayFill, 2, 0); definePrimitive(base, index++, "_ArrayPop", prArrayPop, 1, 0); definePrimitive(base, index++, "_ArrayCat", prArrayCat, 2, 0); definePrimitive(base, index++, "_ArrayPutEach", prArrayPutEach, 3, 0); definePrimitive(base, index++, "_ArrayAddAll", prArrayAddAll, 2, 0); definePrimitive(base, index++, "_ArrayPutSeries", prArrayPutSeries, 5, 0); definePrimitive(base, index++, "_ArrayOverwrite", prArrayOverwrite, 3, 0); definePrimitive(base, index++, "_ArrayIndexOf", prArrayIndexOf, 2, 0); definePrimitive(base, index++, "_ArrayNormalizeSum", prArrayNormalizeSum, 1, 0); definePrimitive(base, index++, "_ArrayWIndex", prArrayWIndex, 1, 0); definePrimitive(base, index++, "_ArrayReverse", prArrayReverse, 1, 0); definePrimitive(base, index++, "_ArrayScramble", prArrayScramble, 1, 0); definePrimitive(base, index++, "_ArrayMirror", prArrayMirror, 1, 0); definePrimitive(base, index++, "_ArrayMirror1", prArrayMirror1, 1, 0); definePrimitive(base, index++, "_ArrayMirror2", prArrayMirror2, 1, 0); definePrimitive(base, index++, "_ArrayRotate", prArrayRotate, 2, 0); definePrimitive(base, index++, "_ArrayPermute", prArrayPermute, 2, 0); definePrimitive(base, index++, "_ArrayAllTuples", prArrayAllTuples, 2, 0); definePrimitive(base, index++, "_ArrayPyramid", prArrayPyramid, 2, 0); definePrimitive(base, index++, "_ArrayRotate", prArrayRotate, 2, 0); definePrimitive(base, index++, "_ArrayExtendWrap", prArrayExtendWrap, 2, 0); definePrimitive(base, index++, "_ArrayExtendFold", prArrayExtendFold, 2, 0); definePrimitive(base, index++, "_ArrayExtendLast", prArrayExtendLast, 2, 0); definePrimitive(base, index++, "_ArrayLace", prArrayLace, 2, 0); definePrimitive(base, index++, "_ArrayDupEach", prArrayDupEach, 2, 0); definePrimitive(base, index++, "_ArraySlide", prArraySlide, 3, 0); definePrimitive(base, index++, "_ArrayContainsSeqColl", prArrayContainsSeqColl, 1, 0); definePrimitive(base, index++, "_ArrayEnvAt", prArrayEnvAt, 2, 0); definePrimitive(base, index++, "_ArrayIndexOfGreaterThan", prArrayIndexOfGreaterThan, 2, 0); definePrimitive(base, index++, "_ArrayUnlace", prArrayUnlace, 3, 0); definePrimitive(base, index++, "_ArrayLevenshteinDistance", prArrayLevenshteinDistance, 2, 0); definePrimitive(base, index++, "_ArrayIsRectangular", prArrayIsRectangular, 1, 0); }
79,871
C++
.cpp
2,363
25.607279
119
0.546942
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
29,879
PyrListPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrListPrim.cpp
/* 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 "PyrKernel.h" #include "PyrKernelProto.h" #include "PyrPrimitive.h" #include "PyrPrimitiveProto.h" #include "PyrSymbol.h" #include "PyrListPrim.h" #include "SC_InlineUnaryOp.h" #include "SC_InlineBinaryOp.h" #include "PyrSignal.h" #include "PyrMessage.h" #include "PyrSched.h" #include "SC_RGen.h" #include "SCBase.h" #include <stdlib.h> #include <string.h> int ivxIdentDict_array, ivxIdentDict_size, ivxIdentDict_parent, ivxIdentDict_proto, ivxIdentDict_know; int class_array_index, class_array_maxsubclassindex; int class_identdict_index, class_identdict_maxsubclassindex; PyrClass* class_identdict; PyrSymbol *s_proto, *s_parent; PyrSymbol *s_delta, *s_dur, *s_stretch; // used in prEvent_IsRest PyrSymbol *s_type, *s_rest, *s_empty, *s_r, *s_isRest; PyrClass *class_rest, *class_metarest; #define HASHSYMBOL(sym) (sym >> 5) #define ISKINDOF(obj, lo, hi) \ (objClassIndex = slotRawInt(&obj->classptr->classIndex), objClassIndex >= lo && objClassIndex <= hi) int prArrayMultiChanExpand(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *slot, *slots1, *slots2, *slots3, *slots4; PyrObject *obj1, *obj2, *obj3, *obj4; int i, j, size, len, maxlen; a = g->sp; obj1 = slotRawObject(a); size = obj1->size; slots1 = obj1->slots; maxlen = 1; for (j = 0; j < size; ++j) { slot = slots1 + j; if (IsObj(slot)) { if (slotRawObject(slot)->classptr == class_array) { len = slotRawObject(slot)->size; maxlen = len > maxlen ? len : maxlen; } else if (isKindOf(slotRawObject(slot), class_sequenceable_collection) && (slotRawObject(slot)->classptr != class_string)) { return errFailed; // this primitive only handles Arrays. } } } obj2 = newPyrArray(g->gc, maxlen, 0, true); // push obj2 onto the stack so it's not collected // we can't just set in a here as we still need obj1's slots below, so we need to ensure it isn't collected ++g->sp; // advance the stack to avoid overwriting receiver SetObject(g->sp, obj2); slots2 = obj2->slots; for (i = 0; i < maxlen; ++i) { obj3 = newPyrArray(g->gc, size, 0, true); obj3->size = size; SetObject(slots2 + i, obj3); g->gc->GCWriteNew(obj2, obj3); // we know obj3 is white so we can use GCWriteNew obj2->size++; slots1 = obj1->slots; slots3 = obj3->slots; for (j = 0; j < size; ++j) { slot = slots1 + j; if (IsObj(slot)) { if (slotRawObject(slot)->classptr == class_array && slotRawObject(slot)->size > 0) { PyrSlot* slotToCopy; obj4 = slotRawObject(slot); slots4 = obj4->slots; slotToCopy = &slots4[i % obj4->size]; slotCopy(&slots3[j], slotToCopy); g->gc->GCWrite(obj3, slotToCopy); } else { slotCopy(&slots3[j], slot); g->gc->GCWrite(obj3, slot); } } else { slotCopy(&slots3[j], slot); // we don't need GCWrite here, as slot is not an object } } } --g->sp; // pop the stack back to the receiver slot since we stored ojb2 there above SetObject(a, obj2); // now we can set the result in a return errNone; } int arrayAtIdentityHash(PyrObject* array, PyrSlot* key) { PyrSlot *slots, *test; unsigned int i, start, end, hash, maxHash; hash = calcHash(key); maxHash = array->size; start = hash % maxHash; end = array->size; slots = array->slots; for (i = start; i < end; i++) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } end = start - 1; for (i = 0; i <= end; i++) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } return -1; } int prArray_AtIdentityHash(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; PyrObject* array; int index; a = g->sp - 1; // array b = g->sp; // key array = slotRawObject(a); if (array->size == 0) return errFailed; index = arrayAtIdentityHash(array, b); SetInt(a, index); return errNone; } int arrayAtIdentityHashInPairs(PyrObject* array, PyrSlot* key) { PyrSlot *slots, *test; unsigned int i, start, end, hash, maxHash; hash = calcHash(key); maxHash = array->size >> 1; start = (hash % maxHash) << 1; end = array->size; slots = array->slots; for (i = start; i < end; i += 2) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } end = start - 2; for (i = 0; i <= end; i += 2) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } return -2; } int arrayAtIdentityHashInPairsWithHash(PyrObject* array, PyrSlot* key, int hash) { PyrSlot *slots, *test; unsigned int i, start, end, maxHash; maxHash = array->size >> 1; start = (hash % maxHash) << 1; end = array->size; slots = array->slots; for (i = start; i < end; i += 2) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } end = start - 2; for (i = 0; i <= end; i += 2) { test = slots + i; if (IsNil(test) || SlotEq(test, key)) return i; } return -2; } int identDictPut(struct VMGlobals* g, PyrObject* dict, PyrSlot* key, PyrSlot* value) { PyrSlot *slot, *newslot; int i, index, size; PyrObject* array; bool knows = IsTrue(dict->slots + ivxIdentDict_know); if (knows && IsSym(key)) { if (slotRawSymbol(key) == s_parent) { slotCopy(&dict->slots[ivxIdentDict_parent], value); g->gc->GCWrite(dict, value); return errNone; } if (slotRawSymbol(key) == s_proto) { slotCopy(&dict->slots[ivxIdentDict_proto], value); g->gc->GCWrite(dict, value); return errNone; } } array = slotRawObject(&dict->slots[ivxIdentDict_array]); if (array->IsImmutable()) return errImmutableObject; if (!isKindOf((PyrObject*)array, class_array)) return errFailed; index = arrayAtIdentityHashInPairs(array, key); slot = array->slots + index; slotCopy(&slot[1], value); g->gc->GCWrite(array, value); if (IsNil(slot)) { slotCopy(slot, key); g->gc->GCWrite(array, key); size = slotRawInt(&dict->slots[ivxIdentDict_size]) + 1; SetRaw(&dict->slots[ivxIdentDict_size], size); if (array->size < size * 3) { PyrObject* newarray; newarray = newPyrArray(g->gc, size * 3, 0, false); newarray->size = ARRAYMAXINDEXSIZE(newarray); nilSlots(newarray->slots, newarray->size); slot = array->slots; for (i = 0; i < array->size; i += 2, slot += 2) { if (NotNil(slot)) { index = arrayAtIdentityHashInPairs(newarray, slot); newslot = newarray->slots + index; slotCopy(&newslot[0], &slot[0]); slotCopy(&newslot[1], &slot[1]); } } SetRaw(&dict->slots[ivxIdentDict_array], newarray); g->gc->GCWriteNew(dict, newarray); // we know newarray is white so we can use GCWriteNew } } return errNone; } int prIdentDict_Put(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; a = g->sp - 2; // dict b = g->sp - 1; // key c = g->sp; // value if (IsNil(b)) return errWrongType; if (IsNil(c)) return errFailed; // will call removeAt return identDictPut(g, slotRawObject(a), b, c); } int prIdentDict_PutGet(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *d, *slot, *newslot; int i, index, size; PyrObject* dict; PyrObject* array; a = g->sp - 2; // dict b = g->sp - 1; // key c = g->sp; // value d = ++g->sp; // push the stack to save the receiver slotCopy(d, a); dict = slotRawObject(d); array = slotRawObject(&dict->slots[ivxIdentDict_array]); if (!isKindOf((PyrObject*)array, class_array)) { SetNil(a); --g->sp; return errFailed; } index = arrayAtIdentityHashInPairs(array, b); slot = array->slots + index; slotCopy(a, &slot[1]); slotCopy(&slot[1], c); g->gc->GCWrite(array, c); if (IsNil(slot)) { slotCopy(slot, b); g->gc->GCWrite(array, b); size = slotRawInt(&dict->slots[ivxIdentDict_size]) + 1; SetRaw(&dict->slots[ivxIdentDict_size], size); if (array->size < size * 3) { PyrObject* newarray; newarray = newPyrArray(g->gc, size * 3, 0, true); newarray->size = ARRAYMAXINDEXSIZE(newarray); nilSlots(newarray->slots, newarray->size); slot = array->slots; for (i = 0; i < array->size; i += 2, slot += 2) { if (NotNil(slot)) { index = arrayAtIdentityHashInPairs(newarray, slot); newslot = newarray->slots + index; slotCopy(&newslot[0], &slot[0]); slotCopy(&newslot[1], &slot[1]); } } SetRaw(&dict->slots[ivxIdentDict_array], newarray); g->gc->GCWriteNew(dict, newarray); // we know newarray is white so we can use GCWriteNew } } --g->sp; return errNone; } int prArray_AtIdentityHashInPairs(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; unsigned int i; a = g->sp - 1; // array b = g->sp; // key if (slotRawObject(a)->size < 2) return errFailed; i = arrayAtIdentityHashInPairs(slotRawObject(a), b); SetInt(a, i); return errNone; } bool identDict_lookupNonNil(PyrObject* dict, PyrSlot* key, int hash, PyrSlot* result) { again: PyrSlot* dictslots = dict->slots; PyrSlot* arraySlot = dictslots + ivxIdentDict_array; if (isKindOfSlot(arraySlot, class_array)) { PyrObject* array = slotRawObject(arraySlot); int index = arrayAtIdentityHashInPairsWithHash(array, key, hash); if (SlotEq(key, array->slots + index)) { slotCopy(result, &array->slots[index + 1]); return true; } } PyrClass* identDictClass = s_identitydictionary->u.classobj; PyrSlot* parentSlot = dictslots + ivxIdentDict_parent; PyrSlot* protoSlot = dictslots + ivxIdentDict_proto; if (isKindOfSlot(parentSlot, identDictClass)) { if (isKindOfSlot(protoSlot, identDictClass)) { // recursive call. if (identDict_lookupNonNil(slotRawObject(protoSlot), key, hash, result)) return true; } dict = slotRawObject(parentSlot); goto again; // tail call } else { if (isKindOfSlot(protoSlot, identDictClass)) { dict = slotRawObject(protoSlot); goto again; // tail call } } return false; } bool identDict_lookup(PyrObject* dict, PyrSlot* key, int hash, PyrSlot* result) { again: PyrSlot* dictslots = dict->slots; PyrSlot* arraySlot = dictslots + ivxIdentDict_array; if (isKindOfSlot(arraySlot, class_array)) { PyrObject* array = slotRawObject(arraySlot); int index = arrayAtIdentityHashInPairsWithHash(array, key, hash); if (SlotEq(key, array->slots + index)) { slotCopy(result, &array->slots[index + 1]); return true; } } PyrClass* identDictClass = s_identitydictionary->u.classobj; PyrSlot* parentSlot = dictslots + ivxIdentDict_parent; PyrSlot* protoSlot = dictslots + ivxIdentDict_proto; if (isKindOfSlot(parentSlot, identDictClass)) { if (isKindOfSlot(protoSlot, identDictClass)) { // recursive call. if (identDict_lookup(slotRawObject(protoSlot), key, hash, result)) return true; } dict = slotRawObject(parentSlot); goto again; // tail call } else { if (isKindOfSlot(protoSlot, identDictClass)) { dict = slotRawObject(protoSlot); goto again; // tail call } } SetNil(result); return false; } int prIdentDict_At(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; // dict PyrSlot* key = g->sp; // key PyrObject* dict = slotRawObject(a); bool knows = IsTrue(dict->slots + ivxIdentDict_know); if (knows && IsSym(key)) { if (slotRawSymbol(key) == s_parent) { slotCopy(a, &dict->slots[ivxIdentDict_parent]); return errNone; } if (slotRawSymbol(key) == s_proto) { slotCopy(a, &dict->slots[ivxIdentDict_proto]); return errNone; } } identDict_lookup(dict, key, calcHash(key), a); return errNone; } int prSymbol_envirGet(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, result; int objClassIndex; a = g->sp; // key PyrSlot* currentEnvironmentSlot = &g->classvars->slots[1]; PyrObject* dict = slotRawObject(currentEnvironmentSlot); if (!IsObj(currentEnvironmentSlot)) return errFailed; if (!ISKINDOF(dict, class_identdict_index, class_identdict_maxsubclassindex)) return errFailed; identDict_lookup(dict, a, calcHash(a), &result); slotCopy(a, &result); return errNone; } int prSymbol_envirPut(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int objClassIndex; a = g->sp - 1; // key b = g->sp; // value PyrSlot* currentEnvironmentSlot = &g->classvars->slots[1]; PyrObject* dict = slotRawObject(currentEnvironmentSlot); if (!IsObj(currentEnvironmentSlot)) return errFailed; if (!ISKINDOF(dict, class_identdict_index, class_identdict_maxsubclassindex)) return errFailed; int err = identDictPut(g, dict, a, b); if (err) return err; slotCopy(a, b); return errNone; } int prEvent_Delta(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, key, dur, stretch, delta; double fdur, fstretch; int err; PyrClass* restClass = getsym("Rest")->u.classobj; PyrSlot* slot; a = g->sp; // dict SetSymbol(&key, s_delta); identDict_lookup(slotRawObject(a), &key, calcHash(&key), &delta); if (NotNil(&delta)) { if (isKindOfSlot(&delta, restClass)) { slot = slotRawObject(&delta)->slots; err = slotDoubleVal(slot, &fdur); } else { err = slotDoubleVal(&delta, &fdur); } if (err) { return err; } else { SetFloat(a, fdur); return errNone; } } else { SetSymbol(&key, s_dur); identDict_lookup(slotRawObject(a), &key, calcHash(&key), &dur); err = slotDoubleVal(&dur, &fdur); if (err) { if (IsNil(&dur)) { SetNil(g->sp); return errNone; } else if (isKindOfSlot(&dur, restClass)) { slot = slotRawObject(&dur)->slots; err = slotDoubleVal(slot, &fdur); if (err) return err; } else { return errWrongType; } } SetSymbol(&key, s_stretch); identDict_lookup(slotRawObject(a), &key, calcHash(&key), &stretch); err = slotDoubleVal(&stretch, &fstretch); if (err) { if (NotNil(&stretch)) { if (isKindOfSlot(&stretch, restClass)) { slot = slotRawObject(&stretch)->slots; err = slotDoubleVal(slot, &fstretch); if (err) return err; } else { return errWrongType; } } else { SetFloat(a, fdur); return errNone; } } SetFloat(a, fdur * fstretch); } return errNone; } /// Returns whether the slot is considered a rest for \c Event.isRest. static bool slotIsRestlike(PyrSlot* slot) { PyrSymbol* slotSym; if (isKindOfSlot(slot, class_rest) || isKindOfSlot(slot, class_metarest)) { return true; } else if (!slotSymbolVal(slot, &slotSym)) { return slotSym == s_empty || slotSym == s_r || slotSym == s_rest; } // why no 'else'? // slotSymbolVal nonzero return = not a symbol; // non-symbols don't indicate rests, so, ignore them. return false; } /// Returns whether the dictionary has an entry with a 'restlike' value (see \c slotIsRestlike). static bool dictHasRestlikeValue(PyrObject* array) { auto finalSlot = array->slots + array->size; // odd-numered slots are values for (auto slot = array->slots + 1; slot < finalSlot; slot += 2) if (slotIsRestlike(slot)) return true; return false; } int prEvent_IsRest(struct VMGlobals* g, int numArgsPushed) { PyrSlot* dictslots = slotRawObject(g->sp)->slots; PyrSlot* arraySlot = dictslots + ivxIdentDict_array; static int isRestCount = 0; if (!isKindOfSlot(arraySlot, class_array)) { return errWrongType; } PyrSlot key, typeSlot; PyrSymbol* typeSym; // easy tests first: 'this[\type] == \rest' SetSymbol(&key, s_type); identDict_lookup(slotRawObject(g->sp), &key, calcHash(&key), &typeSlot); if (!slotSymbolVal(&typeSlot, &typeSym) && typeSym == s_rest) { SetBool(g->sp, 1); return errNone; } // and, 'this[\isRest] == true' SetSymbol(&key, s_isRest); identDict_lookup(slotRawObject(g->sp), &key, calcHash(&key), &typeSlot); if (IsTrue(&typeSlot)) { if (isRestCount == 0) post("\nWARNING: Setting isRest to true in an event is deprecated. See the Rest helpfile for supported " "ways to specify rests.\n\n"); isRestCount = (isRestCount + 1) % 100; SetBool(g->sp, 1); return errNone; } // failing those, scan slot values for something rest-like PyrObject* array = slotRawObject(arraySlot); SetBool(g->sp, dictHasRestlikeValue(array) ? 1 : 0); return errNone; } void PriorityQueueAdd(struct VMGlobals* g, PyrObject* queueobj, PyrSlot* item, double time) { PyrObject *schedq, *newschedq; int size, maxsize; PyrSlot* schedqSlot = queueobj->slots; if (!IsObj(schedqSlot)) { size = 32; schedq = newPyrArray(g->gc, size, 0, true); schedq->size = 1; SetInt(schedq->slots + 0, 0); // stability count SetObject(schedqSlot, schedq); g->gc->GCWriteNew(queueobj, schedq); // we know schedq is white so we can use GCWriteNew } else { schedq = slotRawObject(schedqSlot); maxsize = ARRAYMAXINDEXSIZE(schedq); size = schedq->size; if (size + 3 > maxsize) { newschedq = newPyrArray(g->gc, maxsize * 2, 0, true); newschedq->size = size; slotCopy(newschedq->slots, schedq->slots, size); assert(IsInt(newschedq->slots)); SetObject(schedqSlot, newschedq); g->gc->GCWriteNew(queueobj, newschedq); // we know newschedq is white so we can use GCWriteNew schedq = newschedq; } } addheap(g, schedq, time, item); } int prPriorityQueueAdd(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 2; // priority queue PyrSlot* b = g->sp - 1; // time PyrSlot* c = g->sp; // item double time; int err = slotDoubleVal(b, &time); if (err) return errNone; // nil is OK, nothing gets added PriorityQueueAdd(g, slotRawObject(a), c, time); return errNone; } void PriorityQueuePop(VMGlobals* g, PyrObject* queueobj, PyrSlot* result) { PyrSlot* schedqSlot = queueobj->slots; if (IsObj(schedqSlot)) { PyrObject* schedq = slotRawObject(schedqSlot); double time; if (!getheap(g, schedq, &time, result)) { SetNil(result); } } else { SetNil(result); } } void PriorityQueueTop(PyrObject* queueobj, PyrSlot* result) { PyrSlot* schedqSlot = queueobj->slots; if (IsObj(schedqSlot)) { PyrObject* schedq = slotRawObject(schedqSlot); if (schedq->size > 1) { slotCopy(result, &schedq->slots[1]); } else { SetNil(result); } } else { SetNil(result); } } void PriorityQueueClear(PyrObject* queueobj) { PyrSlot* schedqSlot = queueobj->slots; if (IsObj(schedqSlot)) { PyrObject* schedq = slotRawObject(schedqSlot); SetInt(schedq->slots, 0); // stability count schedq->size = 1; } } bool PriorityQueueEmpty(PyrObject* queueobj) { PyrSlot* schedqSlot = queueobj->slots; if (IsObj(schedqSlot)) { PyrObject* schedq = slotRawObject(schedqSlot); if (schedq->size > 1) { return false; } } return true; } int prPriorityQueuePop(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; // priority queue PriorityQueuePop(g, slotRawObject(a), a); return errNone; } int prPriorityQueueTop(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; // priority queue PriorityQueueTop(slotRawObject(a), a); return errNone; } int prPriorityQueueClear(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; // priority queue PriorityQueueClear(slotRawObject(a)); return errNone; } int prPriorityQueueEmpty(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; // priority queue if (PriorityQueueEmpty(slotRawObject(a))) { SetTrue(a); } else { SetFalse(a); } return errNone; } void PriorityQueuePostpone(PyrObject* queueobj, double time) { PyrSlot* schedqSlot = queueobj->slots; if (IsObj(schedqSlot)) { PyrObject* schedq = slotRawObject(schedqSlot); PyrSlot* slots = schedq->slots; for (int i = 1; i < schedq->size; i += 3) { SetRaw(&slots[i], slotRawFloat(&slots[i]) + time); } } } int prPriorityQueuePostpone(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; // priority queue PyrSlot* b = g->sp; // time double time; int err = slotDoubleVal(b, &time); if (err) return err; PyrObject* queueobj = slotRawObject(a); PriorityQueuePostpone(queueobj, time); return errNone; } void initListPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_Array_AtIdentityHash", prArray_AtIdentityHash, 2, 0); definePrimitive(base, index++, "_Array_AtIdentityHashInPairs", prArray_AtIdentityHashInPairs, 2, 0); definePrimitive(base, index++, "_IdentDict_Put", prIdentDict_Put, 3, 0); definePrimitive(base, index++, "_IdentDict_PutGet", prIdentDict_PutGet, 3, 0); definePrimitive(base, index++, "_IdentDict_At", prIdentDict_At, 2, 0); definePrimitive(base, index++, "_Symbol_envirGet", prSymbol_envirGet, 1, 0); definePrimitive(base, index++, "_Symbol_envirPut", prSymbol_envirPut, 2, 0); definePrimitive(base, index++, "_ArrayMultiChannelExpand", prArrayMultiChanExpand, 1, 0); definePrimitive(base, index++, "_PriorityQueueAdd", prPriorityQueueAdd, 3, 0); definePrimitive(base, index++, "_PriorityQueuePop", prPriorityQueuePop, 1, 0); definePrimitive(base, index++, "_PriorityQueueTop", prPriorityQueueTop, 1, 0); definePrimitive(base, index++, "_PriorityQueueClear", prPriorityQueueClear, 1, 0); definePrimitive(base, index++, "_PriorityQueueEmpty", prPriorityQueueEmpty, 1, 0); definePrimitive(base, index++, "_PriorityQueuePostpone", prPriorityQueuePostpone, 2, 0); definePrimitive(base, index++, "_Event_Delta", prEvent_Delta, 1, 0); definePrimitive(base, index++, "_Event_IsRest", prEvent_IsRest, 1, 0); } void initPatterns() { PyrSymbol* sym; ivxIdentDict_array = instVarOffset("IdentityDictionary", "array"); ivxIdentDict_size = instVarOffset("IdentityDictionary", "size"); ivxIdentDict_parent = instVarOffset("IdentityDictionary", "parent"); ivxIdentDict_proto = instVarOffset("IdentityDictionary", "proto"); ivxIdentDict_know = instVarOffset("IdentityDictionary", "know"); sym = getsym("IdentityDictionary"); class_identdict = sym ? sym->u.classobj : nullptr; class_identdict_index = slotRawInt(&class_identdict->classIndex); class_identdict_maxsubclassindex = slotRawInt(&class_identdict->maxSubclassIndex); class_array_index = slotRawInt(&class_array->classIndex); class_array_maxsubclassindex = slotRawInt(&class_array->maxSubclassIndex); s_parent = getsym("parent"); s_proto = getsym("proto"); s_delta = getsym("delta"); s_dur = getsym("dur"); s_stretch = getsym("stretch"); // used in prEvent_IsRest s_type = getsym("type"); s_rest = getsym("rest"); s_empty = getsym(""); s_r = getsym("r"); s_isRest = getsym("isRest"); class_rest = getsym("Rest")->u.classobj; class_metarest = getsym("Meta_Rest")->u.classobj; }
26,305
C++
.cpp
699
30.306152
120
0.610828
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
29,881
PyrSignalPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrSignalPrim.cpp
/* 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 "PyrSymbol.h" #include "PyrKernel.h" #include "PyrObject.h" #include "PyrPrimitive.h" #include "PyrSignal.h" #include "PyrSignalPrim.h" #include "PyrMessage.h" #include "SC_Constants.h" #include "SCBase.h" #include "clz.h" extern "C" { #include "fftlib.h" } #include <stdlib.h> #include <string.h> #include <math.h> int prSignalFill(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int err; float value; a = g->sp - 1; b = g->sp; err = slotFloatVal(b, &value); if (err != errNone) return err; signal_fill(slotRawObject(a), value); return errNone; } int prSignalScale(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int err; float value; a = g->sp - 1; b = g->sp; err = slotFloatVal(b, &value); if (err != errNone) return err; signal_scale(slotRawObject(a), value); return errNone; } int prSignalOffset(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int err; float value; a = g->sp - 1; b = g->sp; err = slotFloatVal(b, &value); if (err != errNone) return err; signal_offset(slotRawObject(a), value); return errNone; } int prSignalString(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrString* string; PyrObject* signal; float* x; char str[128]; a = g->sp; slotString(a, str); signal = slotRawObject(a); if (signal->size) { x = (float*)(signal->slots); sprintf(str, "%s[%g .. %g]", slotRawSymbol(&signal->classptr->name)->name, x[0], x[signal->size - 1]); } else { sprintf(str, "%s[none]", slotRawSymbol(&signal->classptr->name)->name); } string = newPyrString(g->gc, str, 0, true); SetObject(a, string); return errNone; } int prSignalPeak(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetFloat(a, signal_findpeak(slotRawObject(a))); return errNone; } int prSignalNormalize(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err, start, end; a = g->sp - 2; b = g->sp - 1; c = g->sp; err = slotIntVal(b, &start); if (err) { if (IsNil(c)) start = 0; else return err; } err = slotIntVal(c, &end); if (err) { if (IsNil(c)) end = slotRawObject(a)->size; else return err; } signal_normalize_range(slotRawObject(a), start, end); return errNone; } int prSignalNormalizeTransferFn(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; signal_normalize_transfer_fn(slotRawObject(a)); return errNone; } int prSignalIntegral(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; a = g->sp; SetFloat(a, signal_integral(slotRawObject(a))); return errNone; } int prSignalInvert(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err, start, end; a = g->sp - 2; b = g->sp - 1; c = g->sp; err = slotIntVal(b, &start); if (err) { if (IsNil(c)) start = 0; else return err; } err = slotIntVal(c, &end); if (err) { if (IsNil(c)) end = slotRawObject(a)->size; else return err; } signal_invert_range(slotRawObject(a), start, end); return errNone; } int prSignalReverse(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err, start, end; a = g->sp - 2; b = g->sp - 1; c = g->sp; err = slotIntVal(b, &start); if (err) { if (IsNil(b)) start = 0; else return err; } err = slotIntVal(c, &end); if (err) { if (IsNil(c)) end = slotRawObject(a)->size; else return err; } signal_reverse_range(slotRawObject(a), start, end); return errNone; } int prSignalRotate(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b; int err, rot; a = g->sp - 1; b = g->sp; err = slotIntVal(b, &rot); if (err) return err; SetRaw(a, signal_rotate(g, slotRawObject(a), rot)); return errNone; } int prSignalOverDub(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err; int index; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotObj(b) || !isKindOf(slotRawObject(b), class_signal)) return errWrongType; err = slotIntVal(c, &index); if (err) return errWrongType; signal_overdub(g, slotRawObject(a), slotRawObject(b), index); return errNone; } int prSignalOverWrite(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err; int index; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotObj(b) || !isKindOf(slotRawObject(b), class_signal)) return errWrongType; err = slotIntVal(c, &index); if (err) return errWrongType; signal_overwrite(g, slotRawObject(a), slotRawObject(b), index); return errNone; } int prSignalFade(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *d, *e; int err; int start, end; float lvl0, lvl1; a = g->sp - 4; b = g->sp - 3; c = g->sp - 2; d = g->sp - 1; e = g->sp; err = slotIntVal(b, &start); if (err) { if (IsNil(b)) start = 0; else return err; } err = slotIntVal(c, &end); if (err) { if (IsNil(c)) end = slotRawObject(a)->size; else return err; } err = slotFloatVal(d, &lvl0); if (err) return err; err = slotFloatVal(e, &lvl1); if (err) return err; signal_fade_range(slotRawObject(a), start, end, lvl0, lvl1); return errNone; } int prSignalAddHarmonic(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c, *d; int err; float harmonic, amp; double phase, step; PyrObject* signal; float* out; a = g->sp - 3; b = g->sp - 2; c = g->sp - 1; d = g->sp; err = slotFloatVal(b, &harmonic); if (err) return errWrongType; err = slotFloatVal(c, &amp); if (err) return errWrongType; err = slotDoubleVal(d, &phase); if (err) return errWrongType; signal = slotRawObject(a); out = (float*)(signal->slots) - 1; step = twopi * harmonic / signal->size; UNROLL_CODE(signal->size, out, *++out += sin(phase) * amp; phase += step;); return errNone; } int prSignalAddChebyshev(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int err; float harmonic, amp; double x, step; PyrObject* signal; float* out; a = g->sp - 2; b = g->sp - 1; c = g->sp; err = slotFloatVal(b, &harmonic); if (err) return errWrongType; err = slotFloatVal(c, &amp); if (err) return errWrongType; signal = slotRawObject(a); out = (float*)(signal->slots) - 1; x = -1.0; step = 2.0 / (signal->size - 1); UNROLL_CODE(signal->size, out, *++out += cos(harmonic * acos(sc_min(x, 1.0))) * amp; x += step;); return errNone; } ////////////////////////////////////////////////////////////////////////////// void signalAsWavetable(float* signal, float* wavetable, int size) { int i, imax; float *in, *out; float val1, val2; in = signal; out = wavetable - 1; imax = size - 1; for (i = 0; i < imax; ++i) { val1 = in[i]; val2 = in[i + 1]; *++out = 2.f * val1 - val2; *++out = val2 - val1; } val1 = in[imax]; val2 = in[0]; *++out = 2.f * val1 - val2; *++out = val2 - val1; } void wavetableAsSignal(float* wavetable, float* signal, int size) { float *in, *out; in = wavetable; out = signal - 1; for (int i = 0; i < size; ++i) { *++out = in[0] + in[1]; in += 2; } } ////////////////////////////////////////////////////////////////////////////// int prSignalAsWavetable(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; int size; PyrObject *signal, *wavetable; a = g->sp; signal = slotRawObject(a); size = signal->size; if ((size & (size - 1)) != 0) { error("Signal size not a power of two.\n"); return errFailed; } wavetable = newPyrSignal(g, signal->size * 2); wavetable->classptr = class_wavetable; signalAsWavetable((float*)signal->slots, (float*)wavetable->slots, signal->size); SetObject(a, wavetable); return errNone; } int prWavetableAsSignal(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; PyrObject *signal, *wavetable; a = g->sp; wavetable = slotRawObject(a); signal = newPyrSignal(g, wavetable->size / 2); wavetableAsSignal((float*)wavetable->slots, (float*)signal->slots, signal->size); SetObject(a, signal); return errNone; } // class_signal #if 1 int prSignal_FFT(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int i, M, fftsize, fftbufsize, asize; float *inreal, *inimag, *fftbuf, *costable, *outreal, *outimag; PyrObject *fftoutobj, *complexobj, *realobj, *imagobj; a = g->sp - 2; b = g->sp - 1; c = g->sp; asize = slotRawObject(a)->size; if (NotNil(b) && !(isKindOfSlot(b, class_signal) && slotRawObject(b)->size == asize)) { error("Signal::fft imaginary part wrong type or length.\n"); return errFailed; } M = LOG2CEIL(asize); fftsize = 1L << M; if (!(isKindOfSlot(c, class_floatarray))) { error("Signal::fft must be provided a table containing 1/4 cycle of a cosine.\n"); return errFailed; } if (slotRawObject(c)->size != fftsize / 4 + 1) { error("Signal::fft cosine table wrong size (%d), expected %d.\n", slotRawObject(c)->size, fftsize / 4 + 1); return errFailed; } costable = (float*)slotRawObject(c)->slots; fftbufsize = fftsize * 2; fftoutobj = newPyrSignal(g, fftbufsize); fftoutobj->size = fftbufsize; ++g->sp; SetObject(g->sp, fftoutobj); complexobj = instantiateObject(g->gc, s_complex->u.classobj, 0, false, true); ++g->sp; SetObject(g->sp, complexobj); realobj = newPyrSignal(g, fftbufsize); SetObject(complexobj->slots + 0, realobj); g->gc->GCWriteNew(complexobj, realobj); imagobj = newPyrSignal(g, fftbufsize); SetObject(complexobj->slots + 1, imagobj); g->gc->GCWriteNew(complexobj, imagobj); inreal = (float*)slotRawObject(a)->slots - 1; if (IsNil(b)) { fftbuf = (float*)fftoutobj->slots - 1; for (i = 0; i < asize; ++i) { *++fftbuf = *++inreal; } for (i = asize; i < fftsize; ++i) { *++fftbuf = 0.f; } fftbuf = (float*)fftoutobj->slots; rffts(fftbuf, M, 1, costable); } else { inimag = (float*)slotRawObject(b)->slots - 1; fftbuf = (float*)fftoutobj->slots - 1; for (i = 0; i < asize; ++i) { *++fftbuf = *++inreal; *++fftbuf = *++inimag; } for (i = asize; i < fftsize; ++i) { *++fftbuf = 0.f; *++fftbuf = 0.f; } fftbuf = (float*)fftoutobj->slots; ffts(fftbuf, M, 1, costable); } outreal = (float*)realobj->slots - 1; outimag = (float*)imagobj->slots - 1; fftbuf = (float*)fftoutobj->slots - 1; for (i = 0; i < fftsize; ++i) { *++outreal = *++fftbuf; *++outimag = *++fftbuf; } realobj->size = fftsize; imagobj->size = fftsize; g->sp -= 2; SetRaw(a, complexobj); return errNone; } int prSignal_IFFT(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int i, M, fftsize, fftbufsize, asize; float *inreal, *inimag, *fftbuf, *costable, *outreal, *outimag; PyrObject *fftoutobj, *complexobj, *realobj, *imagobj; a = g->sp - 2; b = g->sp - 1; c = g->sp; asize = slotRawObject(a)->size; if (!(isKindOfSlot(b, class_signal) && slotRawObject(b)->size == asize)) { error("Signal::ifft imaginary part wrong type or length.\n"); return errFailed; } M = LOG2CEIL(asize); fftsize = 1L << M; if (!(isKindOfSlot(c, class_floatarray))) { error("Signal::ifft must be provided a table containing 1/4 cycle of a cosine.\n"); return errFailed; } if (slotRawObject(c)->size != fftsize / 4 + 1) { error("Signal::ifft cosine table wrong size (%d), expected %d.\n", slotRawObject(c)->size, fftsize / 4 + 1); return errFailed; } costable = (float*)slotRawObject(c)->slots; fftbufsize = fftsize * 2; fftoutobj = newPyrSignal(g, fftbufsize); fftoutobj->size = fftbufsize; ++g->sp; SetObject(g->sp, fftoutobj); complexobj = instantiateObject(g->gc, s_complex->u.classobj, 0, false, true); ++g->sp; SetObject(g->sp, complexobj); realobj = newPyrSignal(g, fftbufsize); SetObject(complexobj->slots + 0, realobj); g->gc->GCWriteNew(complexobj, realobj); imagobj = newPyrSignal(g, fftbufsize); SetObject(complexobj->slots + 1, imagobj); g->gc->GCWriteNew(complexobj, imagobj); inreal = (float*)slotRawObject(a)->slots - 1; inimag = (float*)slotRawObject(b)->slots - 1; fftbuf = (float*)fftoutobj->slots - 1; for (i = 0; i < asize; ++i) { *++fftbuf = *++inreal; *++fftbuf = *++inimag; } for (i = asize; i < fftsize; ++i) { *++fftbuf = 0.f; *++fftbuf = 0.f; } fftbuf = (float*)fftoutobj->slots; iffts(fftbuf, M, 1, costable); outreal = (float*)realobj->slots - 1; outimag = (float*)imagobj->slots - 1; fftbuf = (float*)fftoutobj->slots - 1; for (i = 0; i < fftsize; ++i) { *++outreal = *++fftbuf; *++outimag = *++fftbuf; } realobj->size = fftsize; imagobj->size = fftsize; g->sp -= 2; SetRaw(a, complexobj); return errNone; } #endif void initSignalPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_SignalPeak", prSignalPeak, 1, 0); definePrimitive(base, index++, "_SignalNormalize", prSignalNormalize, 3, 0); definePrimitive(base, index++, "_SignalNormalizeTransferFn", prSignalNormalizeTransferFn, 1, 0); definePrimitive(base, index++, "_SignalIntegral", prSignalIntegral, 1, 0); definePrimitive(base, index++, "_SignalReverse", prSignalReverse, 3, 0); definePrimitive(base, index++, "_SignalInvert", prSignalInvert, 3, 0); definePrimitive(base, index++, "_SignalRotate", prSignalRotate, 2, 0); definePrimitive(base, index++, "_SignalFill", prSignalFill, 2, 0); definePrimitive(base, index++, "_SignalScale", prSignalScale, 2, 0); definePrimitive(base, index++, "_SignalOffset", prSignalOffset, 2, 0); definePrimitive(base, index++, "_SignalOverDub", prSignalOverDub, 3, 0); definePrimitive(base, index++, "_SignalOverWrite", prSignalOverWrite, 3, 0); definePrimitive(base, index++, "_SignalFade", prSignalFade, 5, 0); definePrimitive(base, index++, "_SignalAddHarmonic", prSignalAddHarmonic, 4, 0); definePrimitive(base, index++, "_SignalAddChebyshev", prSignalAddChebyshev, 3, 0); definePrimitive(base, index++, "_SignalString", prSignalString, 1, 0); definePrimitive(base, index++, "_SignalAsWavetable", prSignalAsWavetable, 1, 0); definePrimitive(base, index++, "_WavetableAsSignal", prWavetableAsSignal, 1, 0); definePrimitive(base, index++, "_Signal_FFT", prSignal_FFT, 3, 0); definePrimitive(base, index++, "_Signal_IFFT", prSignal_IFFT, 3, 0); }
16,558
C++
.cpp
521
26.149712
116
0.599397
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
29,882
PyrArchiver.cpp
supercollider_supercollider/lang/LangPrimSource/PyrArchiver.cpp
/* 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. */ #include "PyrArchiverT.h" #include "PyrKernel.h" #include "PyrPrimitive.h" #include "VMGlobals.h" #include "GC.h" #include "ReadWriteMacros.h" int prAsArchive(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrArchiver<char*> arch(g); int err = arch.prepareToWriteArchive(a); if (err) return err; int32 size = arch.calcArchiveSize(); PyrInt8Array* obj = newPyrInt8Array(g->gc, size, 0, true); obj->size = size; arch.setStream((char*)obj->b); err = arch.writeArchive(); if (err == errNone) SetObject(a, obj); else SetNil(a); return err; } int prUnarchive(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; if (!isKindOfSlot(a, class_int8array)) return errWrongType; PyrArchiver<char*> arch(g); arch.setStream((char*)slotRawObject(a)->slots); int err = arch.readArchive(a); return err; } int prWriteArchive(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (!isKindOfSlot(b, class_string)) return errWrongType; char pathname[PATH_MAX]; memcpy(pathname, slotRawString(b)->s, slotRawObject(b)->size); pathname[slotRawString(b)->size] = 0; PyrArchiver<FILE*> arch(g); FILE* file = fopen(pathname, "wb"); int err = errNone; if (file) { err = arch.prepareToWriteArchive(a); if (!err) { arch.setStream(file); err = arch.writeArchive(); } fclose(file); } else { error("file open failed\n"); err = errFailed; } return err; } int prReadArchive(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (!isKindOfSlot(b, class_string)) return errWrongType; char pathname[PATH_MAX]; memcpy(pathname, slotRawString(b)->s, slotRawObject(b)->size); pathname[slotRawString(b)->size] = 0; PyrArchiver<FILE*> arch(g); FILE* file = fopen(pathname, "rb"); int err; if (file) { arch.setStream(file); err = arch.readArchive(a); fclose(file); } else { error("file open failed\n"); err = errFailed; } return err; } void initArchiverPrimitives() { int base, index; base = nextPrimitiveIndex(); index = 0; definePrimitive(base, index++, "_AsArchive", prAsArchive, 1, 0); definePrimitive(base, index++, "_Unarchive", prUnarchive, 1, 0); definePrimitive(base, index++, "_WriteArchive", prWriteArchive, 2, 0); definePrimitive(base, index++, "_ReadArchive", prReadArchive, 2, 0); }
3,562
C++
.cpp
105
28.638095
81
0.666764
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
29,883
PyrStringPrim.cpp
supercollider_supercollider/lang/LangPrimSource/PyrStringPrim.cpp
/* 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 */ /* Primitives for String. */ #include "PyrPrimitive.h" #include "PyrKernel.h" #include "GC.h" #include "Hash.h" #include <string.h> #include <stdlib.h> #include <ctype.h> #include <vector> #include "PyrLexer.h" #include "SC_Filesystem.hpp" #include "SC_Codecvt.hpp" // path_to_utf8_str #ifdef _WIN32 # include <direct.h> # include "SC_Win32Utils.h" #else # include <sys/param.h> #endif #include <boost/regex.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive/unordered_set.hpp> #include <fstream> #include <filesystem> #include <yaml-cpp/yaml.h> using namespace std; namespace fs = std::filesystem; int prStringAsSymbol(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a; char str[1024], *strp = nullptr; int len; a = g->sp; len = slotRawObject(a)->size; strp = len > 1023 ? (char*)malloc(len + 1) : str; memcpy(strp, slotRawString(a)->s, len); strp[len] = 0; SetSymbol(a, getsym(strp)); if (len > 1023) free(strp); return errNone; } int prString_AsInteger(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char str[256]; int err = slotStrVal(a, str, 255); if (err) return err; SetInt(a, atoi(str)); return errNone; } int prString_AsFloat(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char str[256]; int err = slotStrVal(a, str, 255); if (err) return err; SetFloat(a, atof(str)); return errNone; } int prString_AsCompileString(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; PyrString* scstr = slotRawString(a); char* chars1 = scstr->s; int newSize = scstr->size + 2; for (int i = 0; i < scstr->size; ++i) { if (chars1[i] == '"' || chars1[i] == '\\') newSize++; } PyrString* newString = newPyrStringN(g->gc, newSize, 0, true); char* chars2 = newString->s; chars2[0] = '"'; chars2[newSize - 1] = '"'; int k = 1; for (int i = 0; i < scstr->size; ++i) { int c = chars1[i]; if (c == '"' || c == '\\') chars2[k++] = '\\'; chars2[k++] = c; } SetObject(a, newString); return errNone; } int prString_Format(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 1; PyrSlot* b = g->sp; if (!isKindOfSlot(b, class_array)) return errWrongType; char* fmt = slotRawString(a)->s; int asize = slotRawObject(a)->size; int bsize = slotRawObject(b)->size; int csize = asize; PyrSlot* slots = slotRawObject(b)->slots; for (int i = 0; i < bsize; ++i) { PyrSlot* slot = slots + i; if (!isKindOfSlot(slot, class_string)) return errWrongType; csize += slotRawString(slot)->size; } PyrString* newString = newPyrStringN(g->gc, csize, 0, true); char* buf = newString->s; int k = 0; int index = 0; for (int i = 0; i < asize;) { char ch = fmt[i++]; if (ch == '%') { if (index < bsize) { PyrString* bstring = slotRawString(&slots[index]); memcpy(buf + k, bstring->s, bstring->size); k += bstring->size; index++; } } else if (ch == '\\') { if (i >= asize) break; ch = fmt[i++]; if (ch == '%') { buf[k++] = '%'; } else { i--; buf[k++] = '\\'; } } else { buf[k++] = ch; } } newString->size = k; SetObject(a, newString); return errNone; }; namespace detail { namespace bin = boost::intrusive; class regex_lru_cache { int regex_flags; struct regex_node : bin::list_base_hook<>, bin::unordered_set_base_hook<> { public: regex_node(const char* str, size_t size, int regex_flags): pattern(str, size, regex_flags) {} boost::regex const& get(void) const { return pattern; } private: boost::regex pattern; }; struct regex_equal { bool operator()(regex_node const& lhs, regex_node const& rhs) const { return lhs.get() == rhs.get(); } bool operator()(const char* lhs, regex_node const& rhs) const { return strcmp(lhs, rhs.get().str().c_str()) == 0; } }; static inline std::size_t string_hash(const char* str) { std::size_t ret = 0; // sdbm hash int c; while ((c = *str++)) ret = c + (ret << 6) + (ret << 16) - ret; return ret; } struct regex_hash { size_t operator()(regex_node const& arg) const { return string_hash(arg.get().str().c_str()); } size_t operator()(const char* arg) const { return string_hash(arg); } }; typedef bin::unordered_set<regex_node, bin::equal<regex_equal>, bin::hash<regex_hash>, bin::power_2_buckets<true>, bin::constant_time_size<false>> re_set_t; typedef re_set_t::bucket_type bucket_type; typedef re_set_t::bucket_traits bucket_traits; bucket_type buckets[128]; re_set_t re_set; bin::list<regex_node> re_list; void pop_lru() { regex_node& rlu = re_list.back(); re_list.pop_back(); re_set.erase(rlu); delete &rlu; } public: regex_lru_cache(int regex_flags = boost::regex_constants::ECMAScript): re_set(bucket_traits(buckets, 128)), re_list() {} ~regex_lru_cache() { while (!re_list.empty()) { pop_lru(); } } boost::regex const& get_regex(const char* str, size_t size) { re_set_t::iterator re_in_cache = re_set.find(str, regex_hash(), regex_equal()); if (re_in_cache != re_set.end()) { regex_node& node = *re_in_cache; bin::list<regex_node>::iterator re_in_list = bin::list<regex_node>::s_iterator_to(node); re_list.splice(re_list.begin(), re_list, re_in_list); // move to the begin of the list assert(&re_list.front() == &node); return node.get(); } if (re_list.size() >= 64) pop_lru(); regex_node* new_node = new regex_node(str, size, regex_flags); re_set.insert(*new_node); re_list.push_front(*new_node); return new_node->get(); } }; } int prString_ReplaceRegex(struct VMGlobals* g, int numArgsPushed) { // caches the last 64 boost:regex instances. static detail::regex_lru_cache regex_lru_cache(boost::regex_constants::ECMAScript | boost::regex_constants::nosubs); PyrSlot* slot_this = g->sp - 2; // source string PyrSlot* slot_regex = g->sp - 1; // find PyrSlot* slot_replace = g->sp; // replace with // slot one does not need to be checked as this method should only be called from methods in String, // or children thereof. if (!isKindOfSlot(slot_regex, class_string)) { SetNil(slot_this); return errWrongType; } if (!isKindOfSlot(slot_replace, class_string)) { SetNil(slot_this); return errWrongType; } try { const auto& pattern = regex_lru_cache.get_regex(slotRawString(slot_regex)->s, slotRawString(slot_regex)->size); const char* source_start = slotRawString(slot_this)->s; const int source_size = slotRawString(slot_this)->size; if (source_size < 0) { // size is signed SetNil(slot_this); error("String has negative size\n"); return errFailed; } std::string out {}; // PyrStrings are not null terminated so a copy is needed. const auto [replaceError, replace] = slotStrStdStrVal(slot_replace); if (replaceError != errNone) { SetNil(slot_this); return replaceError; } boost::regex_replace(std::back_inserter(out), source_start, source_start + source_size, pattern, replace); if (out.size() > std::numeric_limits<decltype(PyrObjectHdr {}.size)>::max()) { SetNil(slot_this); error("String too big\n"); return errNone; } SetObject(slot_this, newPyrStringN(g->gc, static_cast<int>(out.size()), 0, true)); std::copy(out.begin(), out.end(), slotRawString(slot_this)->s); return errNone; } catch (const std::exception& e) { postfl("Warning: Exception in _String_ReplaceRegex -%s\n", e.what()); SetNil(slot_this); return errFailed; }; } int prString_Regexp(struct VMGlobals* g, int numArgsPushed) { /* not reentrant */ static detail::regex_lru_cache regex_lru_cache(boost::regex_constants::ECMAScript | boost::regex_constants::nosubs); using namespace boost; int start, end, len; PyrSlot* a = g->sp - 3; PyrSlot* b = g->sp - 2; PyrSlot* c = g->sp - 1; PyrSlot* d = g->sp; if (!isKindOfSlot(b, class_string)) return errWrongType; if (NotInt(c) || (NotInt(d) && NotNil(d))) return errWrongType; start = slotRawInt(c); len = slotRawObject(b)->size; // last char index instead of size if (IsNil(d)) { end = len; } else { end = slotRawInt(d); } if (end > len) end = len; if (end - start <= 0) { SetFalse(a); return errNone; } int stringlen = end - start; try { regex const& pattern = regex_lru_cache.get_regex(slotRawString(a)->s, slotRawObject(a)->size); match_flag_type flags = match_nosubs | match_any; const char* stringStart = slotRawString(b)->s + start; const char* stringEnd = stringStart + stringlen; bool res = regex_search(stringStart, stringEnd, pattern, flags); if (res) SetTrue(a); else SetFalse(a); return errNone; } catch (std::exception const& e) { postfl("Warning: Exception in _String_Regexp - %s\n", e.what()); return errFailed; } } struct sc_regexp_match { int pos; int len; }; static int prString_FindRegexp(struct VMGlobals* g, int numArgsPushed) { /* not reentrant */ static detail::regex_lru_cache regex_lru_cache(boost::regex_constants::ECMAScript); using namespace boost; PyrSlot* a = g->sp - 2; // source string PyrSlot* b = g->sp - 1; // pattern PyrSlot* c = g->sp; // offset if (!isKindOfSlot(b, class_string) || (NotInt(c))) { SetNil(a); return errWrongType; } int offset = slotRawInt(c); int stringlen = std::max(slotRawObject(a)->size - offset, 0); std::vector<sc_regexp_match> matches; const char* const stringBegin = slotRawString(a)->s + offset; try { regex const& pattern = regex_lru_cache.get_regex(slotRawString(b)->s, slotRawObject(b)->size); match_flag_type flags = match_default; match_results<const char*> what; const char* start = stringBegin; const char* end = start + stringlen; while (start <= end && regex_search(start, end, what, pattern, flags)) { for (int i = 0; i < what.size(); ++i) { sc_regexp_match match; if (what[i].matched) { match.pos = what[i].first - stringBegin; match.len = what[i].second - what[i].first; } else { match.pos = 0; match.len = 0; } matches.push_back(match); } start = what[0].second; if (what[0].first == what[0].second) ++start; } } catch (std::exception const& e) { postfl("Warning: Exception in _String_FindRegexp - %s\n", e.what()); SetNil(a); return errFailed; } int match_count = matches.size(); PyrObject* result_array = newPyrArray(g->gc, match_count, 0, true); ++g->sp; // advance the stack to avoid overwriting receiver SetObject(g->sp, result_array); // push result to make reachable for (int i = 0; i < match_count; ++i) { int pos = matches[i].pos; int len = matches[i].len; PyrObject* array = newPyrArray(g->gc, 2, 0, true); SetObject(result_array->slots + i, array); result_array->size++; g->gc->GCWriteNew(result_array, array); // we know array is white so we can use GCWriteNew PyrString* matched_string = newPyrStringN(g->gc, len, 0, true); memcpy(matched_string->s, stringBegin + pos, len); array->size = 2; SetInt(array->slots, pos + offset); SetObject(array->slots + 1, matched_string); g->gc->GCWriteNew(array, matched_string); // we know matched_string is white so we can use GCWriteNew }; --g->sp; // pop the stack back to the receiver slot since we stored result_array there above SetObject(a, result_array); // now we can set the result in a return errNone; } static int prString_FindRegexpAt(struct VMGlobals* g, int numArgsPushed) { /* not reentrant */ static detail::regex_lru_cache regex_lru_cache(boost::regex_constants::ECMAScript); using namespace boost; PyrSlot* a = g->sp - 2; // source string PyrSlot* b = g->sp - 1; // pattern PyrSlot* c = g->sp; // offset if (!isKindOfSlot(b, class_string) || (NotInt(c))) { SetNil(a); return errWrongType; } int offset = slotRawInt(c); int stringlen = std::max(slotRawObject(a)->size - offset, 0); int matched_len = 0; const char* const stringBegin = slotRawString(a)->s + offset; try { regex const& pattern = regex_lru_cache.get_regex(slotRawString(b)->s, slotRawObject(b)->size); // match_continuous: the match must begin at the offset start match_flag_type flags = match_continuous; match_results<const char*> what; const char* start = stringBegin; const char* end = start + stringlen; if (regex_search(start, end, what, pattern, flags)) { assert(what[0].first == stringBegin); matched_len = what[0].second - what[0].first; } else { SetNil(a); return errNone; } } catch (std::exception const& e) { postfl("Warning: Exception in _String_FindRegexpAt - %s\n", e.what()); return errFailed; } PyrObject* array = newPyrArray(g->gc, 2, 0, true); ++g->sp; SetObject(g->sp, array); // push on stack to make reachable PyrString* matched_string = newPyrStringN(g->gc, matched_len, 0, true); memcpy(matched_string->s, stringBegin, (size_t)matched_len); array->size = 2; SetInt(array->slots + 1, matched_len); SetObject(array->slots, matched_string); g->gc->GCWriteNew(array, matched_string); // we know matched_string is white so we can use GCWriteNew --g->sp; // pop the stack back to the receiver slot since we stored array there above SetObject(a, array); // now we can set the result in a return errNone; } int memcmpi(char* a, char* b, int len) { for (int i = 0; i < len; ++i) { char aa = toupper(a[i]); char bb = toupper(b[i]); if (aa < bb) return -1; if (aa > bb) return 1; } return 0; } int prStringCompare(struct VMGlobals* g, int numArgsPushed) { PyrSlot *a, *b, *c; int cmp, length; a = g->sp - 2; b = g->sp - 1; c = g->sp; if (NotObj(b) || !isKindOf(slotRawObject(b), class_string)) return errWrongType; length = sc_min(slotRawObject(a)->size, slotRawObject(b)->size); if (IsTrue(c)) cmp = memcmpi(slotRawString(a)->s, slotRawString(b)->s, length); else cmp = memcmp(slotRawString(a)->s, slotRawString(b)->s, length); if (cmp == 0) { if (slotRawObject(a)->size < slotRawObject(b)->size) cmp = -1; else if (slotRawObject(a)->size > slotRawObject(b)->size) cmp = 1; } SetInt(a, cmp); return errNone; } int prStringHash(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; int hash = Hash(slotRawString(a)->s, slotRawString(a)->size); SetInt(a, hash); return errNone; } int prString_PathMatch(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; char pattern[PATH_MAX]; int err = slotStrVal(a, pattern, PATH_MAX - 1); if (err) return err; SC_Filesystem::Glob* glob = SC_Filesystem::makeGlob(pattern); // exit early with empty array if no matches found if (!glob) { SetObject(a, newPyrArray(g->gc, 0, 0, true)); return errNone; } // read all paths into a vector std::vector<fs::path> paths; while (true) { const fs::path& matched_path = SC_Filesystem::globNext(glob); if (matched_path.empty()) break; else paths.push_back(matched_path); }; // create array with appropriate reserved size PyrObject* array = newPyrArray(g->gc, paths.size(), 0, true); SetObject(a, array); // this is okay here as we don't use the receiver below // convert paths and copy into sclang array. for (int i = 0; i < paths.size(); ++i) { const std::string& matched_path_utf8 = SC_Codecvt::path_to_utf8_str(paths[i]); PyrObject* string = (PyrObject*)newPyrString(g->gc, matched_path_utf8.c_str(), 0, true); SetObject(array->slots + i, string); g->gc->GCWriteNew(array, string); // we know string is white so we can use GCWriteNew array->size++; } SC_Filesystem::freeGlob(glob); return errNone; } int prString_Getenv(struct VMGlobals* g, int /* numArgsPushed */) { PyrSlot* slot_this = g->sp; const auto [this_err, this_str] = slotStdStrVal(slot_this); if (this_err != errNone) return this_err; #ifdef _WIN32 const auto this_str_w = SC_Codecvt::utf8_cstr_to_utf16_wstring(this_str.c_str()); const auto count = GetEnvironmentVariableW(this_str_w.c_str(), nullptr, 0); std::string buf; if (count != 0) { std::wstring wbuf(count, 0); GetEnvironmentVariableW(this_str_w.c_str(), wbuf.data(), count); buf = SC_Codecvt::utf16_wcstr_to_utf8_string(wbuf.c_str()); } char* value = count != 0 ? buf.data() : nullptr; #else char* value = getenv(this_str.c_str()); #endif if (value == nullptr) { SetNil(slot_this); return errNone; // returns nil if not present } PyrString* pyrString = newPyrString(g->gc, value, 0, true); if (pyrString == nullptr) return errFailed; SetObject(slot_this, pyrString); return errNone; } int prString_Setenv(struct VMGlobals* g, int numArgsPushed) { assert(numArgsPushed == 2); // String::setEnv {|value| ... } PyrSlot* slot_this_name = g->sp - 1; PyrSlot* slot_value = g->sp; const auto [this_name_err, this_name_str] = slotStdStrVal(slot_this_name); if (this_name_err != errNone) return this_name_err; if (IsNil(slot_value)) { #ifdef _WIN32 SetEnvironmentVariableW(SC_Codecvt::utf8_cstr_to_utf16_wstring(this_name_str.c_str()).c_str(), nullptr); #else unsetenv(this_name_str.c_str()); #endif } else { const auto [value_err, value_str] = slotStdStrVal(slot_value); if (value_err != errNone) return value_err; #ifdef _WIN32 SetEnvironmentVariableW(SC_Codecvt::utf8_cstr_to_utf16_wstring(this_name_str.c_str()).c_str(), SC_Codecvt::utf8_cstr_to_utf16_wstring(value_str.c_str()).c_str()); #else setenv(this_name_str.c_str(), value_str.c_str(), 1); #endif } return errNone; } int prStripRtf(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; int len = slotRawObject(a)->size; char* chars = (char*)malloc(len + 1); memcpy(chars, slotRawString(a)->s, len); chars[len] = 0; rtf2txt(chars); PyrString* string = newPyrString(g->gc, chars, 0, false); SetObject(a, string); free(chars); return errNone; } int prStripHtml(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp; int len = slotRawObject(a)->size; char* chars = (char*)malloc(len + 1); memcpy(chars, slotRawString(a)->s, len); chars[len] = 0; html2txt(chars); PyrString* string = newPyrString(g->gc, chars, 0, false); SetObject(a, string); free(chars); return errNone; } int prString_Find(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; // source string PyrSlot* b = g->sp - 2; // search string PyrSlot* c = g->sp - 1; // ignoreCase PyrSlot* d = g->sp; // offset int offset; int err = slotIntVal(d, &offset); if (err) return err; int alength = slotRawObject(a)->size - offset; if (alength <= 0) { SetNil(a); return errNone; } if (isKindOfSlot(b, class_string)) { int blength = slotRawObject(b)->size; if ((blength == 0) // should also return nil if search string is longer than source || (blength > alength)) { SetNil(a); return errNone; } int cmp = 1; // assume contains will be false char* achar = slotRawString(a)->s + offset; char* bchar = slotRawString(b)->s; char bchar0 = bchar[0]; int scanlength = alength - blength; if (IsTrue(c)) { bchar0 = toupper(bchar0); for (int i = 0; i <= scanlength; ++i, ++achar) { if (toupper(*achar) == bchar0) { cmp = memcmpi(achar + 1, bchar + 1, blength - 1); if (cmp == 0) break; } } } else { for (int i = 0; i <= scanlength; ++i, ++achar) { if (*achar == bchar0) { cmp = memcmp(achar + 1, bchar + 1, blength - 1); if (cmp == 0) break; } } } if (cmp == 0) { SetInt(a, achar - slotRawString(a)->s); } else { SetNil(a); } return errNone; } else if (IsChar(b)) { char* achar = slotRawString(a)->s + offset; char bchar = slotRawChar(b); int scanlength = alength - 1; if (IsTrue(c)) { bchar = toupper(bchar); for (int i = 0; i <= scanlength; ++i, ++achar) { if (toupper(*achar) == bchar) { SetInt(a, achar - slotRawString(a)->s); return errNone; } } } else { for (int i = 0; i <= scanlength; ++i, ++achar) { if (*achar == bchar) { SetInt(a, achar - slotRawString(a)->s); return errNone; } } } SetNil(a); return errNone; } else return errWrongType; } int prString_FindBackwards(struct VMGlobals* g, int numArgsPushed) { PyrSlot* a = g->sp - 3; // source string PyrSlot* b = g->sp - 2; // search string PyrSlot* c = g->sp - 1; // ignoreCase PyrSlot* d = g->sp; // offset int offset; int err = slotIntVal(d, &offset); if (err) return err; int alength = sc_min(offset + 1, slotRawObject(a)->size); if (alength <= 0) { SetNil(a); return errNone; } if (isKindOfSlot(b, class_string)) { int blength = slotRawObject(b)->size; if ((blength == 0) // should also return nil if search string is longer than source || (blength > alength)) { SetNil(a); return errNone; } int cmp = 1; // assume contains will be false char* achar = slotRawString(a)->s + (alength - blength); char* bchar = slotRawString(b)->s; char bchar0 = bchar[0]; int scanlength = alength - blength; if (IsTrue(c)) { bchar0 = toupper(bchar0); for (int i = scanlength; i >= 0; --i, --achar) { if (toupper(*achar) == bchar0) { cmp = memcmpi(achar + 1, bchar + 1, blength - 1); if (cmp == 0) break; } } } else { for (int i = scanlength; i >= 0; --i, --achar) { if (*achar == bchar0) { cmp = memcmp(achar + 1, bchar + 1, blength - 1); if (cmp == 0) break; } } } if (cmp == 0) { SetInt(a, achar - slotRawString(a)->s); } else { SetNil(a); } return errNone; } else if (IsChar(b)) { char* achar = slotRawString(a)->s + (alength - 1); char bchar = slotRawChar(b); int scanlength = alength - 1; if (IsTrue(c)) { bchar = toupper(bchar); for (int i = scanlength; i >= 0; --i, --achar) { if (toupper(*achar) == bchar) { SetInt(a, achar - slotRawString(a)->s); return errNone; } } } else { for (int i = scanlength; i >= 0; --i, --achar) { if (*achar == bchar) { SetInt(a, achar - slotRawString(a)->s); return errNone; } } } SetNil(a); return errNone; } else return errWrongType; } /** \brief Expand `~` to home directory and resolve aliases * * Prints an error message if alias resolution failed. */ int prString_StandardizePath(struct VMGlobals* g, int /* numArgsPushed */) { PyrSlot* arg = g->sp; char ipath[PATH_MAX]; int err = slotStrVal(arg, ipath, PATH_MAX); if (err != errNone) return err; fs::path p = SC_Codecvt::utf8_str_to_path(ipath); p = SC_Filesystem::instance().expandTilde(p); bool isAlias; p = SC_Filesystem::resolveIfAlias(p, isAlias); // Don't consider alias resolution a failure condition, but print an error if (isAlias && p.empty()) error("standardizePath: symlink resolution failed for '%s'\n", ipath); const std::string& utf8_str = SC_Codecvt::path_to_utf8_str(p); PyrString* pyrString = newPyrString(g->gc, utf8_str.c_str(), 0, true); SetObject(arg, pyrString); return errNone; } int prString_EscapeChar(struct VMGlobals* g, int numArgsPushed) { PyrSlot* arg = g->sp - 1; PyrSlot* charToEscapeSlot = g->sp; assert(isKindOfSlot(arg, class_string)); if (!IsChar(charToEscapeSlot)) return errWrongType; char charToEscape = slotRawChar(charToEscapeSlot); PyrString* argString = slotRawString(arg); int length = argString->size; PyrString* resultString = newPyrStringN(g->gc, length * 2 + 1, 0, 1); // pressimize char* original = argString->s; char* result = resultString->s; int resultLength = length; for (int i = 0; i != length; ++i) { char current = *original++; if (current == charToEscape) { *result++ = '\\'; resultLength += 1; } *result++ = current; } *result = 0; resultString->size = resultLength; SetRaw(arg, (PyrObject*)resultString); return errNone; } static void yaml_traverse(struct VMGlobals* g, const YAML::Node& node, PyrObject* parent, PyrSlot* slot) { YAML::NodeType::value type = node.Type(); string out; PyrObject* result = nullptr; switch (type) { case YAML::NodeType::Scalar: out = node.as<string>(); result = (PyrObject*)newPyrString(g->gc, out.c_str(), 0, true); SetObject(slot, result); if (parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew break; case YAML::NodeType::Sequence: result = newPyrArray(g->gc, node.size(), 0, true); SetObject(slot, result); if (parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew for (unsigned int i = 0; i < node.size(); i++) { const YAML::Node& subnode = node[i]; result->size++; yaml_traverse(g, subnode, result, result->slots + i); } break; case YAML::NodeType::Map: { result = instantiateObject(g->gc, s_dictionary->u.classobj, 0, false, true); SetObject(slot, result); if (parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew PyrObject* array = newPyrArray(g->gc, node.size() * 2, 0, true); result->size = 2; SetObject(result->slots, array); // array SetInt(result->slots + 1, node.size()); // size g->gc->GCWriteNew(result, array); // we know array is white so we can use GCWriteNew int j = 0; for (auto const& element : node) { const YAML::Node& key = element.first; const YAML::Node& value = element.second; out = key.as<string>(); PyrObject* pkey = (PyrObject*)newPyrString(g->gc, out.c_str(), 0, true); SetObject(array->slots + j, pkey); array->size++; g->gc->GCWriteNew(array, pkey); // we know pkey is white so we can use GCWriteNew array->size++; yaml_traverse(g, value, array, array->slots + j + 1); j += 2; } break; } case YAML::NodeType::Null: SetNil(slot); break; default: postfl("WARNING: yaml_traverse(): unknown/unsupported node type\n"); SetNil(slot); } } int prString_ParseYAML(struct VMGlobals* g, int numArgsPushed) { PyrSlot* arg = g->sp; if (!isKindOfSlot(arg, class_string)) return errWrongType; string str((const char*)slotRawString(arg)->s, slotRawString(arg)->size); std::istringstream fin(str); YAML::Node doc = YAML::Load(fin); yaml_traverse(g, doc, nullptr, arg); return errNone; } int prString_ParseYAMLFile(struct VMGlobals* g, int numArgsPushed) { PyrSlot* arg = g->sp; if (!isKindOfSlot(arg, class_string)) return errWrongType; string str((const char*)slotRawString(arg)->s, slotRawString(arg)->size); const fs::path& path = SC_Codecvt::utf8_str_to_path(str); std::ifstream fin(path); YAML::Node doc = YAML::Load(fin); yaml_traverse(g, doc, nullptr, arg); return errNone; } void initStringPrimitives() { int base, index = 0; base = nextPrimitiveIndex(); definePrimitive(base, index++, "_StringCompare", prStringCompare, 3, 0); definePrimitive(base, index++, "_StringHash", prStringHash, 1, 0); definePrimitive(base, index++, "_StringPathMatch", prString_PathMatch, 1, 0); definePrimitive(base, index++, "_StringAsSymbol", prStringAsSymbol, 1, 0); definePrimitive(base, index++, "_String_AsInteger", prString_AsInteger, 1, 0); definePrimitive(base, index++, "_String_AsFloat", prString_AsFloat, 1, 0); definePrimitive(base, index++, "_String_AsCompileString", prString_AsCompileString, 1, 0); definePrimitive(base, index++, "_String_Getenv", prString_Getenv, 1, 0); definePrimitive(base, index++, "_String_Setenv", prString_Setenv, 2, 0); definePrimitive(base, index++, "_String_Find", prString_Find, 4, 0); definePrimitive(base, index++, "_String_FindBackwards", prString_FindBackwards, 4, 0); definePrimitive(base, index++, "_String_Format", prString_Format, 2, 0); definePrimitive(base, index++, "_String_Regexp", prString_Regexp, 4, 0); definePrimitive(base, index++, "_String_FindRegexp", prString_FindRegexp, 3, 0); definePrimitive(base, index++, "_String_FindRegexpAt", prString_FindRegexpAt, 3, 0); definePrimitive(base, index++, "_StripRtf", prStripRtf, 1, 0); definePrimitive(base, index++, "_StripHtml", prStripHtml, 1, 0); definePrimitive(base, index++, "_String_StandardizePath", prString_StandardizePath, 1, 0); definePrimitive(base, index++, "_String_EscapeChar", prString_EscapeChar, 2, 0); definePrimitive(base, index++, "_String_ParseYAML", prString_ParseYAML, 1, 0); definePrimitive(base, index++, "_String_ParseYAMLFile", prString_ParseYAMLFile, 1, 0); definePrimitive(base, index++, "_String_ReplaceRegex", prString_ReplaceRegex, 3, 0); }
33,263
C++
.cpp
876
30.285388
120
0.588148
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
29,884
Samp.cpp
supercollider_supercollider/common/Samp.cpp
/* 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 "Samp.hpp" #include "SC_Constants.h" float32 gSine[kSineSize + 1]; float32 gPMSine[kSineSize + 1]; float32 gInvSine[kSineSize + 1]; float32 gSineWavetable[2 * kSineSize]; void SignalAsWavetable(float32* signal, float32* wavetable, long inSize) { float32 val1, val2; float32* in = signal; float32* out = wavetable - 1; for (int i = 0; i < inSize - 1; ++i) { val1 = in[i]; val2 = in[i + 1]; *++out = 2.f * val1 - val2; *++out = val2 - val1; } val1 = in[inSize - 1]; val2 = in[0]; *++out = 2.f * val1 - val2; *++out = val2 - val1; } void WavetableAsSignal(float32* wavetable, float32* signal, long inSize) { float32* in = wavetable - 1; float32* out = signal - 1; for (int i = 0; i < inSize; ++i) { float32 a = *++in; float32 b = *++in; *++out = a + b; } } class SynthLibInit { public: SynthLibInit() { FillTables(); } void FillTables() { double sineIndexToPhase = twopi / kSineSize; double pmf = (1L << 29) / twopi; for (int i = 0; i <= kSineSize; ++i) { double phase = i * sineIndexToPhase; float32 d = sin(phase); gSine[i] = d; gInvSine[i] = 1. / d; gPMSine[i] = d * pmf; } SignalAsWavetable(gSine, gSineWavetable, kSineSize); gInvSine[0] = gInvSine[kSineSize / 2] = gInvSine[kSineSize] = kBadValue; int sz = kSineSize; int sz2 = sz >> 1; for (int i = 1; i <= 8; ++i) { gInvSine[i] = gInvSine[sz - i] = kBadValue; gInvSine[sz2 - i] = gInvSine[sz2 + i] = kBadValue; } } }; static SynthLibInit gSynthLibInit;
2,582
C++
.cpp
70
30.857143
81
0.6248
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
29,886
sc_popen.cpp
supercollider_supercollider/common/sc_popen.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sc_popen.h" #include <cerrno> #include <tuple> #ifndef _WIN32 /* This code is based on popen() and pclose() from Darwin's libc. The only functional difference is that sc_popen() places the new process' pid at the pidp address. sc_pclose() takes this pid which allows the code to be simplified (maintaining a global linked list of fds to pids and locking it is no longer necessary). */ # include <sys/param.h> # include <sys/wait.h> # include <signal.h> # include <unistd.h> # include <paths.h> # include <vector> # include <array> # include <string> std::tuple<pid_t, FILE*> sc_popen(std::string&& command, const std::string& type) { std::vector<std::string> argv; argv.emplace_back("/bin/sh"); argv.emplace_back("-c"); argv.push_back(std::move(command)); return sc_popen_argv(argv, type); } std::tuple<pid_t, FILE*> sc_popen_argv(const std::vector<std::string>& strings, const std::string& type) { std::vector<char*> argv(strings.size() + 1); for (int i = 0; i < strings.size(); ++i) { // execv wants argv as char *const argv[] // need to make the pointer const argv[i] = const_cast<char*>(strings[i].data()); } argv[strings.size()] = nullptr; return sc_popen_c_argv(argv[0], argv.data(), type.c_str()); } std::tuple<pid_t, FILE*> sc_popen_c_argv(const char* filename, char* const argv[], const char* type) { const std::tuple<int, FILE*> error_result = std::make_tuple(-1, nullptr); FILE* iop; pid_t pid; int pdes[2], twoway; /* * Lite2 introduced two-way popen() pipes using _socketpair(). * FreeBSD's pipe() is bidirectional, so we use that. */ if (strchr(type, '+')) { twoway = 1; type = "r+"; } else { twoway = 0; if ((*type != 'r' && *type != 'w') || type[1]) return error_result; } if (pipe(pdes) < 0) return error_result; switch (pid = fork()) { case -1: /* Error. */ (void)close(pdes[0]); (void)close(pdes[1]); return error_result; /* NOTREACHED */ case 0: /* Child. */ if (*type == 'r') { /* * The _dup2() to STDIN_FILENO is repeated to avoid * writing to pdes[1], which might corrupt the * parent's copy. This isn't good enough in * general, since the _exit() is no return, so * the compiler is free to corrupt all the local * variables. */ (void)close(pdes[0]); if (pdes[1] != STDOUT_FILENO) { (void)dup2(pdes[1], STDOUT_FILENO); (void)close(pdes[1]); if (twoway) (void)dup2(STDOUT_FILENO, STDIN_FILENO); } else if (twoway && (pdes[1] != STDIN_FILENO)) (void)dup2(pdes[1], STDIN_FILENO); } else { if (pdes[0] != STDIN_FILENO) { (void)dup2(pdes[0], STDIN_FILENO); (void)close(pdes[0]); } (void)close(pdes[1]); } execvp(filename, argv); exit(127); /* NOTREACHED */ } /* Parent; assume fdopen can't fail. */ if (*type == 'r') { iop = fdopen(pdes[0], type); (void)close(pdes[1]); } else { iop = fdopen(pdes[1], type); (void)close(pdes[0]); } return std::make_tuple(pid, iop); } /* * pclose -- * Pclose returns -1 if stream is not associated with a `popened' command, * if already `pclosed', or waitpid returns an error. */ int sc_pclose(FILE* iop, pid_t mPid) { int pstat = 0; pid_t pid; (void)fclose(iop); do { pid = wait4(mPid, &pstat, 0, (struct rusage*)0); } while (pid == -1 && errno == EINTR); return (pid == -1 ? -1 : pstat); } #else # include <numeric> # include <windows.h> # include <fcntl.h> # include <io.h> # include "SC_Lock.h" # include "SC_Codecvt.hpp" /* The process handle allows us to get the exit code after the process has died. It must be closed in sc_pclose; just having the pid as in the unix version is not enough. Thus this global linked list needs to be maintained and access to it needs to be locked. */ static struct process { struct process* next; FILE* fp; HANDLE handle; } * processlist; static SC_Lock processlist_mutex; # define THREAD_LOCK() processlist_mutex.lock() # define THREAD_UNLOCK() processlist_mutex.unlock() std::tuple<pid_t, FILE*> sc_popen_argv(const std::vector<std::string>& strings, const std::string& type) { // joins strings using space as delimeter std::string commandLine = std::accumulate( strings.begin(), strings.end(), std::string(), [](const std::string& a, const std::string& b) -> std::string { return a + (a.length() > 0 ? " " : "") + b; }); return sc_popen(std::move(commandLine), type); } std::tuple<pid_t, FILE*> sc_popen(std::string&& command, const std::string& type) { return sc_popen_c(command.data(), type.data()); } std::tuple<pid_t, FILE*> sc_popen_c(const char* utf8_cmd, const char* mode) { PROCESS_INFORMATION pi; FILE* f = NULL; int fno; HANDLE child_in, child_out; HANDLE father_in, father_out; HANDLE father_in_dup, father_out_dup; HANDLE current_pid; int binary_mode; struct process* cur; BOOL read_mode, write_mode; const std::tuple<int, FILE*> error_result = std::make_tuple(-1, nullptr); if (utf8_cmd == NULL) { return error_result; } std::wstring cmd = L"cmd /c " + SC_Codecvt::utf8_cstr_to_utf16_wstring(utf8_cmd); current_pid = GetCurrentProcess(); STARTUPINFOW si; ZeroMemory(&si, sizeof(STARTUPINFOW)); si.cb = sizeof(STARTUPINFOW); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); // if the mode contains 'b', use binary mode binary_mode = (strchr(mode, 'b') ? _O_BINARY : _O_TEXT); // check whether the mode includes reading or writing read_mode = (strchr(mode, 'r') != 0); write_mode = (strchr(mode, 'w') != 0); // Opening the pipe for writing if (write_mode) { binary_mode |= _O_WRONLY; if (CreatePipe(&child_in, &father_out, NULL, 0) == FALSE) { fprintf(stderr, "popen: error CreatePipe\n"); return error_result; } if (DuplicateHandle(current_pid, child_in, current_pid, &father_in_dup, 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE) { fprintf(stderr, "popen: error DuplicateHandle father_out\n"); return error_result; } si.hStdInput = father_in_dup; CloseHandle(child_in); fno = _open_osfhandle((size_t)father_out, binary_mode); f = _fdopen(fno, mode); } // Opening the pipe for reading else if (read_mode) { binary_mode |= _O_RDONLY; if (CreatePipe(&father_in, &child_out, NULL, 0) == FALSE) { fprintf(stderr, "popen: error CreatePipe\n"); return error_result; } if (DuplicateHandle(current_pid, child_out, current_pid, &father_out_dup, 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE) { fprintf(stderr, "popen: error DuplicateHandle father_in\n"); return error_result; } CloseHandle(child_out); si.hStdOutput = father_out_dup; fno = _open_osfhandle((size_t)father_in, binary_mode); f = _fdopen(fno, mode); } else { fprintf(stderr, "popen: invalid mode %s\n", mode); return error_result; } // creating child process if (CreateProcessW(NULL, /* pointer to name of executable module */ &cmd[0], /* pointer to command line string */ NULL, /* pointer to process security attributes */ NULL, /* pointer to thread security attributes */ TRUE, /* handle inheritance flag */ 0, /* creation flags */ NULL, /* pointer to environment */ NULL, /* pointer to current directory */ &si, /* pointer to STARTUPINFOW */ &pi /* pointer to PROCESS_INFORMATION */ ) == FALSE) { fprintf(stderr, "popen: CreateProcess %x\n", GetLastError()); fclose(f); return error_result; } // Only the process handle is needed, ignore errors CloseHandle(pi.hThread); // Closing the unnecessary part of the pipe if (read_mode) CloseHandle(father_out_dup); else if (write_mode) CloseHandle(father_in_dup); if ((cur = (struct process*)malloc(sizeof(struct process))) == NULL) { fclose(f); CloseHandle(pi.hProcess); return error_result; } cur->fp = f; cur->handle = pi.hProcess; THREAD_LOCK(); cur->next = processlist; processlist = cur; THREAD_UNLOCK(); return std::make_tuple(pi.dwProcessId, f); } int sc_pclose(FILE* f, pid_t pid) { struct process *cur, *last; int exit_code; THREAD_LOCK(); for (last = NULL, cur = processlist; cur; last = cur, cur = cur->next) if (cur->fp == f) break; if (cur == NULL) { THREAD_UNLOCK(); return (-1); } if (last == NULL) processlist = cur->next; else last->next = cur->next; THREAD_UNLOCK(); if (WaitForSingleObject(cur->handle, INFINITE) != WAIT_OBJECT_0) { fprintf(stderr, "sc_pclose: error, process still active\n"); free(cur); return -1; } if (GetExitCodeProcess(cur->handle, (LPDWORD)&exit_code) == 0) { fprintf(stderr, "sc_pclose: can't get process exit code\n"); free(cur); return -1; } fclose(cur->fp); if (CloseHandle(cur->handle) == FALSE) { fprintf(stderr, "sc_pclose: error closing process handle\n"); free(cur); return -1; } free(cur); return exit_code; } #endif
10,325
C++
.cpp
286
28.93007
119
0.584785
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
29,887
SC_AllocPool.cpp
supercollider_supercollider/common/SC_AllocPool.cpp
/* 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 <string.h> #include <stdexcept> #include "SC_AllocPool.h" #include "SC_BoundsMacros.h" #include <assert.h> #include <string> /* Requests are `small' if both the corresponding and the next bin are small */ #ifdef ENABLE_MEMORY_CHECKS # define check_pool() DoCheckPool() # define check_free_chunk(P) DoCheckFreeChunk(P) # define check_inuse_chunk(P) DoCheckInUseChunk(P) # define check_chunk(P) DoCheckChunk(P) # define check_malloced_chunk(P, N) DoCheckAllocedChunk(P, N) # define garbage_fill(P) DoGarbageFill(P) #else # define check_pool() # define check_free_chunk(P) # define check_inuse_chunk(P) # define check_chunk(P) # define check_malloced_chunk(P, N) # define garbage_fill(P) #endif #define aligned_OK(m) ((((size_t)(m)) & kAlignMask) == 0) /* void* allocmem(AllocPool *pool, int32 size); void* allocmem(AllocPool *pool, int32 size) { return pool->Alloc(size); } void* reallocmem(AllocPool *pool, void* ptr, int32 size); void* reallocmem(AllocPool *pool, void* ptr, int32 size) { return pool->Realloc(ptr, size); } void freemem(AllocPool *pool, void* ptr); void freemem(AllocPool *pool, void* ptr) { pool->Free(ptr); } */ void AllocPool::InitAlloc() { if (mAreaInitSize == 0) return; /* alloc initial area */ NewArea(mAreaInitSize); /* get chunk */ AllocAreaPtr area = mAreas; AllocChunkPtr chunk = &area->mChunk; LinkFree(chunk); check_pool(); } void AllocPool::InitBins() { for (int i = 0; i < kNumAllocBins; ++i) { mBins[i].BeEmpty(); } for (int i = 0; i < 4; ++i) { mBinBlocks[i] = 0; } } AllocPool::AllocPool(NewAreaFunc inAllocArea, FreeAreaFunc inFreeArea, size_t inAreaInitSize, size_t inAreaMoreSize) { InitBins(); mAreaInitSize = inAreaInitSize; mAreaMoreSize = inAreaMoreSize; mAllocArea = inAllocArea; mFreeArea = inFreeArea; mAreas = 0; check_pool(); InitAlloc(); } AllocPool::~AllocPool() { FreeAll(); } void AllocPool::FreeAll() { check_pool(); AllocAreaPtr area = mAreas; if (area) { AllocAreaPtr firstArea = area; do { AllocAreaPtr nextarea = area->mNext; (mFreeArea)(area->mUnalignedPointerToThis); area = nextarea; } while (area != firstArea); mAreas = NULL; } InitBins(); check_pool(); } void AllocPool::FreeAllInternal() { check_pool(); InitBins(); AllocAreaPtr area = mAreas; if (area) { AllocAreaPtr firstArea = area; do { AllocAreaPtr nextarea = area->mNext; size_t size = area->mSize; AllocChunkPtr chunk = &area->mChunk; chunk->SetSizeFree(size); chunk->SetNeighborsInUse(size); LinkFree(chunk); area = nextarea; } while (area != firstArea); } check_pool(); } void AllocPool::Reinit() { FreeAll(); InitAlloc(); } void AllocPool::Free(void* inPtr) { #ifdef DISABLE_MEMORY_POOLS free(inPtr); return; #endif check_pool(); if (inPtr == 0) return; /* free(0) has no effect */ AllocChunkPtr chunk = MemToChunk(inPtr); check_inuse_chunk(chunk); garbage_fill(chunk); size_t size = chunk->Size(); if (!chunk->PrevInUse()) /* consolidate backward */ { size_t prevSize = chunk->PrevSize(); chunk = chunk->ChunkAtOffset(0L - prevSize); size += prevSize; UnlinkFree(chunk); } AllocChunkPtr next = chunk->ChunkAtOffset(size); if (!next->InUse()) /* consolidate forward */ { size += next->Size(); UnlinkFree(next); } chunk->SetSizeFree(size); if (mAreaMoreSize && chunk->IsArea()) { // whole area is free FreeArea(chunk); } else { LinkFree(chunk); } check_pool(); } AllocAreaPtr AllocPool::NewArea(size_t inAreaSize) { void* ptr = (AllocAreaPtr)(mAllocArea)(inAreaSize + kAreaOverhead); if (ptr == NULL) throw std::runtime_error(std::string("Could not allocate new area")); // AllocAreaPtr area = (AllocAreaPtr)((unsigned long)ptr & ~kAlignMask); AllocAreaPtr area = (AllocAreaPtr)(((size_t)ptr + kAlignMask) & ~kAlignMask); assert((area >= ptr) && ((void*)((size_t)area & ~kAlignMask) == area)); area->mUnalignedPointerToThis = ptr; /* link in area */ if (mAreas) { area->mNext = mAreas; area->mPrev = mAreas->mPrev; area->mNext->mPrev = area; area->mPrev->mNext = area; } else { area->mNext = area; area->mPrev = area; } mAreas = area; /* set area size */ area->mSize = inAreaSize; area->mChunk.BeEmpty(); area->mChunk.SetNeighborsInUse(inAreaSize); area->mChunk.SetSizeFree(inAreaSize); return area; } void AllocPool::FreeArea(AllocChunkPtr chunk) { AllocAreaPtr area = (AllocAreaPtr)((char*)chunk - sizeof(AllocAreaHdr)); if (area->mNext == area) { mAreas = NULL; } else { /* unlink area */ mAreas = area->mPrev->mNext = area->mNext; area->mNext->mPrev = area->mPrev; } (mFreeArea)(area->mUnalignedPointerToThis); } size_t AllocPool::TotalFree() { size_t total = 0; for (int i = 0; i < kNumAllocBins; ++i) { AllocChunkPtr bin = mBins + i; if (bin->Prev() != bin) { for (AllocChunkPtr candidate = bin->Prev(); candidate != bin; candidate = candidate->Prev()) { total += candidate->Size(); } } } return total; } size_t AllocPool::LargestFreeChunk() { int word = 0; for (int i = 3; i >= 0; --i) { if (mBinBlocks[i]) { word = i; break; } } int binBits = (int)mBinBlocks[word]; int bitPosition = NUMBITS(binBits) - 1; int index = (word << 5) + bitPosition; AllocChunkPtr bin = mBins + index; // postbuf("** %p %p %p %p\n", mBinBlocks[0], mBinBlocks[1], mBinBlocks[2], mBinBlocks[3]); // postbuf("%d %d %d %p %p %p\n", word, bitPosition, index, binBits, bin->Prev(), bin->Next()); AllocChunkPtr candidate; size_t maxsize = 0; for (candidate = bin->Prev(); candidate != bin; candidate = candidate->Prev()) { size_t candidate_size = candidate->Size(); maxsize = sc_max(maxsize, candidate_size); // postbuf(" %d %d\n", maxsize, candidate_size); } /*for (int i=0; i<kNumAllocBins; ++i) { bin = mBins + i; if (bin->Prev() != bin) { postbuf("* %d %d\n", i, bin->Prev()->Size()); } }*/ return maxsize; } void* AllocPool::Alloc(size_t inReqSize) { #ifdef DISABLE_MEMORY_POOLS return malloc(inReqSize); #endif // OK it has a lot of gotos, but these remove a whole lot of common code // that was obfuscating the original version of this function. // So here I am choosing the OnceAndOnlyOnce principle over the caveats on gotos. // The gotos only jump forward and only to the exit paths of the function // The old bin block scheme has been replaced by 4 x 32 bit words so that each bin has a bit // and the next bin is found using a count leading zeroes instruction. Much faster. // Also now each bin's flag can be kept accurate. This simplifies the searching code quite a bit. // Also fwiw, changed 'victim' in the original code to 'candidate'. 'victim' just bothered me. AllocChunkPtr candidate; /* inspected/selected chunk */ size_t candidate_size; /* its size */ AllocChunkPtr remainder; /* remainder from a split */ int32 remainder_size; /* its size */ AllocAreaPtr area; size_t areaSize; size_t size = RequestToSize(inReqSize); int index = BinIndex(size); assert(index < 128); AllocChunkPtr bin = mBins + index; check_pool(); /* Check for exact match in a bin */ if (index < kMaxSmallBin) { /* Faster version for small requests */ /* No traversal or size check necessary for small bins. */ candidate = bin->Prev(); /* Also scan the next one, since it would have a remainder < kMinAllocSize */ if (candidate == bin) candidate = (++bin)->Prev(); if (candidate != bin) { candidate_size = candidate->Size(); goto found_exact_fit; } index += 2; /* Set for bin scan below. We've already scanned 2 bins. */ } else { for (candidate = bin->Prev(); candidate != bin; candidate = candidate->Prev()) { candidate_size = candidate->Size(); remainder_size = (int)(candidate_size - size); if (remainder_size >= (int32)kMinAllocSize) { /* too big */ --index; /* adjust to rescan below after checking last remainder */ break; } else if (remainder_size >= 0) { /* exact fit */ goto found_exact_fit; } } ++index; } for (; (index = NextFullBin(index)) >= 0; ++index) { bin = mBins + index; /* Find and use first big enough chunk ... */ for (candidate = bin->Prev(); candidate != bin; candidate = candidate->Prev()) { candidate_size = candidate->Size(); remainder_size = (int)(candidate_size - size); if (remainder_size >= (int32)kMinAllocSize) { /* split */ UnlinkFree(candidate); goto found_bigger_fit; } else if (remainder_size >= 0) goto found_exact_fit; } } check_pool(); if (mAreaMoreSize == 0) { /* pool has a non-growable area */ if (mAreas != NULL /* fixed size area exhausted */ || size > mAreaInitSize) /* too big anyway */ goto found_nothing; areaSize = mAreaInitSize; goto split_new_area; } if (size > mAreaMoreSize) { areaSize = size; goto whole_new_area; } else { areaSize = mAreaMoreSize; goto split_new_area; } // exit paths: found_nothing: // ipostbuf("alloc failed. size: %d\n", inReqSize); // throw std::runtime_error(std::string("alloc failed, increase server's memory allocation (e.g. via // ServerOptions)")); return 0; whole_new_area: // ipostbuf("whole_new_area\n"); area = NewArea(areaSize); if (!area) return 0; candidate = &area->mChunk; candidate_size = candidate->Size(); goto return_chunk; split_new_area: // ipostbuf("split_new_area\n"); area = NewArea(areaSize); if (!area) return 0; candidate = &area->mChunk; candidate_size = candidate->Size(); remainder_size = (int)(areaSize - size); // FALL THROUGH found_bigger_fit: // ipostbuf("found_bigger_fit\n"); remainder = candidate->ChunkAtOffset(size); remainder->SetSizeFree(remainder_size); candidate_size -= remainder_size; LinkFree(remainder); goto return_chunk; found_exact_fit: check_pool(); UnlinkFree(candidate); // FALL THROUGH return_chunk: candidate->SetSizeInUse(candidate_size); check_malloced_chunk(candidate, candidate_size); check_pool(); garbage_fill(candidate); return candidate->ToPtr(); } void* AllocPool::Realloc(void* inPtr, size_t inReqSize) { #ifdef DISABLE_MEMORY_POOLS return realloc(inPtr, inReqSize); #endif void* outPtr; AllocChunkPtr prev; check_pool(); bool docopy = false; /* realloc of null is supposed to be same as malloc */ if (inPtr == 0) return Alloc(inReqSize); AllocChunkPtr oldChunk = MemToChunk(inPtr); AllocChunkPtr newChunk = oldChunk; size_t oldsize = oldChunk->Size(); size_t newsize = oldsize; size_t size = RequestToSize(inReqSize); size_t nextsize, prevsize; check_inuse_chunk(oldChunk); if (oldsize < size) { /* Try expanding forward */ AllocChunkPtr next = oldChunk->NextChunk(); if (!next->InUse()) { nextsize = next->Size(); /* Forward into next chunk */ if (nextsize + newsize >= size) { UnlinkFree(next); newsize += nextsize; goto split; } } else { next = 0; nextsize = 0; } /* Try shifting backwards. */ prev = oldChunk->PrevChunk(); if (!prev->InUse()) { prevsize = prev->Size(); /* try forward + backward first to save a later consolidation */ if (next != 0) { /* into next chunk */ if (nextsize + prevsize + newsize >= size) { newsize += nextsize + prevsize; UnlinkFree(next); goto alloc_prev; } } /* backward only */ if (prev != 0 && prevsize + newsize >= size) { newsize += prevsize; goto alloc_prev; } } /* Must allocate */ outPtr = Alloc(inReqSize); check_pool(); if (outPtr == 0) { // ipostbuf("realloc failed. size: %d\n", inReqSize); throw std::runtime_error( std::string("realloc failed, increase server's memory allocation (e.g. via ServerOptions)")); } /* Otherwise copy, free, and exit */ memcpy(outPtr, inPtr, oldsize - sizeof(AllocChunk)); Free(inPtr); return outPtr; } else goto split; alloc_prev: UnlinkFree(prev); newChunk = prev; docopy = true; // FALL THROUGH split: /* split off extra room in old or expanded chunk */ // check_pool(); if (newsize - size >= kMinAllocSize) { /* split off remainder */ size_t remainder_size = newsize - size; AllocChunkPtr remainder = newChunk->ChunkAtOffset(size); remainder->SetSizeInUse(remainder_size); newChunk->SetSizeInUse(size); Free(remainder->ToPtr()); /* let free() deal with it */ } else { newChunk->SetSizeInUse(newsize); } outPtr = newChunk->ToPtr(); if (docopy) { memmove(outPtr, inPtr, oldsize - sizeof(AllocChunk)); } check_inuse_chunk(newChunk); check_pool(); garbage_fill(newChunk); return outPtr; } void AllocPool::LinkFree(AllocChunkPtr inChunk) { size_t size = inChunk->Size(); size_t 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 AllocPool::DoCheckArea(AllocAreaPtr area) { assert(area->mChunk.PrevInUse()); AllocChunkPtr p = &area->mChunk; while (p->mSize != kChunkInUse) { if (p->InUse()) { DoCheckInUseChunk(p); } else { DoCheckFreeChunk(p); } p = p->NextChunk(); } } void AllocPool::DoCheckBin(AllocChunkPtr bin, long index) { AllocChunkPtr p = bin->Next(); while (p != bin) { assert(BinIndex(p->Size()) == index); DoCheckFreeChunk(p); p = p->Next(); } } void AllocPool::DoCheckPool() { AllocAreaPtr area = mAreas; if (area) { do { AllocAreaPtr nextarea = area->mNext; DoCheckArea(area); area = nextarea; } while (area != mAreas); } for (int i = 0; i < kNumAllocBins; ++i) { AllocChunkPtr b = mBins + i; DoCheckBin(b, i); } } void AllocPool::DoCheckChunk(AllocChunkPtr p) { #ifndef NDEBUG size_t size = p->Size(); // size_t maxsize = mAreaInitSize > mAreaMoreSize ? mAreaInitSize : mAreaMoreSize; // assert(size < maxsize); AllocChunkPtr next = p->ChunkAtOffset(size); #endif assert(p->mSize == next->mPrevSize); } void AllocPool::DoCheckFreeChunk(AllocChunkPtr p) { size_t size = p->Size(); #ifndef NDEBUG AllocChunkPtr next = p->ChunkAtOffset(size); #endif DoCheckChunk(p); /* Check whether it claims to be free ... */ assert(!p->InUse()); /* Unless an end marker, must have OK fields */ if (size >= kMinAllocSize) { assert((size & kAlignMask) == 0); assert(aligned_OK(p->ToPtr())); /* ... and is fully consolidated */ assert(p->PrevInUse()); assert(next->InUse()); /* ... and has minimally sane links */ assert(p->Next()->Prev() == p); assert(p->Prev()->Next() == p); } else /* end markers are always of size 0 */ assert(size == 0); } void AllocPool::DoCheckInUseChunk(AllocChunkPtr p) { size_t size = p->Size(); AllocChunkPtr next = p->NextChunk(); DoCheckChunk(p); /* Check whether it claims to be in use ... */ assert(p->InUse()); /* ... and is surrounded by OK chunks. Since more things can be checked with free chunks than inuse ones, if an inuse chunk borders them and debug is on, it's worth doing them. */ if (!p->PrevInUse()) { size_t prevsize = p->PrevSize(); if (prevsize > 0) { AllocChunkPtr prv = p->PrevChunk(); assert(prv->NextChunk() == p); DoCheckFreeChunk(prv); } } if (!p->ChunkAtOffset(size)->InUse()) { DoCheckFreeChunk(next); } } void AllocPool::DoCheckAllocedChunk(AllocChunkPtr p, size_t s) { #ifndef NDEBUG size_t size = p->Size(); long room = size - s; #endif DoCheckInUseChunk(p); /* Legal size ... */ assert(size >= kMinAllocSize); assert((size & kAlignMask) == 0); assert(room >= 0); assert(room < kMinAllocSize); /* ... and alignment */ assert(aligned_OK(p->ToPtr())); /* ... and was allocated at front of an available chunk */ assert(p->PrevInUse()); // huh?? - jmc } void AllocPool::DoGarbageFill(AllocChunkPtr p) { long size = (p->Size() - sizeof(AllocChunk)); DoGarbageFill(p, size); } void AllocPool::DoGarbageFill(AllocChunkPtr p, long size) { size /= sizeof(long); long* ptr = (long*)p->ToPtr(); for (int i = 0; i < size; ++i) { ptr[i] = 0xA3A56955; } }
19,139
C++
.cpp
572
27.01049
118
0.605895
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
29,888
SC_Reply.cpp
supercollider_supercollider/common/SC_Reply.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. Copyright (c) 2012 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 */ #include "SC_Reply.h" #include "SC_ReplyImpl.hpp" void null_reply_func(struct ReplyAddress* addr, char* msg, int size) {} bool operator==(const ReplyAddress& a, const ReplyAddress& b) { return a.mAddress == b.mAddress && a.mProtocol == b.mProtocol && a.mPort == b.mPort && a.mSocket == b.mSocket; } bool operator<(const ReplyAddress& a, const ReplyAddress& b) { if (a.mAddress != b.mAddress) { return a.mAddress < b.mAddress; } else if (a.mPort != b.mPort) { return a.mPort < b.mPort; } else if (a.mSocket != b.mSocket) { return a.mSocket < b.mSocket; } else { return a.mProtocol < b.mProtocol; } }
1,569
C++
.cpp
34
41.529412
114
0.710733
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
29,889
SC_PaUtils.cpp
supercollider_supercollider/common/SC_PaUtils.cpp
// helper functions for SuperCollider server's PortAudio backend #include "SC_PaUtils.hpp" #include <cstring> #include <cstdio> #include <cstdint> #ifdef __APPLE__ # include <pa_mac_core.h> #endif using PaSupportCheckFunc = PaError (*)(PaStreamParameters&, double); PaError CheckDeviceSampleRateOrGetDefault(int* device, double sampleRate, int maxChannels, int defaultDevice, const char* deviceType, PaSupportCheckFunc isSupportedFunc) { if (*device != paNoDevice && sampleRate) { // check if device can support requested SR PaStreamParameters parameters = MakePaStreamParameters(*device, maxChannels, 0); PaError err = isSupportedFunc(parameters, sampleRate); if (err != paNoError) { fprintf(stdout, "PortAudio error: %s\nRequested sample rate %f for device %s is not supported\n", Pa_GetErrorText(err), sampleRate, Pa_GetDeviceInfo(*device)->name); return err; } } // in case we still don't have a proper device, use the default device if (*device == paNoDevice) { *device = defaultDevice; if (*device != paNoDevice) fprintf(stdout, "Selecting default system %s device\n", deviceType); } return paNoError; } void TryMatchDeviceSameAPI(int* matchingDevice, const int* knownDevice, bool isInput) { if (*matchingDevice != paNoDevice || *knownDevice == paNoDevice) return; const auto* devInfo = Pa_GetDeviceInfo(*knownDevice); const auto* apiInfo = Pa_GetHostApiInfo(devInfo->hostApi); const auto maxChannels = isInput ? devInfo->maxInputChannels : devInfo->maxOutputChannels; bool isAsioFullDuplex = apiInfo->type == paASIO && maxChannels > 0; if (isAsioFullDuplex) *matchingDevice = *knownDevice; else { *matchingDevice = isInput ? apiInfo->defaultInputDevice : apiInfo->defaultOutputDevice; if (*matchingDevice != paNoDevice) fprintf(stdout, "Selecting default %s %s device\n", apiInfo->name, (isInput ? "input" : "output")); } } std::string GetPaDeviceName(PaDeviceIndex index) { auto* pdi = Pa_GetDeviceInfo(index); return GetPaDeviceName(pdi); } std::string GetPaDeviceName(const PaDeviceInfo* pdi) { std::string name; #ifndef __APPLE__ name += Pa_GetHostApiInfo(pdi->hostApi)->name; name += " : "; #endif name += pdi->name; return name; } PaDeviceIndex GetPaDeviceFromName(const char* device, bool isInput) { if (device == nullptr || device[0] == '\0') return paNoDevice; PaDeviceIndex numDevices = Pa_GetDeviceCount(); for (PaDeviceIndex i = 0; i < numDevices; i++) { auto* pdi = Pa_GetDeviceInfo(i); std::string devString = GetPaDeviceName(i); if (strstr(devString.c_str(), device)) { if (isInput && pdi->maxInputChannels > 0) { return i; } else if (!isInput && pdi->maxOutputChannels > 0) { return i; } } } return paNoDevice; } PaError TryGetDefaultPaDevices(PaDeviceIndex* inDevice, PaDeviceIndex* outDevice, int numIns, int numOuts, double sampleRate) { if (numIns && !numOuts) { *outDevice = paNoDevice; auto maxChannels = (*inDevice != paNoDevice) ? Pa_GetDeviceInfo(*inDevice)->maxInputChannels : 0; return CheckDeviceSampleRateOrGetDefault( inDevice, sampleRate, maxChannels, Pa_GetDefaultInputDevice(), "input", [](PaStreamParameters& params, double sr) { return Pa_IsFormatSupported(&params, nullptr, sr); }); } else if (!numIns && numOuts) { *inDevice = paNoDevice; auto maxChannels = (*outDevice != paNoDevice) ? Pa_GetDeviceInfo(*outDevice)->maxOutputChannels : 0; return CheckDeviceSampleRateOrGetDefault( outDevice, sampleRate, maxChannels, Pa_GetDefaultOutputDevice(), "output", [](PaStreamParameters& params, double sr) { return Pa_IsFormatSupported(nullptr, &params, sr); }); } else if (numIns && numOuts) { // if one device is specified, let's try to open another one on matching api TryMatchDeviceSameAPI(inDevice, outDevice, true); TryMatchDeviceSameAPI(outDevice, inDevice, false); bool apisAreDifferent = *inDevice != paNoDevice && *outDevice != paNoDevice && Pa_GetDeviceInfo(*inDevice)->hostApi != Pa_GetDeviceInfo(*outDevice)->hostApi; if (apisAreDifferent) { fprintf(stdout, "Requested devices %s and %s use different API. ", GetPaDeviceName(*inDevice).c_str(), GetPaDeviceName(*outDevice).c_str()); *outDevice = Pa_GetHostApiInfo(Pa_GetDeviceInfo(*inDevice)->hostApi)->defaultOutputDevice; fprintf(stdout, "Setting output device to %s.\n", GetPaDeviceName(*outDevice).c_str()); } // check for matching sampleRate or requested sample rate if (*inDevice != paNoDevice && *outDevice != paNoDevice) { const auto in_parameters = MakePaStreamParameters(*inDevice, Pa_GetDeviceInfo(*inDevice)->maxInputChannels, 0); const auto out_parameters = MakePaStreamParameters(*outDevice, Pa_GetDeviceInfo(*outDevice)->maxOutputChannels, 0); if (sampleRate) { // check if devices can support requested SR PaError err = Pa_IsFormatSupported(&in_parameters, &out_parameters, sampleRate); if (err != paNoError) { fprintf(stdout, "\nRequested sample rate %f for devices %s and %s is not supported.\n", sampleRate, GetPaDeviceName(*inDevice).c_str(), GetPaDeviceName(*outDevice).c_str()); return err; } } else { // if we don't request SR, check if devices have matching SR auto inSR = Pa_GetDeviceInfo(*inDevice)->defaultSampleRate; auto outSR = Pa_GetDeviceInfo(*outDevice)->defaultSampleRate; if (uint32_t(inSR) != uint32_t(outSR)) { // if defaults are different, check if both devices can be opened using the OUTPUT's SR PaError err = Pa_IsFormatSupported(&in_parameters, &out_parameters, outSR); if (err != paNoError) { fprintf(stdout, "\nRequested devices %s and %s use different sample rates. " "Please set matching sample rates " "in the Windows Sound Control Panel and try again.\n", GetPaDeviceName(*inDevice).c_str(), GetPaDeviceName(*outDevice).c_str()); return err; } } } } // in case we still don't have a proper device, use default devices if (*inDevice == paNoDevice || *outDevice == paNoDevice) { *inDevice = Pa_GetDefaultInputDevice(); *outDevice = Pa_GetDefaultOutputDevice(); if (*inDevice != paNoDevice && *outDevice != paNoDevice) fprintf(stdout, "Selecting default system input/output devices\n"); } } else { // no inputs nor outputs *inDevice = paNoDevice; *outDevice = paNoDevice; } return paNoError; } PaStreamParameters MakePaStreamParameters(int device, int channelCount, double suggestedLatency) { PaStreamParameters streamParams; PaSampleFormat fmt = paFloat32 | paNonInterleaved; streamParams.device = device; streamParams.channelCount = channelCount; streamParams.sampleFormat = fmt; streamParams.suggestedLatency = suggestedLatency; #ifdef __APPLE__ static PaMacCoreStreamInfo macInfo; PaMacCore_SetupStreamInfo(&macInfo, paMacCorePro); streamParams.hostApiSpecificStreamInfo = &macInfo; #else streamParams.hostApiSpecificStreamInfo = nullptr; #endif return streamParams; }
8,040
C++
.cpp
162
39.87037
119
0.638098
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
29,890
SC_Errors.cpp
supercollider_supercollider/common/SC_Errors.cpp
/* 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_Errors.h" #include "stdio.h" int gMissingNodeID; void SC_ErrorString(SCErr err, char returnString[]) { switch (err) { case kSCErr_None: sprintf(returnString, "none"); break; case kSCErr_Failed: sprintf(returnString, "failed"); break; case kSCErr_NodeNotFound: sprintf(returnString, "Node %i not found", gMissingNodeID); break; case kSCErr_TargetNodeNotFound: sprintf(returnString, "target Node %i not found", gMissingNodeID); break; case kSCErr_GroupNotFound: sprintf(returnString, "Group %i not found", gMissingNodeID); break; case kSCErr_SynthDefNotFound: sprintf(returnString, "SynthDef not found"); break; case kSCErr_NoSuchCommand: sprintf(returnString, "no such command"); break; case kSCErr_WrongArgType: sprintf(returnString, "wrong argument type"); break; case kSCErr_IndexOutOfRange: sprintf(returnString, "index out of range"); break; case kSCErr_AccessDenied: sprintf(returnString, "access denied"); break; case kSCErr_NoReplyPort: sprintf(returnString, "no reply port"); break; case kSCErr_InvalidControlIndex: sprintf(returnString, "invalid control index"); break; case kSCErr_AlreadyLoggedIn: sprintf(returnString, "already logged in"); break; case kSCErr_NotLoggedIn: sprintf(returnString, "not logged in"); break; case kSCErr_TooManyUsers: sprintf(returnString, "too many users"); break; case kSCErr_TooManyNodes: sprintf(returnString, "too many nodes"); break; case kSCErr_DuplicateNodeID: sprintf(returnString, "duplicate node ID"); break; case kSCErr_ReservedNodeID: sprintf(returnString, "negative node IDs are reserved"); break; case kSCErr_ReplaceRootGroup: sprintf(returnString, "can't replace group 0"); break; case kSCErr_OutOfRealTimeMemory: sprintf(returnString, "out of real time memory"); break; case kSCErr_UnsupportedHeaderFormat: sprintf(returnString, "unsupported header format"); break; case kSCErr_UnsupportedSampleFormat: sprintf(returnString, "unsupported sample format"); break; case kSCErr_BufGenNotFound: sprintf(returnString, "buf gen routine not found"); break; default: sprintf(returnString, "unknown error"); } }
3,433
C++
.cpp
94
29.691489
81
0.686805
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
29,891
SC_ServerBootDelayWarning.cpp
supercollider_supercollider/common/SC_ServerBootDelayWarning.cpp
#include "SC_ServerBootDelayWarning.h" #ifdef _WIN32 # include <iostream> # include <thread> # include <mutex> # include <chrono> # include <condition_variable> static bool g_isServerBooted = false; static std::mutex g_serverBootWarningMutex; static std::condition_variable g_serverBootWarningConditionVariable; static std::thread g_bootWarningThread; static void displayWarningIfServerHasNotBooted() { std::unique_lock<std::mutex> lock(g_serverBootWarningMutex); if (!g_serverBootWarningConditionVariable.wait_for(lock, std::chrono::seconds(10), [] { return g_isServerBooted; })) { std::cout << "Server: possible boot delay." << std::endl; std::cout << "On some Windows-based machines, Windows Defender sometimes "; std::cout << "delays server boot by one minute." << std::endl; std::cout << "You can add scsynth.exe and/or supernova.exe *processes* to "; std::cout << "Windows Defender exclusion list to avoid this delay. It's safe." << std::endl; } } #endif //_WIN32 void startServerBootDelayWarningTimer() { #ifdef _WIN32 g_bootWarningThread = std::thread(displayWarningIfServerHasNotBooted); #endif //_WIN32 } void stopServerBootDelayWarningTimer() { #ifdef _WIN32 { const std::lock_guard<std::mutex> lock(g_serverBootWarningMutex); g_isServerBooted = true; } g_serverBootWarningConditionVariable.notify_all(); g_bootWarningThread.join(); #endif //_WIN32 }
1,526
C++
.cpp
38
35.236842
100
0.696356
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
29,892
SC_Win32Utils.cpp
supercollider_supercollider/common/SC_Win32Utils.cpp
/* 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 */ #ifdef _WIN32 # include "SC_Win32Utils.h" # include <cstdio> # include <cstring> # include <cstdlib> # include <sys/timeb.h> # include <time.h> # include <windows.h> # include <shlobj.h> void win32_ReplaceCharInString(char* string, int len, char src, char dst) { for (int i = 0; i < len; i++) if (string[i] == src) string[i] = dst; } void win32_ExtractContainingFolder(char* folder, const char* pattern, int maxChars) { strcpy(folder, pattern); bool backSlashFound = false; int pathLen = strlen(pattern); for (int i = pathLen - 2; i >= 0; --i) { if (pattern[i] == '\\') { folder[i + 1] = 0; backSlashFound = true; break; } } if (!backSlashFound) folder[0] = 0; } char* win32_basename(char* path) { int pathLen = strlen(path); int lastPathSepFoundPos = -1; int pos = 0; while (path[pathLen - 1] == '\\' || path[pathLen - 1] == '/') { path[pathLen - 1] = 0; pathLen--; }; while (path[pos] != 0) { if (path[pos] == '\\' || path[pos] == '/') { lastPathSepFoundPos = pos; } pos++; } if (lastPathSepFoundPos == -1) return path; else return path + lastPathSepFoundPos + 1; } char* win32_dirname(char* path) { int pathLen = strlen(path); int lastPathSepFoundPos = -1; int pos = 0; while (path[pathLen - 1] == '\\' || path[pathLen - 1] == '/') { path[pathLen - 1] = 0; pathLen--; }; while (path[pos] != 0) { if (path[pos] == '\\' || path[pos] == '/') { lastPathSepFoundPos = pos; } pos++; } if (lastPathSepFoundPos != -1) path[lastPathSepFoundPos] = 0; return path; } /* Based on code from PostgreSQL (pgsql/src/port/pipe.c) * This is a replacement version of pipe for Win32 which allows * returned handles to be used in select(). Note that read/write calls * must be replaced with recv/send. */ int win32_pipe(int handles[2]) { SOCKET s; struct sockaddr_in serv_addr; int len = sizeof(serv_addr); handles[0] = handles[1] = INVALID_SOCKET; if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { printf("win32_pipe failed to create socket: %ui", WSAGetLastError()); return -1; } memset((void*)&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(0); serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(s, (SOCKADDR*)&serv_addr, len) == SOCKET_ERROR) { printf("win32_pipe failed to bind: %ui", WSAGetLastError()); return -1; } if (listen(s, 1) == SOCKET_ERROR) { printf("win32_pipe failed to listen to socket: %ui", WSAGetLastError()); closesocket(s); return -1; } if (getsockname(s, (SOCKADDR*)&serv_addr, &len) == SOCKET_ERROR) { printf("win32_pipe failed to getsockname: %ui", WSAGetLastError()); closesocket(s); return -1; } if ((handles[1] = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { printf("win32_pipe failed to create socket 2: %ui", WSAGetLastError()); closesocket(s); return -1; } if (connect(handles[1], (SOCKADDR*)&serv_addr, len) == SOCKET_ERROR) { printf("win32_pipe failed to connect to socket: %ui", WSAGetLastError()); closesocket(s); return -1; } if ((handles[0] = accept(s, (SOCKADDR*)&serv_addr, &len)) == INVALID_SOCKET) { printf("win32_pipe failed to accept socket: %ui", WSAGetLastError()); closesocket(handles[1]); handles[1] = INVALID_SOCKET; closesocket(s); return -1; } closesocket(s); return 0; } int win32_piperead(int s, char* buf, int len) { int ret = recv(s, buf, len, 0); if (ret < 0 && WSAGetLastError() == WSAECONNRESET) /* EOF on the pipe! (win32 socket based implementation) */ ret = 0; return ret; } int win32_pipewrite(int s, char* buf, int len) { int ret = send(s, buf, len, 0); if (ret < 0 && WSAGetLastError() == WSAECONNRESET) /* EOF on the pipe! (win32 socket based implementation) */ ret = 0; return ret; } // Microsoft doesn't recommend the use of SetThreadAffinityMask - except for testing // individual processors - because it can interfere with the OS scheduler and decrease // multi-processing performance. // https://docs.microsoft.com/en-us/windows/win32/procthread/multiple-processors // // In my tests SetThreadIdealProcessor() doesn't seem to improve performance at all. // It is only a hint after all, and the OS is free to ignore it - which it will! // // SetThreadAffinityMask(), on the other hand, really makes a big difference when using // all hardware threads on an Intel SMT machine: // * without thread pinning performance can be *worse* than single thread performance (!) // * with SetThreadAffinityMask() performance can be better than with the default number // of threads (= physical concurrency). // // If someone decides to use thread pinning, they probably are serious about it, so we // use SetThreadAffinity() by default (= STRICT_THREAD_AFFINITY 1) # define STRICT_THREAD_AFFINITY 1 # define DEBUG_THREAD_AFFINITY 0 bool win32_thread_set_affinity(int i) { # if STRICT_THREAD_AFFINITY // SetThreadAffinityMask forces a thread to run only on the specified core(s) DWORD_PTR mask = 1 << i; DWORD_PTR prev = SetThreadAffinityMask(GetCurrentThread(), mask); # if DEBUG_THREAD_AFFINITY fprintf(stdout, "set thread %d affinity mask: previous: %lx, new: %lx\n", i, prev, mask); fflush(stdout); # endif return prev != 0; # else // SetThreadIdealProcessor is merely a hint to the OS scheduler DWORD prev = SetThreadIdealProcessor(GetCurrentThread(), i); # if DEBUG_THREAD_AFFINITY fprintf(stdout, "set thread %d ideal processor: previous: %d, new: %d\n", i, prev, i); fflush(stdout); # endif return prev >= 0; # endif } using SetThreadDescriptionType = HRESULT(WINAPI*)(HANDLE, PCWSTR); int win32_name_thread(const char* name) { // SetThreadDescription is only available on Windows 10 and above. # if _WIN32_WINNT >= 0x0A00 auto fn = &SetThreadDescription; # else // To support older systems, we try to lazily load the function at // runtime from Kernel32.dll. static auto fn = []() -> SetThreadDescriptionType { auto lib = GetModuleHandleA("kernel32"); if (lib) { auto fn = (void*)GetProcAddress(lib, "SetThreadDescription"); if (fn) { return reinterpret_cast<SetThreadDescriptionType>(fn); } } return nullptr; }(); # endif if (fn) { auto size = MultiByteToWideChar(CP_UTF8, 0, name, -1, nullptr, 0); if (size == 0) { return GetLastError(); } auto buffer = (WCHAR*)alloca(size * sizeof(WCHAR)); auto count = MultiByteToWideChar(CP_UTF8, 0, name, -1, buffer, size); if (count == 0) { return GetLastError(); } HRESULT result = fn(GetCurrentThread(), buffer); if (result == S_OK) { return ERROR_SUCCESS; } else { return GetLastError(); } } else { return ERROR_CALL_NOT_IMPLEMENTED; } } #endif // _WIN32
8,338
C++
.cpp
226
31.380531
93
0.632666
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
29,893
SC_StringParser.cpp
supercollider_supercollider/common/SC_StringParser.cpp
// Copyright (c) 2003-2006 stefan kersten // // 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_StringParser.h" #include "SC_BoundsMacros.h" #include <string.h> #include <stdlib.h> SC_StringParser::SC_StringParser(): mSpec(0), mStart(0), mEnd(0), mSep(0) {} SC_StringParser::SC_StringParser(const char* spec, char sep): mSpec(spec), mStart(0), mEnd(0), mSep(sep) { if (mSpec) { size_t len = strlen(mSpec); if (len > 0) { mStart = mSpec; mEnd = mStart + len; } else { mSpec = 0; } } } bool SC_StringParser::AtEnd() const { return mSpec == 0; } const char* SC_StringParser::NextToken() { if (mSpec) { const char* end = strchr(mStart, mSep); if (end == 0) { end = mEnd; } size_t len = sc_min(SC_MAX_TOKEN_LENGTH - 1, end - mStart); memcpy(mBuf, mStart, len); mBuf[len] = '\0'; if (end == mEnd) { mSpec = 0; } else { mStart = end + 1; } return mBuf; } return 0; } // EOF
1,762
C++
.cpp
52
28.769231
106
0.631765
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
29,894
XenomaiLock.cpp
supercollider_supercollider/common/XenomaiLock.cpp
#include "XenomaiLock.h" #include <pthread.h> #include <error.h> #include <string.h> #include <cobalt/sys/cobalt.h> #include <xenomai/init.h> #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <unistd.h> #include <sys/syscall.h> #ifndef __COBALT__ # error This should be compiled with __COBALT__ and the appropriate Xenomai headers in the #include path #endif // __COBALT__ // All __wrap_* calls below are Xenomai libcobalt calls //#define PRINT_XENO_LOCK #ifdef PRINT_XENO_LOCK # define xprintf printf # define xfprintf fprintf #else // PRINT_XENO_LOCK # define xprintf(...) # define xfprintf(...) #endif // PRINT_XENO_LOCK // Standard Linux `gettid(2)` not available on Bela static inline pid_t getTid() { pid_t tid = syscall(SYS_gettid); return tid; } // throughout, we use heuristics to check whether Xenomai needs to be // initialised and whether the current thread is a Xenomai thread. // See https://www.xenomai.org/pipermail/xenomai/2019-January/040203.html static void initializeXenomai() { xprintf("initializeXenomai\n"); int argc = 2; char blankOpt[] = ""; #ifdef PRINT_XENO_LOCK char traceOpt[] = "--trace"; #else // PRINT_XENO_LOCK char traceOpt[] = ""; #endif // PRINT_XENO_LOCK char* const argv[argc] = { blankOpt, traceOpt }; char* const* argvPtrs[argc] = { &argv[0], &argv[1] }; xenomai_init(&argc, argvPtrs); } static bool turnIntoCobaltThread(bool recurred = false) { struct sched_param param; memset(&param, 0, sizeof(param)); int policy; // Guaranteed to succeed as pthread_self() cannot fail and pthread_getschedparam()'s only error condition is when // the given thread does not exist. pthread_getschedparam(pthread_self(), &policy, &param); pid_t tid = getTid(); if (int ret = __wrap_sched_setscheduler(tid, policy, &param)) { fprintf(stderr, "Warning: unable to turn current thread into a Xenomai thread : (%d) %s\n", -ret, strerror(-ret)); initializeXenomai(); if (!recurred) return turnIntoCobaltThread(true); else return false; } xprintf("Turned thread %d into a Cobalt thread %s\n", tid, recurred ? "with recursion" : ""); return true; } XenomaiInitializer::XenomaiInitializer() { initializeXenomai(); } XenomaiMutex::XenomaiMutex() { xprintf("Construct mutex\n"); if (int ret = __wrap_pthread_mutex_init(&m_mutex, NULL)) { if (EPERM != ret) { xprintf("__wrap_thread_mutex_init failed with %d %s\n", ret, strerror(ret)); return; } else { xprintf("mutex init returned EPERM\n"); initializeXenomai(); if (int ret = __wrap_pthread_mutex_init(&m_mutex, NULL)) { fprintf(stderr, "Error: unable to initialize mutex : (%d) %s\n", ret, strerror(-ret)); return; } } } m_enabled = true; } XenomaiMutex::~XenomaiMutex() { xprintf("Destroy mutex %p\n", &m_mutex); if (m_enabled) __wrap_pthread_mutex_destroy(&m_mutex); } // a helper function to try // - call func() // - if it fails, try to turn the current thread into a cobalt thread and call func() again // - if it fails again, just fail // - return true if it succeeds, or false if it fails // id and name are just for debugging purposes, while m_enabled is there because it saves duplicating some lines template <typename F, typename T> static bool tryOrRetryImpl(F&& func, bool m_enabled, T* id, const char* name) { xprintf("tid: %d ", getTid()); if (!m_enabled) { xfprintf(stderr, "%s disabled %p\n", name, id); return false; } xprintf("%s %p\n", name, id); int ret = func(); // 0 is "success" (or at least meaningful failure) if (0 == ret) { return true; } else if (EPERM != ret) { return false; } else { // if we got EPERM, we are not a Xenomai thread if (!turnIntoCobaltThread()) { xfprintf(stderr, "%s %p could not turn into cobalt\n", name, id); return false; } } // retry after becoming a cobalt thread ret = func(); if (0 == ret) { return true; } else { xfprintf(stderr, "%s %p failed after having turned into cobalt: %d\n", name, id, ret); return false; } } // Helper macro to insert this-ptr and function name #define tryOrRetry(_func_, _enabled_) tryOrRetryImpl(_func_, _enabled_, this, __func__) // condition resource_deadlock_would_occur instead of deadlocking. https://en.cppreference.com/w/cpp/thread/mutex/lock bool XenomaiMutex::try_lock() { return tryOrRetry([this]() { return __wrap_pthread_mutex_trylock(&this->m_mutex); }, m_enabled); // TODO: An implementation that can detect the invalid usage is encouraged to throw a std::system_error with error // condition resource_deadlock_would_occur instead of deadlocking. } void XenomaiMutex::lock() { tryOrRetry([this]() { return __wrap_pthread_mutex_lock(&this->m_mutex); }, m_enabled); } void XenomaiMutex::unlock() { tryOrRetry([this]() { return __wrap_pthread_mutex_unlock(&this->m_mutex); }, m_enabled); } XenomaiConditionVariable::XenomaiConditionVariable() { xprintf("Construct CondictionVariable\n"); if (int ret = __wrap_pthread_cond_init(&m_cond, NULL)) { if (EPERM != ret) { xprintf("__wrap_thread_cond_init failed with %d %s\n", ret, strerror(ret)); return; } else { xprintf("mutex init returned EPERM\n"); initializeXenomai(); if (int ret = __wrap_pthread_cond_init(&m_cond, NULL)) { fprintf(stderr, "Error: unable to create condition variable : (%d) %s\n", ret, strerror(ret)); return; } } } m_enabled = true; } XenomaiConditionVariable::~XenomaiConditionVariable() { if (m_enabled) { notify_all(); __wrap_pthread_cond_destroy(&m_cond); } } void XenomaiConditionVariable::wait(std::unique_lock<XenomaiMutex>& lck) { // If any parameter has a value that is not valid for this function (such as if lck's mutex object is not locked by // the calling thread), it causes undefined behavior. // Otherwise, if an exception is thrown, both the condition_variable_any object and the arguments are in a valid // state (basic guarantee). Additionally, on exception, the state of lck is attempted to be restored before exiting // the function scope (by calling lck.lock()). // It may throw system_error in case of failure (transmitting any error condition from the respective call to lock // or unlock). The predicate version (2) may also throw exceptions thrown by pred. tryOrRetry(([this, &lck]() { return __wrap_pthread_cond_wait(&this->m_cond, &lck.mutex()->m_mutex); }), m_enabled); } void XenomaiConditionVariable::notify_one() noexcept { tryOrRetry([this]() { return __wrap_pthread_cond_signal(&this->m_cond); }, m_enabled); } void XenomaiConditionVariable::notify_all() noexcept { tryOrRetry([this]() { return __wrap_pthread_cond_broadcast(&this->m_cond); }, m_enabled); }
7,183
C++
.cpp
175
35.845714
119
0.65621
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
29,895
SC_Filesystem_unix.cpp
supercollider_supercollider/common/SC_Filesystem_unix.cpp
/* * Copyright (c) 2005 Tim Walters. All rights reserved. * Copyright (c) 2017 Brian Heim. All rights reserved. * Created by Tim Walters on 2005-10-19. * * Revision history: * Changed from SC_DirUtils to SC_Filesystem (Brian Heim, 2017-04-03) * * 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 */ /* * SC_Filesystem implementation for Linux/FreeBSD/OpenBSD. */ #if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) # include "SC_Filesystem.hpp" // system # include <glob.h> // ::glob, glob_t // workaround for musl not yet supporting GLOB_TILDE # ifndef GLOB_TILDE # define GLOB_TILDE 0 # endif using Path = SC_Filesystem::Path; using DirName = SC_Filesystem::DirName; using DirMap = SC_Filesystem::DirMap; //============ DIRECTORY NAMES =============// const char* SHARE_DIR_NAME = "share"; const char* USER_DIR_NAME = "usr"; const char* LOCAL_DIR_NAME = "local"; const char* DOT_LOCAL = ".local"; const char* DOT_CONFIG = ".config"; const Path ROOT_PATH = Path("/"); //============ PATH UTILITIES =============// Path SC_Filesystem::resolveIfAlias(const Path& p, bool& isAlias) { isAlias = false; return p; } //============ GLOB UTILITIES =============// struct SC_Filesystem::Glob { glob_t mHandle; size_t mEntry; }; SC_Filesystem::Glob* SC_Filesystem::makeGlob(const char* pattern) { Glob* glob = new Glob; const int flags = GLOB_MARK | GLOB_TILDE; const int err = ::glob(pattern, flags, nullptr, &glob->mHandle); if (err < 0) { delete glob; return nullptr; } glob->mEntry = 0; return glob; } void SC_Filesystem::freeGlob(Glob* glob) { globfree(&glob->mHandle); delete glob; } Path SC_Filesystem::globNext(Glob* glob) { if (glob->mEntry >= glob->mHandle.gl_pathc) return Path(); return Path(glob->mHandle.gl_pathv[glob->mEntry++]); } //============= PRIVATE METHODS ==============// bool SC_Filesystem::isNonHostPlatformDirectoryName(const std::string& s) { return s == "osx" || s == "windows" || s == "iphone"; } Path SC_Filesystem::defaultSystemAppSupportDirectory() { # ifdef SC_DATA_DIR return Path(SC_DATA_DIR); # else return ROOT_PATH / LOCAL_DIR_NAME / SHARE_DIR_NAME / SC_FOLDERNAME_APPLICATION_NAME; # endif } Path SC_Filesystem::defaultUserHomeDirectory() { const char* home = getenv("HOME"); return Path(home ? home : ""); } Path SC_Filesystem::defaultUserAppSupportDirectory() { const char* xdg_data_home = getenv("XDG_DATA_HOME"); if (xdg_data_home) return Path(xdg_data_home) / SC_FOLDERNAME_APPLICATION_NAME; const Path& p = defaultUserHomeDirectory(); return p.empty() ? p : p / DOT_LOCAL / SHARE_DIR_NAME / SC_FOLDERNAME_APPLICATION_NAME; } Path SC_Filesystem::defaultUserConfigDirectory() { const char* xdg_config_home = getenv("XDG_CONFIG_HOME"); if (xdg_config_home) return Path(xdg_config_home) / SC_FOLDERNAME_APPLICATION_NAME; const Path& p = defaultUserHomeDirectory(); return p.empty() ? p : p / DOT_CONFIG / SC_FOLDERNAME_APPLICATION_NAME; } Path SC_Filesystem::defaultResourceDirectory() { # ifdef SC_DATA_DIR return Path(SC_DATA_DIR); # else return ROOT_PATH / USER_DIR_NAME / SHARE_DIR_NAME / SC_FOLDERNAME_APPLICATION_NAME; # endif } #endif // defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
4,080
C++
.cpp
111
33.882883
91
0.679341
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
29,896
SC_Filesystem_win.cpp
supercollider_supercollider/common/SC_Filesystem_win.cpp
/* * Copyright (c) 2005 Tim Walters. All rights reserved. * Copyright (c) 2017 Brian Heim. All rights reserved. * Created by Tim Walters on 2005-10-19. * * Revision history: * Changed from SC_DirUtils to SC_Filesystem (Brian Heim, 2017-04-03) * * 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 */ /* * SC_Filesystem implementation for Windows. */ #ifdef _WIN32 # include "SC_Filesystem.hpp" # include "SC_Codecvt.hpp" # include <filesystem> // system # include <Shlobj.h> // SHGetKnownFolderPath using Path = SC_Filesystem::Path; using DirName = SC_Filesystem::DirName; using DirMap = SC_Filesystem::DirMap; //============ PATH UTILITIES =============// Path SC_Filesystem::resolveIfAlias(const Path& p, bool& isAlias) { isAlias = false; return p; } //============ GLOB UTILITIES =============// // Keep a buffer of one filename to return on the next call to nextGlob. // This is because FindFirstFile already loads one filename. struct SC_Filesystem::Glob { HANDLE mHandle; // find handle Path mFolder; // parent folder of the search path WIN32_FIND_DATAW mEntry; bool mAtEnd; // true if the NEXT call to nextGlob should fail Path mFilename; // filename to return on the next call to nextGlob }; SC_Filesystem::Glob* SC_Filesystem::makeGlob(const char* pattern) { Glob* glob = new Glob; // use make_preferred() to change / -> \ on Windows std::filesystem::path path = SC_Codecvt::utf8_str_to_path(pattern).make_preferred(); // remove a trailing backslash. Even if searching with 'foo/.', this will // change to 'foo' harmlessly. Use has_parent_path() because otherwise '.' // (referring to the CWD) won't be recognized as a valid query. if (path.filename() == "." && path.has_parent_path()) path = path.parent_path(); // expand to home directory, if path starts with tilde path = SC_Filesystem::instance().expandTilde(path); glob->mHandle = ::FindFirstFileW(path.wstring().c_str(), &glob->mEntry); if (glob->mHandle == INVALID_HANDLE_VALUE) { delete glob; return nullptr; } glob->mFolder = path.parent_path(); glob->mAtEnd = false; return glob; } void SC_Filesystem::freeGlob(Glob* glob) { ::FindClose(glob->mHandle); delete glob; } Path SC_Filesystem::globNext(Glob* glob) { bool isDirectory = false; // loop to ignore . and .. results do { if (glob->mAtEnd) return Path(); glob->mFilename = glob->mFolder / glob->mEntry.cFileName; // record whether it's a directory here, since we overwrite mEntry on the next step isDirectory = (glob->mEntry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0; if (!::FindNextFileW(glob->mHandle, &glob->mEntry)) glob->mAtEnd = true; } while (glob->mFilename.filename() == "." || glob->mFilename.filename() == ".."); // add preferred separator (L'\\') for directories on Windows, to match // POSIX globbing. boost::filesystem::is_directory won't work for this because // in the case of input '.' and '..', the filename here is just a single folder, // not a relative path, and so can't be correctly identified. Plus, it's faster // to check the attributes than to make another system call. return isDirectory ? glob->mFilename += std::filesystem::path::preferred_separator : glob->mFilename; } //============= PRIVATE METHODS ==============// bool SC_Filesystem::isNonHostPlatformDirectoryName(const std::string& s) { return s == "linux" || s == "osx" || s == "iphone"; } Path SC_Filesystem::defaultSystemAppSupportDirectory() { PWSTR wptr = nullptr; const HRESULT hr = SHGetKnownFolderPath(FOLDERID_ProgramData, 0, nullptr, &wptr); return FAILED(hr) ? Path() : Path(wptr) / SC_FOLDERNAME_APPLICATION_NAME; } Path SC_Filesystem::defaultUserHomeDirectory() { PWSTR wptr = nullptr; const HRESULT hr = SHGetKnownFolderPath(FOLDERID_Profile, 0, nullptr, &wptr); return FAILED(hr) ? Path() : Path(wptr); } Path SC_Filesystem::defaultUserAppSupportDirectory() { PWSTR wptr = nullptr; const HRESULT hr = SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &wptr); return FAILED(hr) ? Path() : Path(wptr) / SC_FOLDERNAME_APPLICATION_NAME; } Path SC_Filesystem::defaultUserConfigDirectory() { return defaultUserAppSupportDirectory(); } Path SC_Filesystem::defaultMyDocumentsDirectory() { PWSTR wptr = nullptr; const HRESULT hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &wptr); return FAILED(hr) ? Path() : Path(wptr) / SC_FOLDERNAME_APPLICATION_NAME; } Path SC_Filesystem::defaultResourceDirectory() { WCHAR buf[MAX_PATH]; GetModuleFileNameW(nullptr, buf, MAX_PATH); return Path(buf).parent_path(); } #endif // _WIN32
5,488
C++
.cpp
124
40.5
105
0.694788
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
29,897
SC_Filesystem_iphone.cpp
supercollider_supercollider/common/SC_Filesystem_iphone.cpp
/* * Copyright (c) 2005 Tim Walters. All rights reserved. * Copyright (c) 2017 Brian Heim. All rights reserved. * Created by Tim Walters on 2005-10-19. * * Revision history: * Changed from SC_DirUtils to SC_Filesystem (Brian Heim, 2017-04-03) * * 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 */ /* * SC_Filesystem implementation for iPhone. */ #ifdef SC_IPHONE # include "SC_Filesystem.hpp" // system # include <glob.h> // ::glob, glob_t using Path = SC_Filesystem::Path; using DirName = SC_Filesystem::DirName; using DirMap = SC_Filesystem::DirMap; //============ DIRECTORY NAMES =============// const char* LIBRARY_DIR_NAME = "Library"; const char* DOCUMENTS_DIR_NAME = "Documents"; const char* APPLICATION_SUPPORT_DIR_NAME = "Application Support"; const Path ROOT_PATH = Path("/"); //============ PATH UTILITIES =============// Path SC_Filesystem::resolveIfAlias(const Path& p, bool& isAlias) { isAlias = false; return p; } //============ GLOB UTILITIES =============// struct SC_Filesystem::Glob { glob_t mHandle; size_t mEntry; }; SC_Filesystem::Glob* SC_Filesystem::makeGlob(const char* pattern) { Glob* glob = new Glob; const int flags = GLOB_MARK | GLOB_TILDE | GLOB_QUOTE; const int err = ::glob(pattern, flags, nullptr, &glob->mHandle); if (err < 0) { delete glob; return nullptr; } glob->mEntry = 0; return glob; } void SC_Filesystem::freeGlob(Glob* glob) { globfree(&glob->mHandle); delete glob; } Path SC_Filesystem::globNext(Glob* glob) { if (glob->mEntry >= glob->mHandle.gl_pathc) return Path(); return Path(glob->mHandle.gl_pathv[glob->mEntry++]); } //============= PRIVATE METHODS ==============// bool SC_Filesystem::isNonHostPlatformDirectoryName(const std::string& s) { return s == "linux" || s == "windows" || s == "osx"; } Path SC_Filesystem::defaultSystemAppSupportDirectory() { // Note: original implementation called sc_AppendBundleName if defined(__APPLE__). // However, that function is only defined when !defined(SC_IPHONE). I have taken // the more conservative approach and avoided appending the bundle name here. -BH return ROOT_PATH; } Path SC_Filesystem::defaultUserHomeDirectory() { const char* home = getenv("HOME"); return Path(home ? home : ""); } Path SC_Filesystem::defaultUserAppSupportDirectory() { // Note: I have not added XDG support here because that seems highly unlikely on iPhone. -BH const Path& p = defaultUserHomeDirectory(); return p.empty() ? p : p / DOCUMENTS_DIR_NAME; } Path SC_Filesystem::defaultUserConfigDirectory() { // Note: I have not added XDG support here because that seems highly unlikely on iPhone. -BH return defaultUserAppSupportDirectory(); } Path SC_Filesystem::defaultResourceDirectory() { return defaultUserAppSupportDirectory(); } #endif // SC_IPHONE
3,585
C++
.cpp
93
35.634409
96
0.696542
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
29,898
SC_Filesystem_macos.cpp
supercollider_supercollider/common/SC_Filesystem_macos.cpp
/* * Copyright (c) 2005 Tim Walters. All rights reserved. * Copyright (c) 2017 Brian Heim. All rights reserved. * Created by Tim Walters on 2005-10-19. * * Revision history: * Changed from SC_DirUtils to SC_Filesystem (Brian Heim, 2017-04-03) * * 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 */ /* * SC_Filesystem implementation for macOS. */ #if defined(__APPLE__) && !defined(SC_IPHONE) # include "SC_Filesystem.hpp" # include <filesystem> // path, parent_path(), canonical, current_path() # include <cassert> // system includes # include <Foundation/NSAutoreleasePool.h> # include <Foundation/NSFileManager.h> # include <Foundation/NSURL.h> # include <CoreFoundation/CFBundle.h> # include <CoreFoundation/CFString.h> # include <glob.h> // ::glob, glob_t # include <mach-o/dyld.h> // _NSGetExecutablePath # include <algorithm> // std::mismatch using Path = SC_Filesystem::Path; using DirName = SC_Filesystem::DirName; using DirMap = SC_Filesystem::DirMap; //============ DIRECTORY NAMES =============// const char* LIBRARY_DIR_NAME = "Library"; const char* APPLICATION_SUPPORT_DIR_NAME = "Application Support"; const Path ROOT_PATH = Path("/"); //====== STATIC FUNC FORWARD DECLS =======// // Get the bundle name static const char* getBundleName(); //============ PATH UTILITIES =============// Path SC_Filesystem::resolveIfAlias(const Path& p, bool& isAlias) { NSString* nsPath = [NSString stringWithCString:p.c_str() encoding:NSUTF8StringEncoding]; BOOL isDirectory; // does the file exist? If not just copy and bail if ([[NSFileManager defaultManager] fileExistsAtPath:nsPath isDirectory:&isDirectory]) { NSURL* aliasURL = [NSURL fileURLWithPath:nsPath isDirectory:isDirectory]; NSError* error = nil; // Previously, used bookmarkDataWithContentsOfURL. But for some reason, the call would hang // endlessly on certain files (e.g. /dev/auditsessions with mode crw-r--r--). So, we do the // less reliable thing and try to resolve it forcefully. If it is an alias, the resulting // path will be different (not always true, see below). See issue #4131. NSURL* resolvedURL = [NSURL URLByResolvingAliasFileAtURL:aliasURL options:NSURLBookmarkResolutionWithoutMounting | NSURLBookmarkResolutionWithoutUI error:&error]; // If there was an error, it was a broken alias. Otherwise no error even if it wasn't an alias // to begin with; even if it doesn't exist (i.e. was destroyed between `fileExistsAtPath` and // `URLByResolvingAliasFileAtURL`)! if (error != nil) { isAlias = true; return Path(); } const char* resolvedNsPath = [[resolvedURL path] cStringUsingEncoding:NSUTF8StringEncoding]; // Unlikely, but possible if (resolvedNsPath == nullptr) { assert(false && "Resolved path could not be converted to C string"); isAlias = true; return Path(); } // #4252 - URLByResolvingAliasFileAtURL will remove last trailing slash ('/Users/' -> // '/Users', '/Users///' -> '/Users//'). Protect against this case. auto* pEnd = p.c_str() + p.string().size(); const auto* mismatchPos = std::mismatch(p.c_str(), pEnd, resolvedNsPath).first; // note that p.size() >= 1 because empty string would fail 'fileExistsAtPath' if (mismatchPos == pEnd || (mismatchPos == pEnd - 1 && *mismatchPos == '/')) { isAlias = false; return p; } else { isAlias = true; return Path(resolvedNsPath); } } isAlias = false; return p; } //============ GLOB UTILITIES =============// struct SC_Filesystem::Glob { glob_t mHandle; size_t mEntry; }; SC_Filesystem::Glob* SC_Filesystem::makeGlob(const char* pattern) { Glob* glob = new Glob; const int flags = GLOB_MARK | GLOB_TILDE | GLOB_QUOTE; const int err = ::glob(pattern, flags, nullptr, &glob->mHandle); if (err < 0) { delete glob; return nullptr; } glob->mEntry = 0; return glob; } void SC_Filesystem::freeGlob(Glob* glob) { globfree(&glob->mHandle); delete glob; } Path SC_Filesystem::globNext(Glob* glob) { if (glob->mEntry >= glob->mHandle.gl_pathc) return Path(); return Path(glob->mHandle.gl_pathv[glob->mEntry++]); } //============= PRIVATE METHODS ==============// bool SC_Filesystem::isNonHostPlatformDirectoryName(const std::string& s) { return s == "linux" || s == "windows" || s == "iphone"; } Path SC_Filesystem::defaultSystemAppSupportDirectory() { // "/Library/Application Support/[SuperCollider]" return ROOT_PATH / LIBRARY_DIR_NAME / APPLICATION_SUPPORT_DIR_NAME / getBundleName(); } Path SC_Filesystem::defaultUserHomeDirectory() { // "/Users/[username]" const char* home = getenv("HOME"); return Path(home ? home : ""); } Path SC_Filesystem::defaultUserAppSupportDirectory() { // XDG support // see http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html const char* home = getenv("XDG_DATA_HOME"); if (home) return Path(home) / SC_FOLDERNAME_APPLICATION_NAME; const Path& p = defaultUserHomeDirectory(); // "/Users/[username]/Library/Application Support/[SuperCollider]" return p.empty() ? p : p / LIBRARY_DIR_NAME / APPLICATION_SUPPORT_DIR_NAME / getBundleName(); } Path SC_Filesystem::defaultUserConfigDirectory() { // XDG support // see http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html const char* xdgConfigHome = getenv("XDG_CONFIG_HOME"); if (xdgConfigHome) return Path(xdgConfigHome) / SC_FOLDERNAME_APPLICATION_NAME; else return defaultUserAppSupportDirectory(); } Path SC_Filesystem::defaultResourceDirectory() { Path ret; CFStringEncoding encoding = kCFStringEncodingUTF8; CFURLRef enablerURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("SCClassLibrary"), NULL, NULL); if (!enablerURL) { enablerURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("sclang.app"), NULL, NULL); } if (enablerURL) { // If sclang or SuperCollider binary is run within the .app bundle, // this is how we find the Resources path. char relDir[PATH_MAX]; CFStringRef rawUrlPath = CFURLCopyFileSystemPath(enablerURL, kCFURLPOSIXPathStyle); CFStringRef rawPath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@/.."), rawUrlPath); CFStringGetCString(rawPath, relDir, PATH_MAX, encoding); CFRelease(rawUrlPath); CFRelease(rawPath); CFRelease(enablerURL); ret = Path(relDir); } else { // when sclang is run from a symlink, the resource URL above will not be found, // so we need to find the path of the executable. uint32_t bufsize = PATH_MAX; char relDir[PATH_MAX]; if (_NSGetExecutablePath(relDir, &bufsize) == 0) { ret = std::filesystem::canonical(relDir); // resolve symlink ret = ret.parent_path(); } else { // in case it failed, fall back to current directory ret = std::filesystem::current_path(); } } ret = std::filesystem::canonical(ret); // resolve lingering symlink return ret; } //============= STATIC FUNCTIONS =============// const char* getBundleName() { CFBundleRef mainBundle; mainBundle = CFBundleGetMainBundle(); if (mainBundle) { CFDictionaryRef dictRef = CFBundleGetInfoDictionary(mainBundle); CFStringRef strRef; strRef = (CFStringRef)CFDictionaryGetValue(dictRef, CFSTR("CFBundleName")); if (strRef) { const char* bundleName = CFStringGetCStringPtr(strRef, CFStringGetSystemEncoding()); if (bundleName) { return bundleName; } } } return SC_FOLDERNAME_APPLICATION_NAME; } #endif // defined(__APPLE__) && !defined(SC_IPHONE)
8,810
C++
.cpp
204
37.348039
114
0.661492
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
29,899
SC_TextUtils.cpp
supercollider_supercollider/common/SC_TextUtils.cpp
/* 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 */ #include "SC_TextUtils.hpp" #include <cstring> #define OPENCURLY '{' #define CLOSCURLY '}' int rtf2txt(char* txt) { int rdpos = 0, wrpos = 0; char c; if (strncmp(txt, "{\\rtf", 5) != 0) return 0; // OK, not an RTF file text: switch (txt[wrpos] = txt[rdpos++]) { case 0: /*{ char fname[32]; sprintf(fname, "rtf2txt_out%d.txt", bugctr++); FILE *fp = fopen(fname, "w"); fwrite(txt,wrpos,1,fp); fclose(fp); }*/ return wrpos; case OPENCURLY: case CLOSCURLY: case '\n': goto text; case '\\': if (strncmp(txt + rdpos, "fonttbl", 7) == 0 || strncmp(txt + rdpos, "filetbl", 7) == 0 || strncmp(txt + rdpos, "colortbl", 8) == 0 || strncmp(txt + rdpos, "stylesheet", 10) == 0) { int level = 1; while (level && (c = txt[rdpos++]) != 0) { if (c == OPENCURLY) level++; else if (c == CLOSCURLY) level--; } } else if (strncmp(txt + rdpos, "\'a0", 3) == 0 || (strncmp(txt + rdpos, "\'A0", 3) == 0)) { txt[wrpos++] = ' '; rdpos = rdpos + 3; } else { if (txt[rdpos] == CLOSCURLY || txt[rdpos] == OPENCURLY || txt[rdpos] == '\\' || txt[rdpos] == '\t' || txt[rdpos] == '\n') { txt[wrpos++] = txt[rdpos++]; goto text; } if (strncmp(txt + rdpos, "tab", 3) == 0) { txt[wrpos++] = '\t'; } if (strncmp(txt + rdpos, "par", 3) == 0) { txt[wrpos++] = '\n'; } while ((c = txt[rdpos++]) && c != ' ' && c != '\\') ; if (c == '\\') rdpos--; } goto text; default: wrpos++; goto text; } } // strips HTML down to plaintext tags in a fairly simple-minded way int html2txt(char* txt) { int rdpos = -1, wrpos = 0, bodypos = -1; bool intag = false; // First check if we can find a BODY tag to start at while (bodypos == -1 && txt[++rdpos] != 0) { if (strncmp(txt + rdpos, "<body", 5) == 0) // FIXME: should be case-insensitive, ideally bodypos = rdpos; } if (bodypos != -1) rdpos = bodypos; else rdpos = 0; // Now we start from our start, and add the non-tag text to the result while (txt[rdpos] != 0) { if (intag) { if (txt[rdpos++] == '>') intag = false; } else { if (txt[rdpos] == '<') { intag = true; ++rdpos; } else { /* if(strncmp(txt+rdpos, "&amp;", 5)==0){ txt[wrpos++] = '&'; rdpos += 5; }else if(strncmp(txt+rdpos, "&nbsp;", 6)==0){ txt[wrpos++] = ' '; rdpos += 6; }else if(strncmp(txt+rdpos, "&lt;", 4)==0){ txt[wrpos++] = '<'; rdpos += 4; }else if(strncmp(txt+rdpos, "&gt;", 4)==0){ txt[wrpos++] = '>'; rdpos += 4; }else{ */ txt[wrpos++] = txt[rdpos++]; //} } } } txt[wrpos] = 0; return wrpos; }
4,414
C++
.cpp
123
25.308943
110
0.473955
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
29,900
SC_StringBuffer.cpp
supercollider_supercollider/common/SC_StringBuffer.cpp
// emacs: -*- c++ -*- // file: SC_StringBuffer.cpp // copyright: 2003 stefan kersten <steve@k-hornz.de> // 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 #include "SC_StringBuffer.h" #include <assert.h> #include <stdio.h> #include <string.h> #include <stdexcept> #ifdef _WIN32 # define vsnprintf _vsnprintf # include <stdio.h> # include <stdarg.h> #endif #include <string> SC_StringBuffer::SC_StringBuffer(size_t initialSize): mCapacity(0), mPtr(0), mData(0) { growBy(initialSize); } SC_StringBuffer::SC_StringBuffer(const SC_StringBuffer& other): mCapacity(0), mPtr(0), mData(0) { growBy(other.getSize()); append(other.getData(), other.getSize()); } SC_StringBuffer::~SC_StringBuffer() { free(mData); } void SC_StringBuffer::append(const char* src, size_t size) { if (size > 0) { size_t remaining = getRemaining(); if (size > remaining) { growBy(size - remaining); } memcpy(mPtr, src, size); mPtr += size; } } void SC_StringBuffer::append(char c) { append(&c, sizeof(c)); } void SC_StringBuffer::append(const char* str) { append(str, strlen(str)); } void SC_StringBuffer::vappendf(const char* fmt, va_list ap) { va_list ap2; size_t remaining = getRemaining(); // Calling vsnprintf may invalidate vargs, so keep a copy va_copy(ap2, ap); // NOTE: This only works since glibc 2.0.6! int size = vsnprintf(mPtr, remaining, fmt, ap); va_end(ap); // size returned excludes trailing \0 if (size++ > 0) { if ((size_t)size > remaining) { growBy(size - remaining); vsnprintf(mPtr, size, fmt, ap2); } mPtr += size - 1; // omit trailing \0 } va_end(ap2); } void SC_StringBuffer::appendf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vappendf(fmt, ap); va_end(ap); } void SC_StringBuffer::growBy(size_t request) { size_t oldSize = getSize(); size_t newCapacity = mCapacity + ((request + (size_t)kGrowAlign) & (size_t)~kGrowMask); // fprintf(stderr, "%s: mCapacity %u, request %u, newCapacity %u\n", // __PRETTY_FUNCTION__, mCapacity, request, newCapacity); assert((newCapacity >= (mCapacity + request)) && ((newCapacity & kGrowMask) == 0)); char* newData = (char*)realloc(mData, newCapacity); if (newData) { mData = newData; mCapacity = newCapacity; mPtr = mData + oldSize; } else throw std::runtime_error(std::string("SC_StringBuffer: memory allocation failure")); } // EOF
3,230
C++
.cpp
86
33.534884
110
0.666773
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
29,901
scsynth_main.cpp
supercollider_supercollider/server/scsynth/scsynth_main.cpp
/* 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_WorldOptions.h" #include "SC_Version.hpp" #include "SC_EventLoop.hpp" #include "SC_ServerBootDelayWarning.h" #include <cstring> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <math.h> #include "clz.h" #include <stdexcept> #ifdef _WIN32 # include <winsock2.h> # include <vector> #else # include <unistd.h> // for _POSIX_MEMLOCK # include <sys/wait.h> #endif #ifdef __COBALT__ # include "XenomaiLock.h" static XenomaiInitializer xenomaiInitializer; #endif // __COBALT__ #ifdef _WIN32 // according to this page: http://www.mkssoftware.com/docs/man3/setlinebuf.3.asp // setlinebuf is equivalent to the setvbuf call below. inline int setlinebuf(FILE* stream) { return setvbuf(stream, (char*)0, _IONBF, 0); } #endif void Usage(); void Usage() { WorldOptions defaultOptions; scprintf("supercollider_synth options:\n" " -v print the supercollider version and exit\n" " -u <udp-port-number> a port number 1-65535. Set to 0 to bind a free port.\n" " -t <tcp-port-number> a port number 1-65535. Set to 0 to bind a free port.\n" " -B <bind-to-address>\n" " Bind the UDP or TCP socket to this address.\n" " Default 127.0.0.1. Set to 0.0.0.0 to listen on all interfaces.\n" " -c <number-of-control-bus-channels> (default %d)\n" " -a <number-of-audio-bus-channels> (default %d)\n" " -i <number-of-input-bus-channels> (default %d)\n" " -o <number-of-output-bus-channels> (default %d)\n" " -z <block-size> (default %d)\n" " -Z <hardware-buffer-size> (default %d)\n" " -S <hardware-sample-rate> (default %d)\n" " -b <number-of-sample-buffers> (default %d)\n" " -n <max-number-of-nodes> (default %d)\n" " -d <max-number-of-synth-defs> (default %d)\n" " -m <real-time-memory-size> (default %d)\n" " -w <number-of-wire-buffers> (default %d)\n" " -r <number-of-random-seeds> (default %d)\n" " -D <load synthdefs? 1 or 0> (default %d)\n" " -R <publish to Rendezvous? 1 or 0> (default %d)\n" " -l <max-logins> (default %d)\n" " maximum number of named return addresses stored\n" " also maximum number of tcp connections accepted\n" " -p <session-password>\n" " When using TCP, the session password must be the first command sent.\n" " The default is no password.\n" " UDP ports never require passwords, so for security use TCP.\n" " -N <cmd-filename> <input-filename> <output-filename> <sample-rate> <header-format> <sample-format>\n" #ifdef __APPLE__ " -s <safety-clip-threshold> (default %d)\n" " absolute amplitude value output signals will be clipped to.\n" " Set to <= 0 or inf to completely disable output clipping.\n" " -I <input-streams-enabled>\n" " -O <output-streams-enabled>\n" #endif #ifdef SC_BELA " -J <bela-analog-input-channels>\n" " -K <bela-analog-output-channels>\n" " -G <bela-digital-channels>\n" " -Q <bela-headphone-level> (0dB max, -63.5dB min)\n" " -X <bela-pga-gain-left>\n" " -Y <bela-pga-gain-right>\n" " -A <bela-speaker-mute>\n" " -x <bela-dac-level>\n" " -y <bela-adc-level>\n" " -g <bela-multiplexer-channels>\n" " -T <bela-pru-id>\n" " -E <bela-oscilloscope-max-channels>\n" #endif // SC_BELA #if (_POSIX_MEMLOCK - 0) >= 200112L " -L enable memory locking\n" #endif " -H <hardware-device-name>\n" " -V <verbosity>\n" " 0 is normal behaviour.\n" " -1 suppresses informational messages.\n" " -2 suppresses informational and many error messages, as well as\n" " messages from Poll.\n" " The default is 0.\n" #ifdef _WIN32 " -U <ugen-plugins-path>\n" " A list of paths separated by `;`.\n" #else " -U <ugen-plugins-path>\n" " A list of paths separated by `:`.\n" #endif " If specified, standard paths are NOT searched for plugins.\n" " -P <restricted-path> \n" " if specified, prevents file-accessing OSC commands from\n" " accessing files outside <restricted-path>.\n" "\nTo quit, send a 'quit' command via UDP or TCP, or press ctrl-C.\n\n", defaultOptions.mNumControlBusChannels, defaultOptions.mNumAudioBusChannels, defaultOptions.mNumInputBusChannels, defaultOptions.mNumOutputBusChannels, defaultOptions.mBufLength, defaultOptions.mPreferredHardwareBufferFrameSize, defaultOptions.mPreferredSampleRate, defaultOptions.mNumBuffers, defaultOptions.mMaxNodes, defaultOptions.mMaxGraphDefs, defaultOptions.mRealTimeMemorySize, defaultOptions.mMaxWireBufs, defaultOptions.mNumRGens, defaultOptions.mRendezvous, defaultOptions.mLoadGraphDefs, defaultOptions.mMaxLogins #ifdef __APPLE__ , defaultOptions.mSafetyClipThreshold #endif ); exit(1); } #define checkNumArgs(n) \ if (i + n > argc) { \ if (n == 2) \ scprintf("ERROR: Argument expected after option %s\n", argv[j]); \ else \ scprintf("ERROR: More arguments expected after option %s\n", argv[j]); \ Usage(); \ } \ i += n; int scsynth_main(int argc, char** argv) { startServerBootDelayWarningTimer(); setlinebuf(stdout); EventLoop::setup(); int udpPortNum = -1; int tcpPortNum = -1; std::string bindTo("127.0.0.1"); WorldOptions options; #ifdef SC_BELA // defaults options.mBelaAnalogInputChannels = 0; options.mBelaAnalogOutputChannels = 0; options.mBelaDigitalChannels = 0; options.mBelaHeadphoneLevel = -6.; options.mBelaPgaGainLeft = 20; options.mBelaPgaGainRight = 20; options.mBelaSpeakerMuted = 0; options.mBelaAdcLevel = 0; options.mBelaDacLevel = 0; options.mBelaNumMuxChannels = 0; options.mBelaPru = 1; options.mBelaMaxScopeChannels = 0; #endif // SC_BELA for (int i = 1; i < argc;) { #if defined(SC_BELA) # define SC_EXTRA_OPTIONS "JKGQXYAxygTE" #else // SC_BELA # define SC_EXTRA_OPTIONS "" #endif // SC_BELA if (argv[i][0] != '-' || argv[i][1] == 0 || strchr("utBaioczblndpmwZrCNSDIOsMHvVRUhPL" SC_EXTRA_OPTIONS, argv[i][1]) == nullptr) { scprintf("ERROR: Invalid option %s\n", argv[i]); Usage(); } int j = i; switch (argv[j][1]) { case 'u': checkNumArgs(2); udpPortNum = atoi(argv[j + 1]); break; case 't': checkNumArgs(2); tcpPortNum = atoi(argv[j + 1]); break; case 'B': checkNumArgs(2); bindTo = argv[j + 1]; break; case 'a': checkNumArgs(2); options.mNumAudioBusChannels = atoi(argv[j + 1]); break; case 'i': checkNumArgs(2); options.mNumInputBusChannels = atoi(argv[j + 1]); break; case 'o': checkNumArgs(2); options.mNumOutputBusChannels = atoi(argv[j + 1]); break; case 'c': checkNumArgs(2); options.mNumControlBusChannels = atoi(argv[j + 1]); break; case 'z': checkNumArgs(2); options.mBufLength = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'Z': checkNumArgs(2); options.mPreferredHardwareBufferFrameSize = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'b': checkNumArgs(2); options.mNumBuffers = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'l': checkNumArgs(2); options.mMaxLogins = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'n': checkNumArgs(2); options.mMaxNodes = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'd': checkNumArgs(2); options.mMaxGraphDefs = NEXTPOWEROFTWO(atoi(argv[j + 1])); break; case 'p': checkNumArgs(2); options.mPassword = argv[j + 1]; break; case 'm': checkNumArgs(2); options.mRealTimeMemorySize = atoi(argv[j + 1]); break; case 'w': checkNumArgs(2); options.mMaxWireBufs = atoi(argv[j + 1]); break; case 'r': checkNumArgs(2); options.mNumRGens = atoi(argv[j + 1]); break; case 'S': checkNumArgs(2); options.mPreferredSampleRate = (uint32)atof(argv[j + 1]); break; case 'D': checkNumArgs(2); options.mLoadGraphDefs = atoi(argv[j + 1]); break; case 'N': #ifdef NO_LIBSNDFILE scprintf("NRT mode not supported: scsynth compiled without libsndfile\n"); exit(0); #endif // -N cmd-filename input-filename output-filename sample-rate header-format sample-format checkNumArgs(7); options.mRealTime = false; options.mNonRealTimeCmdFilename = strcmp(argv[j + 1], "_") ? argv[j + 1] : nullptr; options.mNonRealTimeInputFilename = strcmp(argv[j + 2], "_") ? argv[j + 2] : nullptr; options.mNonRealTimeOutputFilename = argv[j + 3]; options.mPreferredSampleRate = (uint32)atof(argv[j + 4]); options.mNonRealTimeOutputHeaderFormat = argv[j + 5]; options.mNonRealTimeOutputSampleFormat = argv[j + 6]; break; #ifdef __APPLE__ case 'I': checkNumArgs(2); options.mInputStreamsEnabled = argv[j + 1]; break; case 'O': checkNumArgs(2); options.mOutputStreamsEnabled = argv[j + 1]; break; case 'M': #endif case 's': checkNumArgs(2); options.mSafetyClipThreshold = atof(argv[j + 1]); break; case 'H': checkNumArgs(2); options.mInDeviceName = argv[j + 1]; if (i + 1 > argc || argv[j + 2][0] == '-') { options.mOutDeviceName = options.mInDeviceName; } else { // If there's a second argument then the user wants separate I/O devices options.mOutDeviceName = argv[j + 2]; ++i; } break; case 'L': checkNumArgs(1); #if (_POSIX_MEMLOCK - 0) >= 200112L options.mMemoryLocking = true; #else options.mMemoryLocking = false; #endif break; #ifdef SC_BELA case 'J': checkNumArgs(2); options.mBelaAnalogInputChannels = atoi(argv[j + 1]); break; case 'K': checkNumArgs(2); options.mBelaAnalogOutputChannels = atoi(argv[j + 1]); break; case 'G': checkNumArgs(2); options.mBelaDigitalChannels = atoi(argv[j + 1]); break; case 'Q': checkNumArgs(2); options.mBelaHeadphoneLevel = atof(argv[j + 1]); break; case 'X': checkNumArgs(2); options.mBelaPgaGainLeft = atof(argv[j + 1]); break; case 'Y': checkNumArgs(2); options.mBelaPgaGainRight = atof(argv[j + 1]); break; case 'A': checkNumArgs(2); options.mBelaSpeakerMuted = atoi(argv[j + 1]) > 0; break; case 'x': checkNumArgs(2); options.mBelaDacLevel = atof(argv[j + 1]); break; case 'y': checkNumArgs(2); options.mBelaAdcLevel = atof(argv[j + 1]); break; case 'g': checkNumArgs(2); options.mBelaNumMuxChannels = atoi(argv[j + 1]); break; case 'T': checkNumArgs(2); options.mBelaPru = atoi(argv[j + 1]); break; case 'E': checkNumArgs(2); options.mBelaMaxScopeChannels = atoi(argv[j + 1]); break; #endif // SC_BELA case 'V': checkNumArgs(2); options.mVerbosity = atoi(argv[j + 1]); break; case 'v': scprintf("scsynth %s (%s)\n", SC_VersionString().c_str(), SC_BuildString().c_str()); exit(0); break; case 'R': checkNumArgs(2); options.mRendezvous = atoi(argv[j + 1]) > 0; break; case 'U': checkNumArgs(2); options.mUGensPluginPath = argv[j + 1]; break; case 'P': checkNumArgs(2); options.mRestrictedPath = argv[j + 1]; break; case 'C': checkNumArgs(2); break; case 'h': default: Usage(); } } if (udpPortNum == -1 && tcpPortNum == -1 && options.mRealTime) { scprintf("ERROR: There must be a -u and/or a -t options, or -N for nonrealtime.\n"); Usage(); } if (options.mNumInputBusChannels + options.mNumOutputBusChannels > options.mNumAudioBusChannels) { scprintf("ERROR: number of audio bus channels < inputs + outputs.\n"); Usage(); } if (options.mRealTime) { int port = (udpPortNum > 0) ? udpPortNum : tcpPortNum; options.mSharedMemoryID = port; } else options.mSharedMemoryID = 0; struct World* world = World_New(&options); if (!world) return 1; if (!options.mRealTime) { #ifdef NO_LIBSNDFILE return 1; #else int exitCode = 0; try { World_NonRealTimeSynthesis(world, &options); } catch (std::exception& exc) { scprintf("%s\n", exc.what()); exitCode = 1; } return exitCode; #endif } if (udpPortNum >= 0) { if (!World_OpenUDP(world, bindTo.c_str(), udpPortNum)) { World_Cleanup(world, true); return 1; } } if (tcpPortNum >= 0) { if (!World_OpenTCP(world, bindTo.c_str(), tcpPortNum, options.mMaxLogins, 8)) { World_Cleanup(world, true); return 1; } } stopServerBootDelayWarningTimer(); if (options.mVerbosity >= 0) { #ifdef NDEBUG scprintf("SuperCollider 3 server ready.\n"); #else scprintf("SuperCollider 3 server ready (debug build).\n"); #endif } fflush(stdout); EventLoop::run([world]() { World_WaitForQuit(world, true); }); return 0; } #ifdef _WIN32 int wmain(int argc, wchar_t** wargv) { // initialize winsock WSAData wsaData; int nCode; if ((nCode = WSAStartup(MAKEWORD(1, 1), &wsaData)) != 0) { scprintf("WSAStartup() failed with error code %d.\n", nCode); return 1; } // convert args to utf-8 std::vector<char*> argv; for (int i = 0; i < argc; i++) { auto argSize = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr); argv.push_back(new char[argSize]); WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], argSize, nullptr, nullptr); } // set codepage to UTF-8 and remember the old codepage auto oldCodePage = GetConsoleOutputCP(); if (!SetConsoleOutputCP(65001)) scprintf("WARNING: could not set codepage to UTF-8\n"); // run main int result = scsynth_main(argv.size(), argv.data()); // clean up winsock WSACleanup(); // reset codepage from UTF-8 SetConsoleOutputCP(oldCodePage); // clear vector with converted args for (auto* arg : argv) delete[] arg; return result; } #else int main(int argc, char** argv) { return scsynth_main(argc, argv); }; #endif //_WIN32
18,238
C++
.cpp
468
29.726496
120
0.532852
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
29,902
SC_PortAudio.cpp
supercollider_supercollider/server/scsynth/SC_PortAudio.cpp
/* 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 "SC_Time.hpp" #include <math.h> #include <stdlib.h> #include "SC_PaUtils.hpp" #include "portaudio.h" #define SC_PA_USE_DLL int32 server_timeseed() { return timeSeed(); } #ifdef SC_PA_USE_DLL # include "SC_TimeDLL.hpp" // ===================================================================== // Timing static inline int64 sc_PAOSCTime() { return OSCTime(getTime()); } static inline double sc_PAOSCTimeSeconds() { return (uint64)sc_PAOSCTime() * kOSCtoSecs; } int64 oscTimeNow() { return sc_PAOSCTime(); } void initializeScheduler() {} #else // SC_PA_USE_DLL int64 gOSCoffset = 0; static inline int64 GetCurrentOSCTime() { return OSCTime(getTime()); } int64 oscTimeNow() { return GetCurrentOSCTime(); } int64 PaStreamTimeToOSC(PaTime pa_time) { uint64 s, f; s = (uint64)pa_time; f = (uint64)((pa_time - s) * 1000000 * kMicrosToOSCunits); return (s << 32) + f; } void initializeScheduler() { gOSCoffset = GetCurrentOSCTime(); } #endif // SC_PA_USE_DLL class SC_PortAudioDriver : public SC_AudioDriver { int mInputChannelCount, mOutputChannelCount; PaStream* mStream; PaTime mPaStreamStartupTime; int64 mPaStreamStartupTimeOSC; #ifdef SC_PA_USE_DLL double mMaxOutputLatency; SC_TimeDLL mDLL; #endif protected: // Driver interface methods virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate); virtual bool DriverStart(); virtual bool DriverStop(); public: SC_PortAudioDriver(struct World* inWorld); virtual ~SC_PortAudioDriver(); int PortAudioCallback(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); }; SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld) { return new SC_PortAudioDriver(inWorld); } #define PRINT_PORTAUDIO_ERROR(function, errorcode) \ scprintf("SC_PortAudioDriver: PortAudio failed at %s with error: '%s'\n", #function, Pa_GetErrorText(errorcode)) SC_PortAudioDriver::SC_PortAudioDriver(struct World* inWorld): SC_AudioDriver(inWorld), mStream(0) #ifdef SC_PA_USE_DLL , mMaxOutputLatency(0.) #endif { PaError paerror = Pa_Initialize(); if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_Initialize, paerror); } SC_PortAudioDriver::~SC_PortAudioDriver() { if (mStream) { PaError paerror = Pa_CloseStream(mStream); if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_CloseStream, paerror); } Pa_Terminate(); } static int SC_PortAudioStreamCallback(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { SC_PortAudioDriver* driver = (SC_PortAudioDriver*)userData; return driver->PortAudioCallback(input, output, frameCount, timeInfo, statusFlags); } void sc_SetDenormalFlags(); int SC_PortAudioDriver::PortAudioCallback(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { sc_SetDenormalFlags(); World* world = mWorld; (void)frameCount, timeInfo, statusFlags; // suppress unused parameter warnings #ifdef SC_PA_USE_DLL mDLL.Update(sc_PAOSCTimeSeconds()); # if SC_PA_DEBUG_DLL static int tick = 0; if (++tick >= 10) { tick = 0; scprintf("DLL: t %.6f p %.9f sr %.6f e %.9f avg(e) %.9f inc %.9f\n", mDLL.PeriodTime(), mDLL.Period(), mDLL.SampleRate(), mDLL.Error(), mDLL.AvgError(), mOSCincrement * kOSCtoSecs); // scprintf("mOSCbuftime1 %llu \t %llu \t %f \n",GetCurrentOSCTime(),(uint64)((mDLL.PeriodTime() - // mMaxOutputLatency) * kSecondsToOSCunits + .5),((mDLL.PeriodTime() - mMaxOutputLatency) * kSecondsToOSCunits + // .5)); } # endif #endif try { #if !defined(SC_PA_USE_DLL) // synchronise against the output buffer - timeInfo->currentTime is 0.0 bug in PA? if (mPaStreamStartupTime == 0 && mPaStreamStartupTimeOSC == 0) { mPaStreamStartupTimeOSC = GetCurrentOSCTime(); mPaStreamStartupTime = timeInfo->outputBufferDacTime; } mOSCbuftime = PaStreamTimeToOSC(timeInfo->outputBufferDacTime - mPaStreamStartupTime) + mPaStreamStartupTimeOSC; #endif mFromEngine.Free(); mToEngine.Perform(); mOscPacketsToEngine.Perform(); const float** inBuffers = (const float**)input; float** outBuffers = (float**)output; int numSamples = NumSamplesPerCallback(); int bufFrames = mWorld->mBufLength; int numBufs = numSamples / bufFrames; float* inBuses = mWorld->mAudioBus + mWorld->mNumOutputs * bufFrames; float* outBuses = mWorld->mAudioBus; int32* inTouched = mWorld->mAudioBusTouched + mWorld->mNumOutputs; int32* outTouched = mWorld->mAudioBusTouched; int bufFramePos = 0; #ifdef SC_PA_USE_DLL int64 oscTime = mOSCbuftime = (uint64)((mDLL.PeriodTime() + mMaxOutputLatency) * kSecondsToOSCunits + .5); // int64 oscInc = mOSCincrement = (int64)(mOSCincrementNumerator / mDLL.SampleRate()); int64 oscInc = mOSCincrement = (uint64)((mDLL.Period() / numBufs) * kSecondsToOSCunits + .5); mSmoothSampleRate = mDLL.SampleRate(); double oscToSamples = mOSCtoSamples = mSmoothSampleRate * kOSCtoSecs /* 1/pow(2,32) */; #else int64 oscTime = mOSCbuftime; int64 oscInc = mOSCincrement; double oscToSamples = mOSCtoSamples; #endif // main loop for (int i = 0; i < numBufs; ++i, mWorld->mBufCounter++, bufFramePos += bufFrames) { int32 bufCounter = mWorld->mBufCounter; int32* tch; // copy+touch inputs tch = inTouched; for (int k = 0; k < mInputChannelCount; ++k) { const float* src = inBuffers[k] + bufFramePos; float* dst = inBuses + k * bufFrames; memcpy(dst, src, bufFrames * sizeof(float)); *tch++ = bufCounter; } // run engine int64 schedTime; int64 nextTime = oscTime + oscInc; // DEBUG /* if (mScheduler.Ready(nextTime)) { double diff = (mScheduler.NextTime() - mOSCbuftime)*kOSCtoSecs; scprintf("rdy %.6f %.6f %.6f %.6f \n", (mScheduler.NextTime()-gStartupOSCTime) * kOSCtoSecs, (mOSCbuftime-gStartupOSCTime)*kOSCtoSecs, diff, (nextTime-gStartupOSCTime)*kOSCtoSecs); } */ while ((schedTime = mScheduler.NextTime()) <= nextTime) { float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5; float diffTimeFloor = floor(diffTime); world->mSampleOffset = (int)diffTimeFloor; world->mSubsampleOffset = diffTime - diffTimeFloor; if (world->mSampleOffset < 0) world->mSampleOffset = 0; else if (world->mSampleOffset >= world->mBufLength) world->mSampleOffset = world->mBufLength - 1; SC_ScheduledEvent event = mScheduler.Remove(); event.Perform(); } world->mSampleOffset = 0; world->mSubsampleOffset = 0.0f; World_Run(world); // copy touched outputs tch = outTouched; for (int k = 0; k < mOutputChannelCount; ++k) { float* dst = outBuffers[k] + bufFramePos; if (*tch++ == bufCounter) { const float* src = outBuses + k * bufFrames; memcpy(dst, src, bufFrames * sizeof(float)); } else { memset(dst, 0, bufFrames * sizeof(float)); } } // update buffer time oscTime = mOSCbuftime = nextTime; } } catch (std::exception& exc) { scprintf("SC_PortAudioDriver: exception in real time: %s\n", exc.what()); } catch (...) { scprintf("SC_PortAudioDriver: unknown exception in real time\n"); } double cpuUsage = Pa_GetStreamCpuLoad(mStream) * 100.0; mAvgCPU = mAvgCPU + 0.1 * (cpuUsage - mAvgCPU); if (cpuUsage > mPeakCPU || --mPeakCounter <= 0) { mPeakCPU = cpuUsage; mPeakCounter = mMaxPeakCounter; } mAudioSync.Signal(); return paContinue; } // ==================================================================== // // bool SC_PortAudioDriver::DriverSetup(int* outNumSamples, double* outSampleRate) { int mDeviceInOut[2]; PaError paerror; const PaDeviceInfo* pdi; const PaStreamInfo* psi; PaTime suggestedLatencyIn, suggestedLatencyOut; PaDeviceIndex numDevices = Pa_GetDeviceCount(); // print out all options: fprintf(stdout, "\nDevice options:\n"); for (int i = 0; i < numDevices; i++) { pdi = Pa_GetDeviceInfo(i); fprintf(stdout, " - %s (device #%d with %d ins %d outs)\n", GetPaDeviceName(i).c_str(), i, pdi->maxInputChannels, pdi->maxOutputChannels); } auto* inDeviceName = mWorld->hw->mInDeviceName; auto* outDeviceName = mWorld->hw->mOutDeviceName; mDeviceInOut[0] = GetPaDeviceFromName(inDeviceName, true); mDeviceInOut[1] = GetPaDeviceFromName(outDeviceName, false); // report requested devices fprintf(stdout, "\nRequested devices:\n"); if (mWorld->mNumInputs) { auto nameIsEmpty = (inDeviceName && !inDeviceName[0]) || (inDeviceName == nullptr); fprintf(stdout, " In%s:\n - %s\n", nameIsEmpty ? "" : (mDeviceInOut[0] == paNoDevice ? " (matching device NOT found)" : " (matching device found)"), (nameIsEmpty ? "(default)" : inDeviceName)); } if (mWorld->mNumOutputs) { auto nameIsEmpty = (outDeviceName && !outDeviceName[0]) || (outDeviceName == nullptr); fprintf(stdout, " Out%s:\n - %s\n", nameIsEmpty ? "" : (mDeviceInOut[1] == paNoDevice ? " (matching device NOT found)" : " (matching device found)"), (nameIsEmpty ? "(default)" : outDeviceName)); } fprintf(stdout, "\n"); paerror = TryGetDefaultPaDevices(&mDeviceInOut[0], &mDeviceInOut[1], mWorld->mNumInputs, mWorld->mNumOutputs, mPreferredSampleRate); // if we got an error from TryGetDefaultPaDevices, stop here if (paerror != paNoError) { PRINT_PORTAUDIO_ERROR(Pa_OpenStream, paerror); return false; } *outNumSamples = mWorld->mBufLength; if (mPreferredSampleRate) *outSampleRate = mPreferredSampleRate; else if (mDeviceInOut[1] != paNoDevice) *outSampleRate = Pa_GetDeviceInfo(mDeviceInOut[1])->defaultSampleRate; else if (mDeviceInOut[0] != paNoDevice) *outSampleRate = Pa_GetDeviceInfo(mDeviceInOut[0])->defaultSampleRate; else *outSampleRate = 44100.; if (mDeviceInOut[0] != paNoDevice || mDeviceInOut[1] != paNoDevice) { if (mPreferredHardwareBufferFrameSize) // controls the suggested latency by hardwareBufferSize switch -Z suggestedLatencyIn = suggestedLatencyOut = mPreferredHardwareBufferFrameSize / (*outSampleRate); else { if (mDeviceInOut[0] != paNoDevice) suggestedLatencyIn = Pa_GetDeviceInfo(mDeviceInOut[0])->defaultLowInputLatency; if (mDeviceInOut[1] != paNoDevice) suggestedLatencyOut = Pa_GetDeviceInfo(mDeviceInOut[1])->defaultLowOutputLatency; } fprintf(stdout, "\nBooting with:\n"); if (mDeviceInOut[0] != paNoDevice) { // avoid to allocate the 128 virtual channels reported by the portaudio library for ALSA "default" mInputChannelCount = std::min<size_t>(mWorld->mNumInputs, Pa_GetDeviceInfo(mDeviceInOut[0])->maxInputChannels); fprintf(stdout, " In: %s\n", GetPaDeviceName(mDeviceInOut[0]).c_str()); } else { mInputChannelCount = 0; } if (mDeviceInOut[1] != paNoDevice) { // avoid to allocate the 128 virtual channels reported by the portaudio library for ALSA "default" mOutputChannelCount = std::min<size_t>(mWorld->mNumOutputs, Pa_GetDeviceInfo(mDeviceInOut[1])->maxOutputChannels); fprintf(stdout, " Out: %s\n", GetPaDeviceName(mDeviceInOut[1]).c_str()); } else { mOutputChannelCount = 0; } PaStreamParameters* inStreamParams_p; PaStreamParameters inStreamParams; if (mDeviceInOut[0] != paNoDevice) { inStreamParams = MakePaStreamParameters(mDeviceInOut[0], mInputChannelCount, suggestedLatencyIn); inStreamParams_p = &inStreamParams; } else { inStreamParams_p = NULL; } PaStreamParameters* outStreamParams_p; PaStreamParameters outStreamParams; if (mDeviceInOut[1] != paNoDevice) { outStreamParams = MakePaStreamParameters(mDeviceInOut[1], mOutputChannelCount, suggestedLatencyOut); outStreamParams_p = &outStreamParams; } else { outStreamParams_p = NULL; } // check if format is supported // this sometimes gives a more accurate error information than Pa_OpenStream's error paerror = Pa_IsFormatSupported(inStreamParams_p, outStreamParams_p, *outSampleRate); if (paerror != paNoError) { PRINT_PORTAUDIO_ERROR(Pa_OpenStream, paerror); return false; } paerror = Pa_OpenStream(&mStream, inStreamParams_p, outStreamParams_p, *outSampleRate, *outNumSamples, paNoFlag, SC_PortAudioStreamCallback, this); if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_OpenStream, paerror); else { psi = Pa_GetStreamInfo(mStream); if (!psi) fprintf(stdout, " Could not obtain further info from portaudio stream\n"); else { fprintf(stdout, " Sample rate: %.3f\n", psi->sampleRate); fprintf(stdout, " Latency (in/out): %.3f / %.3f sec\n", psi->inputLatency, psi->outputLatency); #ifdef SC_PA_USE_DLL mMaxOutputLatency = psi->outputLatency; #endif } } return paerror == paNoError; } // should not be necessary, but a last try with OpenDefaultStream... paerror = Pa_OpenDefaultStream(&mStream, mWorld->mNumInputs, mWorld->mNumOutputs, paFloat32 | paNonInterleaved, *outSampleRate, *outNumSamples, SC_PortAudioStreamCallback, this); mInputChannelCount = mWorld->mNumInputs; mOutputChannelCount = mWorld->mNumOutputs; if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_OpenDefaultStream, paerror); return paerror == paNoError; } bool SC_PortAudioDriver::DriverStart() { if (!mStream) return false; PaError paerror = Pa_StartStream(mStream); if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_StartStream, paerror); // sync times mPaStreamStartupTimeOSC = 0; mPaStreamStartupTime = 0; // it would be better to do the sync here, but the timeInfo in the callback is incomplete // mPaStreamStartupTimeOSC = GetCurrentOSCTime(); // mPaStreamStartupTime = Pa_GetStreamTime(mStream); #ifdef SC_PA_USE_DLL mDLL.Reset(mSampleRate, mNumSamplesPerCallback, SC_TIME_DLL_BW, sc_PAOSCTimeSeconds()); #endif return paerror == paNoError; } bool SC_PortAudioDriver::DriverStop() { if (!mStream) return false; PaError paerror = Pa_StopStream(mStream); if (paerror != paNoError) PRINT_PORTAUDIO_ERROR(Pa_StopStream, paerror); return paerror == paNoError; }
17,147
C++
.cpp
372
37.586022
120
0.637278
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
29,903
SC_Rate.cpp
supercollider_supercollider/server/scsynth/SC_Rate.cpp
/* 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_Rate.h" #include "SC_Constants.h" #include "SC_Prototypes.h" void Rate_Init(Rate* inRate, double inSampleRate, int inBufLength) { inRate->mSampleRate = inSampleRate; inRate->mSampleDur = 1. / inRate->mSampleRate; inRate->mRadiansPerSample = twopi / inRate->mSampleRate; inRate->mBufLength = inBufLength; inRate->mBufDuration = inRate->mBufLength / inRate->mSampleRate; inRate->mBufRate = 1. / inRate->mBufDuration; inRate->mSlopeFactor = 1. / inRate->mBufLength; inRate->mFilterLoops = inRate->mBufLength / 3; inRate->mFilterRemain = inRate->mBufLength % 3; if (inRate->mFilterLoops == 0.) inRate->mFilterSlope = 0.; else inRate->mFilterSlope = 1. / inRate->mFilterLoops; }
1,624
C++
.cpp
34
43.147059
81
0.734049
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
29,904
SC_Str4.cpp
supercollider_supercollider/server/scsynth/SC_Str4.cpp
/* 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_Str4.h" void str4cpy(int32* dst, const char* src) { char* cdst0 = (char*)(dst); char* cdst = cdst0; while (*src) { *cdst++ = *src++; } int charlen = cdst - cdst0; int pad = 4 - (charlen & 3); for (int i = 0; i < pad; ++i) { *cdst++ = 0; } } void mem4cpy(int32* dst, const char* src, int charlen) { dst[str4len(charlen) - 1] = 0; char* cdst0 = (char*)(dst); char* cdst = cdst0; for (int i = 0; i < charlen; ++i) { *cdst++ = *src++; } }
1,401
C++
.cpp
37
33.108108
81
0.665438
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
29,905
SC_Lib_Cintf.cpp
supercollider_supercollider/server/scsynth/SC_Lib_Cintf.cpp
/* 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_Lib_Cintf.h" #include "SC_CoreAudio.h" #include "SC_UnitDef.h" #include "SC_BufGen.h" #include "SC_World.h" #include "SC_WorldOptions.h" #include "SC_StringParser.h" #include "SC_InterfaceTable.h" #include "SC_Filesystem.hpp" #include "ErrorMessage.hpp" // for apiVersionMismatch, apiVersionMissing #include <stdexcept> #include <iostream> #ifndef _MSC_VER # include <dirent.h> #endif // _MSC_VER #ifdef _WIN32 # include "SC_Win32Utils.h" # include "SC_Codecvt.hpp" #else # include <dlfcn.h> # include <libgen.h> # include <sys/param.h> #endif // _WIN32 #include <filesystem> #ifdef __APPLE__ extern "C" { # include <mach-o/dyld.h> # include <mach-o/getsect.h> } char gTempVal; #endif // __APPLE__ namespace fs = std::filesystem; Malloc gMalloc; HashTable<SC_LibCmd, Malloc>* gCmdLib; HashTable<struct UnitDef, Malloc>* gUnitDefLib = nullptr; HashTable<struct BufGen, Malloc>* gBufGenLib = nullptr; HashTable<struct PlugInCmd, Malloc>* gPlugInCmds = nullptr; extern struct InterfaceTable gInterfaceTable; SC_LibCmd* gCmdArray[NUMBER_OF_COMMANDS]; void initMiscCommands(); static bool PlugIn_LoadDir(const fs::path& dir, bool reportError); std::vector<void*> open_handles; #ifdef __APPLE__ void read_section(const struct mach_header* mhp, unsigned long slide, const char* segname, const char* sectname) { u_int32_t size; char* sect = getsectdatafromheader(mhp, segname, sectname, &size); if (!sect) return; char* start = sect + slide; char* end = start + size; while (start != end) { gTempVal += *(char*)start; start++; } } #endif #ifdef STATIC_PLUGINS extern void IO_Load(InterfaceTable* table); extern void Osc_Load(InterfaceTable* table); extern void Delay_Load(InterfaceTable* table); extern void BinaryOp_Load(InterfaceTable* table); extern void Filter_Load(InterfaceTable* table); extern void Gendyn_Load(InterfaceTable* table); extern void LF_Load(InterfaceTable* table); extern void Noise_Load(InterfaceTable* table); extern void MulAdd_Load(InterfaceTable* table); extern void Grain_Load(InterfaceTable* table); extern void Pan_Load(InterfaceTable* table); extern void Reverb_Load(InterfaceTable* table); extern void Trigger_Load(InterfaceTable* table); extern void UnaryOp_Load(InterfaceTable* table); extern void DiskIO_Load(InterfaceTable* table); extern void Test_Load(InterfaceTable* table); extern void PhysicalModeling_Load(InterfaceTable* table); extern void Demand_Load(InterfaceTable* table); extern void DynNoise_Load(InterfaceTable* table); extern void FFT_UGens_Load(InterfaceTable* table); extern void iPhone_Load(InterfaceTable* table); extern void DiskIO_Unload(void); extern void UIUGens_Unload(void); #endif // STATIC_PLUGINS void deinitialize_library() { #ifdef STATIC_PLUGINS DiskIO_Unload(); UIUGens_Unload(); #endif // STATIC_PLUGINS #ifdef _WIN32 for (void* ptrhinstance : open_handles) { HINSTANCE hinstance = (HINSTANCE)ptrhinstance; void* ptr = (void*)GetProcAddress(hinstance, "unload"); if (ptr) { UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr; (*unloadFunc)(); } FreeLibrary(hinstance); } #else for (void* handle : open_handles) { void* ptr = dlsym(handle, "unload"); if (ptr) { UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr; (*unloadFunc)(); } dlclose(handle); } #endif open_handles.clear(); } void initialize_library(const char* uGensPluginPath) { gCmdLib = new HashTable<SC_LibCmd, Malloc>(&gMalloc, 64, true); gUnitDefLib = new HashTable<UnitDef, Malloc>(&gMalloc, 512, true); gBufGenLib = new HashTable<BufGen, Malloc>(&gMalloc, 512, true); gPlugInCmds = new HashTable<PlugInCmd, Malloc>(&gMalloc, 64, true); initMiscCommands(); #ifdef STATIC_PLUGINS IO_Load(&gInterfaceTable); Osc_Load(&gInterfaceTable); Delay_Load(&gInterfaceTable); BinaryOp_Load(&gInterfaceTable); Filter_Load(&gInterfaceTable); Gendyn_Load(&gInterfaceTable); LF_Load(&gInterfaceTable); Noise_Load(&gInterfaceTable); MulAdd_Load(&gInterfaceTable); Grain_Load(&gInterfaceTable); Pan_Load(&gInterfaceTable); Reverb_Load(&gInterfaceTable); Trigger_Load(&gInterfaceTable); UnaryOp_Load(&gInterfaceTable); DiskIO_Load(&gInterfaceTable); PhysicalModeling_Load(&gInterfaceTable); Test_Load(&gInterfaceTable); Demand_Load(&gInterfaceTable); DynNoise_Load(&gInterfaceTable); # if defined(SC_IPHONE) && !TARGET_IPHONE_SIMULATOR iPhone_Load(&gInterfaceTable); # endif FFT_UGens_Load(&gInterfaceTable); return; #endif // STATIC_PLUGINS // If uGensPluginPath is supplied, it is exclusive. bool loadUGensExtDirs = true; if (uGensPluginPath) { loadUGensExtDirs = false; SC_StringParser sp(uGensPluginPath, SC_STRPARSE_PATHDELIMITER); while (!sp.AtEnd()) { PlugIn_LoadDir(const_cast<char*>(sp.NextToken()), true); } } using DirName = SC_Filesystem::DirName; if (loadUGensExtDirs) { #ifdef SC_PLUGIN_DIR // load globally installed plugins if (fs::is_directory(SC_PLUGIN_DIR)) { PlugIn_LoadDir(SC_PLUGIN_DIR, true); } #endif // SC_PLUGIN_DIR // load default plugin directory const fs::path pluginDir = SC_Filesystem::instance().getDirectory(DirName::Resource) / SC_PLUGIN_DIR_NAME; if (fs::is_directory(pluginDir)) { PlugIn_LoadDir(pluginDir, true); } } // get extension directories if (loadUGensExtDirs) { // load system extension plugins const fs::path sysExtDir = SC_Filesystem::instance().getDirectory(DirName::SystemExtension); PlugIn_LoadDir(sysExtDir, false); // load user extension plugins const fs::path userExtDir = SC_Filesystem::instance().getDirectory(DirName::UserExtension); PlugIn_LoadDir(userExtDir, false); // load user plugin directories SC_StringParser sp(getenv("SC_PLUGIN_PATH"), SC_STRPARSE_PATHDELIMITER); while (!sp.AtEnd()) { PlugIn_LoadDir(sp.NextToken(), true); } } #ifdef __APPLE__ /* on darwin plugins are lazily loaded (dlopen uses mmap internally), which can produce audible glitches when UGens have to be paged-in. to work around this we preload all the plugins by iterating through their memory space. */ # ifndef __x86_64__ /* seems to cause a stack corruption on llvm-gcc-4.2, sdk 10.5 on 10.6 */ unsigned long images = _dyld_image_count(); for (unsigned long i = 0; i < images; i++) { const mach_header* hdr = _dyld_get_image_header(i); unsigned long slide = _dyld_get_image_vmaddr_slide(i); const char* name = _dyld_get_image_name(i); uint32_t size; char* sect; if (!strcmp(name + (strlen(name) - 4), ".scx")) { read_section(hdr, slide, "__TEXT", "__text"); read_section(hdr, slide, "__TEXT", "__const"); read_section(hdr, slide, "__TEXT", "__cstring"); read_section(hdr, slide, "__TEXT", "__picsymbol_stub"); read_section(hdr, slide, "__TEXT", "__symbol_stub"); read_section(hdr, slide, "__TEXT", "__const"); read_section(hdr, slide, "__TEXT", "__literal4"); read_section(hdr, slide, "__TEXT", "__literal8"); read_section(hdr, slide, "__DATA", "__data"); read_section(hdr, slide, "__DATA", "__la_symbol_ptr"); read_section(hdr, slide, "__DATA", "__nl_symbol_ptr"); read_section(hdr, slide, "__DATA", "__dyld"); read_section(hdr, slide, "__DATA", "__const"); read_section(hdr, slide, "__DATA", "__mod_init_func"); read_section(hdr, slide, "__DATA", "__bss"); read_section(hdr, slide, "__DATA", "__common"); read_section(hdr, slide, "__IMPORT", "__jump_table"); read_section(hdr, slide, "__IMPORT", "__pointers"); } } # endif // __x86_64__ #endif // ifdef __APPLE__ } typedef int (*InfoFunction)(); bool checkAPIVersion(void* f, const char* filename) { using namespace std; using namespace scsynth; if (f) { InfoFunction fn = (InfoFunction)f; int pluginVersion = (*fn)(); if (pluginVersion == sc_api_version) return true; else cout << ErrorMessage::apiVersionMismatch(filename, sc_api_version, pluginVersion) << endl; } else { cout << ErrorMessage::apiVersionNotFound(filename) << endl; } return false; } bool checkServerVersion(void* f, const char* filename) { if (f) { InfoFunction fn = (InfoFunction)f; if ((*fn)() == 1) return false; } return true; } static bool PlugIn_Load(const fs::path& filename) { #ifdef _WIN32 HINSTANCE hinstance = LoadLibraryW(filename.wstring().c_str()); // here, we have to use a utf-8 version of the string for printing // because the native encoding on Windows is utf-16. const std::string filename_utf8_str = SC_Codecvt::path_to_utf8_str(filename); if (!hinstance) { wchar_t* s; DWORD lastErr = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lastErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*)&s, 0, NULL); scprintf("*** ERROR: LoadLibrary '%s' err '%s'\n", filename_utf8_str.c_str(), SC_Codecvt::utf16_wcstr_to_utf8_string(s).c_str()); LocalFree(s); return false; } void* apiVersionPtr = (void*)GetProcAddress(hinstance, "api_version"); if (!checkAPIVersion(apiVersionPtr, filename_utf8_str.c_str())) { FreeLibrary(hinstance); return false; } void* serverCheckPtr = (void*)GetProcAddress(hinstance, "server_type"); if (!checkServerVersion(serverCheckPtr, filename_utf8_str.c_str())) { FreeLibrary(hinstance); return false; } void* ptr = (void*)GetProcAddress(hinstance, "load"); if (!ptr) { wchar_t* s; FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*)&s, 0, NULL); scprintf("*** ERROR: GetProcAddress err '%s'\n", SC_Codecvt::utf16_wcstr_to_utf8_string(s).c_str()); LocalFree(s); FreeLibrary(hinstance); return false; } LoadPlugInFunc loadFunc = (LoadPlugInFunc)ptr; (*loadFunc)(&gInterfaceTable); // FIXME: at the moment we never call FreeLibrary() on a loaded plugin open_handles.push_back(hinstance); return true; #else // (ifndef _WIN32) void* handle = dlopen(filename.c_str(), RTLD_NOW); if (!handle) { scprintf("*** ERROR: dlopen '%s' err '%s'\n", filename.c_str(), dlerror()); dlclose(handle); return false; } void* apiVersionPtr = (void*)dlsym(handle, "api_version"); if (!checkAPIVersion(apiVersionPtr, filename.c_str())) { dlclose(handle); return false; } void* serverCheckPtr = (void*)dlsym(handle, "server_type"); if (!checkServerVersion(serverCheckPtr, filename.c_str())) { dlclose(handle); return false; } void* ptr = dlsym(handle, "load"); if (!ptr) { scprintf("*** ERROR: dlsym load err '%s'\n", dlerror()); dlclose(handle); return false; } LoadPlugInFunc loadFunc = (LoadPlugInFunc)ptr; (*loadFunc)(&gInterfaceTable); open_handles.push_back(handle); return true; #endif // _WIN32 } static bool PlugIn_LoadDir(const fs::path& dir, bool reportError) { std::error_code ec; fs::recursive_directory_iterator rditer(dir, fs::directory_options::follow_directory_symlink, ec); if (ec) { if (reportError) { scprintf("*** ERROR: open directory failed '%s': %s\n", SC_Codecvt::path_to_utf8_str(dir).c_str(), ec.message().c_str()); fflush(stdout); } return false; } while (rditer != fs::end(rditer)) { const fs::path path = *rditer; if (fs::is_directory(path)) { if (SC_Filesystem::instance().shouldNotCompileDirectory(path)) rditer.disable_recursion_pending(); else ; // do nothing; recursion for free } else if (path.extension() == SC_PLUGIN_EXT) { // don't need to check result: PlugIn_Load does its own error handling and printing. // A `false` return value here just means that loading didn't occur, which is not // an error condition for us. PlugIn_Load(path); } else { // not a plugin, do nothing } rditer.increment(ec); if (ec) { scprintf("*** ERROR: Could not iterate on directory '%s': %s\n", SC_Codecvt::path_to_utf8_str(path).c_str(), ec.message().c_str()); return false; } } return true; }
14,131
C++
.cpp
359
33.203343
120
0.654172
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
29,906
SC_Jack.cpp
supercollider_supercollider/server/scsynth/SC_Jack.cpp
/* Jack audio driver interface. Copyright (c) 2003-2006 stefan kersten. ==================================================================== 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 "SC_HiddenWorld.h" #include "SC_Prototypes.h" #include "SC_StringParser.h" #include "SC_WorldOptions.h" #include "SC_TimeDLL.hpp" #include "SC_Time.hpp" #include <jack/jack.h> #ifdef SC_JACK_USE_METADATA_API # include <jack/metadata.h> # include <jack/uuid.h> # include <jackey.h> #endif #include <math.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> // ===================================================================== // Constants static const char* kJackDriverIdent = "JackDriver"; static const char* kJackDefaultClientName = "SuperCollider"; int32 server_timeseed() { return timeSeed(); } int64 oscTimeNow() { return OSCTime(getTime()); } static double jackOscTimeSeconds() { return OSCTime(getTime()) * kOSCtoSecs; } void initializeScheduler() {} // ===================================================================== // Audio driver static int sc_jack_process_cb(jack_nframes_t numFrames, void* arg); static int sc_jack_bufsize_cb(jack_nframes_t numSamples, void* arg); static int sc_jack_srate_cb(jack_nframes_t sampleRate, void* arg); static int sc_jack_graph_order_cb(void* arg); static void sc_jack_shutdown_cb(void* arg); typedef jack_default_audio_sample_t sc_jack_sample_t; struct SC_JackPortList { int mSize; jack_port_t** mPorts; sc_jack_sample_t** mBuffers; SC_JackPortList(jack_client_t* client, int orderOffset, int numPorts, int type); ~SC_JackPortList(); }; class SC_JackDriver : public SC_AudioDriver { jack_client_t* mClient; SC_JackPortList* mInputList; SC_JackPortList* mOutputList; double mMaxOutputLatency; SC_TimeDLL mDLL; protected: // driver interface methods virtual bool DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate); virtual bool DriverStart(); virtual bool DriverStop(); public: SC_JackDriver(struct World* inWorld); virtual ~SC_JackDriver(); // process loop void Run(); // reset state void Reset(double sampleRate, int bufferSize); // notifications bool BufferSizeChanged(int numSamples); bool SampleRateChanged(double sampleRate); bool GraphOrderChanged(); bool XRun(); private: void ConnectPorts(const char* src, const char* dst) { int err = jack_connect(mClient, src, dst); scprintf("%s: %s %s to %s\n", kJackDriverIdent, err ? "couldn't connect " : "connected ", src, dst); } void ConnectClientInputs(const char* pattern); void ConnectClientOutputs(const char* pattern); }; SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld) { return new SC_JackDriver(inWorld); } // ===================================================================== // SC_JackPortList SC_JackPortList::SC_JackPortList(jack_client_t* client, int orderOffset, int numPorts, int type): mSize(numPorts), mPorts(nullptr), mBuffers(nullptr) { const char* fmt = (type == JackPortIsInput ? "in_%d" : "out_%d"); #ifdef SC_JACK_USE_METADATA_API const char* prettyFmt = (type == JackPortIsInput ? "Input %d" : "Output %d"); #endif char tempStr[32]; mPorts = new jack_port_t*[mSize]; mBuffers = new float*[mSize]; for (int i = 0; i < mSize; i++) { snprintf(tempStr, 32, fmt, i + 1); mPorts[i] = jack_port_register(client, tempStr, JACK_DEFAULT_AUDIO_TYPE, type, 0); mBuffers[i] = nullptr; #ifdef SC_JACK_USE_METADATA_API jack_uuid_t uuid = jack_port_uuid(mPorts[i]); if (!jack_uuid_empty(uuid)) { snprintf(tempStr, 32, prettyFmt, i + 1); jack_set_property(client, uuid, JACK_METADATA_PRETTY_NAME, tempStr, "text/plain"); snprintf(tempStr, 32, "%d", orderOffset + i); jack_set_property(client, uuid, JACKEY_ORDER, tempStr, "http://www.w3.org/2001/XMLSchema#integer"); } #endif } } SC_JackPortList::~SC_JackPortList() { delete[] mPorts; delete[] mBuffers; } // ===================================================================== // JACK callbacks int sc_jack_process_cb(jack_nframes_t numFrames, void* arg) { ((SC_JackDriver*)arg)->Run(); return 0; } int sc_jack_bufsize_cb(jack_nframes_t numSamples, void* arg) { return !((SC_JackDriver*)arg)->BufferSizeChanged((int)numSamples); } int sc_jack_srate_cb(jack_nframes_t sampleRate, void* arg) { return !((SC_JackDriver*)arg)->SampleRateChanged((double)sampleRate); } int sc_jack_graph_order_cb(void* arg) { return !((SC_JackDriver*)arg)->GraphOrderChanged(); } int sc_jack_xrun_cb(void* arg) { return !((SC_JackDriver*)arg)->XRun(); } void sc_jack_shutdown_cb(void* arg) { scprintf("%s: killed by jack\n", kJackDriverIdent); World* world = (World*)arg; world->hw->mTerminating = true; world->hw->mQuitProgram->post(); } // ===================================================================== // SC_JackDriver (JACK) SC_JackDriver::SC_JackDriver(struct World* inWorld): SC_AudioDriver(inWorld), mClient(nullptr), mInputList(nullptr), mOutputList(nullptr), mMaxOutputLatency(0.) {} SC_JackDriver::~SC_JackDriver() { if (mClient) { jack_client_close(mClient); } delete mInputList; delete mOutputList; } // ==================================================================== // NOTE: for now, in lieu of a mechanism that passes generic options to // the platform driver, we rely on environment variables: // // SC_JACK_DEFAULT_INPUTS: which outports to connect to // SC_JACK_DEFAULT_OUTPUTS: which inports to connect to // ==================================================================== bool SC_JackDriver::DriverSetup(int* outNumSamples, double* outSampleRate) { char* clientName = nullptr; char* serverName = nullptr; if (mWorld->hw->mInDeviceName && (strlen(mWorld->hw->mInDeviceName) > 0)) { // parse string <serverName>:<clientName> SC_StringParser sp(mWorld->hw->mInDeviceName, ':'); if (!sp.AtEnd()) serverName = strdup(sp.NextToken()); if (!sp.AtEnd()) clientName = strdup(sp.NextToken()); if (clientName == nullptr) { // no semicolon found clientName = serverName; serverName = nullptr; } else if (strlen(clientName) == 0) { free(clientName); clientName = nullptr; } } mClient = jack_client_open(clientName ? clientName : kJackDefaultClientName, serverName ? JackServerName : JackNullOption, nullptr, serverName); if (serverName) free(serverName); if (clientName) free(clientName); if (mClient == nullptr) return false; scprintf("%s: client name is '%s'\n", kJackDriverIdent, jack_get_client_name(mClient)); // create jack I/O ports mInputList = new SC_JackPortList(mClient, 0, mWorld->mNumInputs, JackPortIsInput); mOutputList = new SC_JackPortList(mClient, mWorld->mNumInputs, mWorld->mNumOutputs, JackPortIsOutput); // register callbacks jack_set_process_callback(mClient, sc_jack_process_cb, this); jack_set_buffer_size_callback(mClient, sc_jack_bufsize_cb, this); jack_set_sample_rate_callback(mClient, sc_jack_srate_cb, this); jack_set_graph_order_callback(mClient, sc_jack_graph_order_cb, this); jack_set_xrun_callback(mClient, sc_jack_xrun_cb, this); jack_on_shutdown(mClient, sc_jack_shutdown_cb, mWorld); *outNumSamples = (int)jack_get_buffer_size(mClient); *outSampleRate = (double)jack_get_sample_rate(mClient); return true; } void SC_JackDriver::ConnectClientInputs(const char* pattern) { const char** ports = jack_get_ports(mClient, pattern, nullptr, JackPortIsOutput); jack_port_t** ourports = mInputList->mPorts; if (!ports) return; int i = 0; while (ports[i]) { if (i == mInputList->mSize) break; const char* src = ports[i]; const char* dst = jack_port_name(ourports[i]); ConnectPorts(src, dst); ++i; } free(ports); } void SC_JackDriver::ConnectClientOutputs(const char* pattern) { const char** ports = jack_get_ports(mClient, pattern, nullptr, JackPortIsInput); jack_port_t** ourports = mOutputList->mPorts; if (!ports) return; int i = 0; while (ports[i]) { if (i == mOutputList->mSize) break; const char* src = jack_port_name(ourports[i]); const char* dst = ports[i]; ConnectPorts(src, dst); ++i; } free(ports); } bool SC_JackDriver::DriverStart() { if (!mClient) return false; int err; SC_StringParser sp; jack_port_t** ports; int numPorts; // activate client err = jack_activate(mClient); if (err) { scprintf("%s: couldn't activate jack client\n", kJackDriverIdent); return false; } // connect default inputs sp = SC_StringParser(getenv("SC_JACK_DEFAULT_INPUTS"), ','); ports = mInputList->mPorts; numPorts = mInputList->mSize; for (int i = 0; !sp.AtEnd() && (i < numPorts); i++) { const char* thatPortName = sp.NextToken(); if (i == 0 && sp.AtEnd() && (strchr(thatPortName, ':') == nullptr)) { ConnectClientInputs(thatPortName); break; } const char* thisPortName = jack_port_name(ports[i]); if (thisPortName && thatPortName) ConnectPorts(thatPortName, thisPortName); } // connect default outputs sp = SC_StringParser(getenv("SC_JACK_DEFAULT_OUTPUTS"), ','); ports = mOutputList->mPorts; numPorts = mOutputList->mSize; for (int i = 0; !sp.AtEnd() && (i < numPorts); i++) { const char* thatPortName = sp.NextToken(); if (i == 0 && sp.AtEnd() && (strchr(thatPortName, ':') == nullptr)) { ConnectClientOutputs(thatPortName); break; } const char* thisPortName = jack_port_name(ports[i]); if (thisPortName && thatPortName) ConnectPorts(thisPortName, thatPortName); } mDLL.Reset(mSampleRate, mNumSamplesPerCallback, SC_TIME_DLL_BW, jackOscTimeSeconds()); return true; } bool SC_JackDriver::DriverStop() { int err = 0; if (mClient) err = jack_deactivate(mClient); return err == 0; } void sc_SetDenormalFlags(); void SC_JackDriver::Run() { sc_SetDenormalFlags(); jack_client_t* client = mClient; World* world = mWorld; mDLL.Update(jackOscTimeSeconds()); #if SC_JACK_DEBUG_DLL static int tick = 0; if (++tick >= 10) { tick = 0; scprintf("DLL: t %.6f p %.9f sr %.6f e %.9f avg(e) %.9f inc %.9f\n", mDLL.PeriodTime(), mDLL.Period(), mDLL.SampleRate(), mDLL.Error(), mDLL.AvgError(), mOSCincrement * kOSCtoSecs); } #endif try { mFromEngine.Free(); mToEngine.Perform(); mOscPacketsToEngine.Perform(); int numInputs = mInputList->mSize; int numOutputs = mOutputList->mSize; jack_port_t** inPorts = mInputList->mPorts; jack_port_t** outPorts = mOutputList->mPorts; sc_jack_sample_t** inBuffers = mInputList->mBuffers; sc_jack_sample_t** outBuffers = mOutputList->mBuffers; int numSamples = NumSamplesPerCallback(); int bufFrames = mWorld->mBufLength; int numBufs = numSamples / bufFrames; float* inBuses = mWorld->mAudioBus + mWorld->mNumOutputs * bufFrames; float* outBuses = mWorld->mAudioBus; int32* inTouched = mWorld->mAudioBusTouched + mWorld->mNumOutputs; int32* outTouched = mWorld->mAudioBusTouched; int minInputs = sc_min(numInputs, (int)mWorld->mNumInputs); int minOutputs = sc_min(numOutputs, (int)mWorld->mNumOutputs); int bufFramePos = 0; // cache I/O buffers for (int i = 0; i < minInputs; ++i) { inBuffers[i] = (sc_jack_sample_t*)jack_port_get_buffer(inPorts[i], numSamples); } for (int i = 0; i < minOutputs; ++i) { outBuffers[i] = (sc_jack_sample_t*)jack_port_get_buffer(outPorts[i], numSamples); } // main loop int64 oscTime = mOSCbuftime = (mDLL.PeriodTime() + mMaxOutputLatency) * kSecondsToOSCunits + .5; int64 oscInc = mOSCincrement = (mDLL.Period() / numBufs) * kSecondsToOSCunits + .5; mSmoothSampleRate = mDLL.SampleRate(); double oscToSamples = mOSCtoSamples = mSmoothSampleRate * kOSCtoSecs /* 1/pow(2,32) */; for (int i = 0; i < numBufs; ++i, mWorld->mBufCounter++, bufFramePos += bufFrames) { int32 bufCounter = mWorld->mBufCounter; int32* tch; // copy+touch inputs tch = inTouched; for (int k = 0; k < minInputs; ++k) { sc_jack_sample_t* src = inBuffers[k] + bufFramePos; float* dst = inBuses + k * bufFrames; for (int n = 0; n < bufFrames; ++n) { *dst++ = *src++; } *tch++ = bufCounter; } // run engine int64 schedTime; int64 nextTime = oscTime + oscInc; while ((schedTime = mScheduler.NextTime()) <= nextTime) { float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5; float diffTimeFloor = floor(diffTime); world->mSampleOffset = (int)diffTimeFloor; world->mSubsampleOffset = diffTime - diffTimeFloor; if (world->mSampleOffset < 0) world->mSampleOffset = 0; else if (world->mSampleOffset >= world->mBufLength) world->mSampleOffset = world->mBufLength - 1; SC_ScheduledEvent event = mScheduler.Remove(); event.Perform(); } world->mSampleOffset = 0; world->mSubsampleOffset = 0.f; World_Run(world); // copy touched outputs tch = outTouched; for (int k = 0; k < minOutputs; ++k) { sc_jack_sample_t* dst = outBuffers[k] + bufFramePos; if (*tch++ == bufCounter) { float* src = outBuses + k * bufFrames; for (int n = 0; n < bufFrames; ++n) { *dst++ = *src++; } } else { for (int n = 0; n < bufFrames; ++n) { *dst++ = 0.0f; } } } // advance OSC time mOSCbuftime = oscTime = nextTime; } } catch (std::exception& exc) { scprintf("%s: exception in real time: %s\n", kJackDriverIdent, exc.what()); } catch (...) { scprintf("%s: unknown exception in real time\n", kJackDriverIdent); } double cpuUsage = (double)jack_cpu_load(mClient); mAvgCPU = mAvgCPU + 0.1 * (cpuUsage - mAvgCPU); if (cpuUsage > mPeakCPU || --mPeakCounter <= 0) { mPeakCPU = cpuUsage; mPeakCounter = mMaxPeakCounter; } mAudioSync.Signal(); } void SC_JackDriver::Reset(double sampleRate, int bufferSize) { mSampleRate = mSmoothSampleRate = sampleRate; mNumSamplesPerCallback = bufferSize; World_SetSampleRate(mWorld, mSampleRate); mBuffersPerSecond = mSampleRate / mNumSamplesPerCallback; mMaxPeakCounter = (int)mBuffersPerSecond; mOSCincrement = (int64)(mOSCincrementNumerator / mSampleRate); mDLL.Reset(mSampleRate, mNumSamplesPerCallback, SC_TIME_DLL_BW, jackOscTimeSeconds()); } bool SC_JackDriver::BufferSizeChanged(int numSamples) { Reset(jack_get_sample_rate(mClient), numSamples); return true; } bool SC_JackDriver::SampleRateChanged(double sampleRate) { Reset(sampleRate, jack_get_buffer_size(mClient)); return true; } bool SC_JackDriver::GraphOrderChanged() { SC_JackPortList* outputs = mOutputList; jack_nframes_t lat = 0; for (int i = 0; i < outputs->mSize; ++i) { jack_latency_range_t range; jack_port_get_latency_range(outputs->mPorts[i], JackPlaybackLatency, &range); jack_nframes_t portLat = range.max; if (portLat > lat) lat = portLat; } double maxLat = (double)lat / mSampleRate; if (maxLat != mMaxOutputLatency) { mMaxOutputLatency = maxLat; scprintf("%s: max output latency %.1f ms\n", kJackDriverIdent, maxLat * 1e3); } return true; } bool SC_JackDriver::XRun() { Reset(mSampleRate, mNumSamplesPerCallback); return true; } // EOF
17,641
C++
.cpp
436
33.649083
111
0.619156
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
29,908
SC_Group.cpp
supercollider_supercollider/server/scsynth/SC_Group.cpp
/* 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_Group.h" #include "SC_GraphDef.h" #include "Hash.h" #include "sc_msg_iter.h" #include <string.h> #include <stdio.h> #include "SC_Prototypes.h" #include "SC_Str4.h" #include "SC_World.h" #include "SC_WorldOptions.h" #include "SC_Errors.h" #include "scsynthsend.h" NodeDef gGroupNodeDef; void Group_Dtor(Group* inGroup) { Group_DeleteAll(inGroup); inGroup->mNode.mWorld->mNumGroups--; Node_Dtor(&inGroup->mNode); } void GroupNodeDef_Init() { str4cpy(gGroupNodeDef.mName, "group"); gGroupNodeDef.mHash = Hash(gGroupNodeDef.mName); gGroupNodeDef.mAllocSize = sizeof(Group); } int Group_New(World* inWorld, int32 inID, Group** outGroup) { Group* group; int err = Node_New(inWorld, &gGroupNodeDef, inID, (Node**)&group); if (err) return err; group->mNode.mCalcFunc = (NodeCalcFunc)&Group_Calc; group->mNode.mIsGroup = true; group->mHead = nullptr; group->mTail = nullptr; inWorld->mNumGroups++; *outGroup = group; return kSCErr_None; } void Group_Calc(Group* inGroup) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; (*child->mCalcFunc)(child); child = next; } } void Group_CalcTrace(Group* inGroup) { scprintf("TRACE Group %d\n", inGroup->mNode.mID); Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; scprintf(" %d %s\n", child->mID, (char*)child->mDef->mName); (*child->mCalcFunc)(child); child = next; } inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_Calc; } void Group_Trace(Group* inGroup) { if (inGroup->mNode.mCalcFunc == (NodeCalcFunc)&Group_Calc) { inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_CalcTrace; } } void Group_DumpNodeTree(Group* inGroup) { static int tabCount = 0; if (tabCount == 0) scprintf("NODE TREE Group %d\n", inGroup->mNode.mID); tabCount++; Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; for (int i = 0; i < tabCount; i++) scprintf(" "); // small 'tabs' scprintf("%d %s\n", child->mID, (char*)child->mDef->mName); if (child->mIsGroup) { Group_DumpTree((Group*)child); } (*child->mCalcFunc)(child); child = next; } tabCount--; } void Group_DumpNodeTreeAndControls(Group* inGroup) { static int tabCount = 0; if (tabCount == 0) scprintf("NODE TREE Group %d\n", inGroup->mNode.mID); tabCount++; Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; int i; for (i = 0; i < tabCount; i++) scprintf(" "); // small 'tabs' scprintf("%d %s", child->mID, (char*)child->mDef->mName); // def will be 'group' if it's a group if (child->mIsGroup) { Group_DumpTreeAndControls((Group*)child); } else { Graph* childGraph = (Graph*)child; int numControls = childGraph->mNumControls; if (numControls > 0) { scprintf("\n "); for (i = 0; i < tabCount; i++) scprintf(" "); char** names; names = new char*[numControls]; for (i = 0; i < numControls; i++) { names[i] = nullptr; } // check the number of named controls and stash their names at the correct index GraphDef* def = (GraphDef*)(child->mDef); int numNamedControls = def->mNumParamSpecs; for (i = 0; i < numNamedControls; i++) { ParamSpec* paramSpec = def->mParamSpecs + i; names[paramSpec->mIndex] = (char*)paramSpec->mName; } // now print the names and values in index order, checking for mappings for (i = 0; i < numControls; i++) { float* ptr = childGraph->mControls + i; if (names[i]) { scprintf(" %s: ", names[i]); } else { scprintf(" ", names[i]); } // the ptr in nMapControls should be the same as the control itself, if not, it's mapped. if ((childGraph->mMapControls[i]) != ptr) { int bus; if (childGraph->mControlRates[i] == 2) { bus = (childGraph->mMapControls[i]) - (child->mWorld->mAudioBus); bus = (int)((float)bus / child->mWorld->mBufLength); scprintf("a%d", bus); } else { bus = (childGraph->mMapControls[i]) - (child->mWorld->mControlBus); scprintf("c%d", bus); } // scprintf("bus: %d\n", bus); } else { scprintf("%.14g", *ptr); } } delete[] names; } } scprintf("\n"); (*child->mCalcFunc)(child); child = next; } tabCount--; } void Group_CalcDumpTree(Group* inGroup) { Group_DumpNodeTree(inGroup); inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_Calc; } void Group_DumpTree(Group* inGroup) { if (inGroup->mNode.mCalcFunc == (NodeCalcFunc)&Group_Calc) { inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_CalcDumpTree; } } void Group_CalcDumpTreeAndControls(Group* inGroup) { Group_DumpNodeTreeAndControls(inGroup); inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_Calc; } void Group_DumpTreeAndControls(Group* inGroup) { if (inGroup->mNode.mCalcFunc == (NodeCalcFunc)&Group_Calc) { inGroup->mNode.mCalcFunc = (NodeCalcFunc)&Group_CalcDumpTreeAndControls; } } // count the children for this group (deep) void Group_CountNodeTags(Group* inGroup, int* count) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; (*count) += 2; if (child->mIsGroup) { Group_CountNodeTags((Group*)child, count); } else { (*count)++; } // for the defname child = next; } } // count the children for this group (deep) void Group_CountNodeAndControlTags(Group* inGroup, int* count, int* controlAndDefCount) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; (*count)++; if (child->mIsGroup) { Group_CountNodeAndControlTags((Group*)child, count, controlAndDefCount); } else { //(*controlCount) += ((Graph*)child)->mNumControls + ((GraphDef*)(child->mDef))->mNumParamSpecs + 1; (*controlAndDefCount) += ((Graph*)child)->mNumControls * 2 + 2; // def, numControls, name or index and value for each } child = next; } } void Group_QueryTree(Group* inGroup, big_scpacket* packet) { packet->addtag('i'); packet->addi(inGroup->mNode.mID); // count the children for this group, but not their children (shallow) int count = 0; Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; count++; child = next; } packet->addtag('i'); packet->addi(count); // numChildren; for a Group >= 0 // now iterate over the children // id, numChildren, defname child = inGroup->mHead; while (child) { Node* next = child->mNext; if (child->mIsGroup) { Group_QueryTree((Group*)child, packet); } else { packet->addtag('i'); // nodeID packet->addtag('i'); // numChildren packet->addtag('s'); // defname packet->addi(child->mID); packet->addi(-1); packet->adds((char*)child->mDef->mName); } child = next; } } void Group_QueryTreeAndControls(Group* inGroup, big_scpacket* packet) { packet->addtag('i'); packet->addi(inGroup->mNode.mID); // count the children for this group, but not their children (shallow) int count = 0; Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; count++; child = next; } packet->addtag('i'); packet->addi(count); // now iterate over the children // id, numChildren, defname child = inGroup->mHead; while (child) { Node* next = child->mNext; if (child->mIsGroup) { Group_QueryTreeAndControls((Group*)child, packet); } else { packet->addtag('i'); packet->addtag('i'); packet->addtag('s'); packet->addi(child->mID); // nodeID packet->addi(-1); // numChildren packet->adds((char*)child->mDef->mName); // defName Graph* childGraph = (Graph*)child; int numControls = childGraph->mNumControls; packet->addtag('i'); packet->addi(numControls); char** names; names = new char*[numControls]; int i; for (i = 0; i < numControls; i++) { names[i] = nullptr; } // check the number of named controls and stash their names GraphDef* def = (GraphDef*)(child->mDef); int numNamedControls = def->mNumParamSpecs; for (i = 0; i < numNamedControls; i++) { ParamSpec* paramSpec = def->mParamSpecs + i; names[paramSpec->mIndex] = (char*)paramSpec->mName; } // now add the names and values in index order, checking for mappings for (i = 0; i < numControls; i++) { float* ptr = childGraph->mControls + i; if (names[i]) { packet->addtag('s'); packet->adds(names[i]); } else { packet->addtag('i'); packet->addi(i); } // the ptr in nMapControls should be the same as the control itself, if not, it's mapped. if ((childGraph->mMapControls[i]) != ptr) { // it's mapped int bus; const size_t BUF_SIZE(10); char buf[BUF_SIZE]; if (childGraph->mControlRates[i] == 2) { bus = (childGraph->mMapControls[i]) - (child->mWorld->mAudioBus); bus = (int)((float)bus / child->mWorld->mBufLength); snprintf(buf, BUF_SIZE, "%c%d", 'a', bus); } else { bus = (childGraph->mMapControls[i]) - (child->mWorld->mControlBus); snprintf(buf, BUF_SIZE, "%c%d", 'c', bus); } // scprintf("bus: %d\n", bus); packet->addtag('s'); packet->adds(buf); } else { packet->addtag('f'); packet->addf(*ptr); } } delete[] names; } child = next; } } void Group_DeleteAll(Group* inGroup) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; child->mPrev = child->mNext = nullptr; child->mParent = nullptr; Node_Delete(child); child = next; } inGroup->mHead = inGroup->mTail = nullptr; } void Group_DeepFreeGraphs(Group* inGroup) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; if (child->mIsGroup) { Group_DeepFreeGraphs((Group*)child); } else { Node_Remove(child); Node_Delete(child); } child = next; } } void Group_AddHead(Group* s, Node* child) { if (child->mID == 0) return; // failed child->mPrev = nullptr; child->mNext = s->mHead; if (s->mHead) { s->mHead->mPrev = child; s->mHead = child; } else s->mHead = s->mTail = child; child->mParent = s; } void Group_AddTail(Group* s, Node* child) { if (child->mID == 0) return; // failed child->mPrev = s->mTail; child->mNext = nullptr; if (s->mTail) { s->mTail->mNext = child; s->mTail = child; } else s->mHead = s->mTail = child; child->mParent = s; } void Group_Insert(Group* s, Node* child, int index) { if (child->mID == 0) return; // failed if (index <= 0) Group_AddHead(s, child); else { Node* before = s->mHead; for (int i = 0; i < index; ++i) { before = before->mNext; if (!before) { Group_AddTail(s, child); return; } } Node_AddBefore(child, before); } } void Group_MapControl(Group* inGroup, uint32 inIndex, uint32 inBus) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_MapControl(child, inIndex, inBus); child = next; } } void Group_MapControl(Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_MapControl(child, inHash, inName, inIndex, inBus); child = next; } } void Group_MapAudioControl(Group* inGroup, uint32 inIndex, uint32 inBus) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_MapAudioControl(child, inIndex, inBus); child = next; } } void Group_MapAudioControl(Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_MapAudioControl(child, inHash, inName, inIndex, inBus); child = next; } } void Group_SetControl(Group* inGroup, uint32 inIndex, float inValue) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_SetControl(child, inIndex, inValue); child = next; } } void Group_SetControl(Group* inGroup, int32 inHash, int32* inName, uint32 inIndex, float inValue) { Node* child = inGroup->mHead; while (child) { Node* next = child->mNext; Node_SetControl(child, inHash, inName, inIndex, inValue); child = next; } }
15,405
C++
.cpp
434
26.458525
112
0.554796
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
29,909
SC_ComPort.cpp
supercollider_supercollider/server/scsynth/SC_ComPort.cpp
/* 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_Endian.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include "sc_msg_iter.h" #include "SC_OscUtils.hpp" #include <ctype.h> #include <stdexcept> #include <stdarg.h> #include <cerrno> #include <sys/types.h> #include "OSC_Packet.h" #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/bind/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/typeof/typeof.hpp> #include "SC_Lock.h" #include "nova-tt/semaphore.hpp" #include "nova-tt/thread_priority.hpp" #ifdef USE_RENDEZVOUS # include "Rendezvous.h" #endif bool ProcessOSCPacket(World* inWorld, OSC_Packet* inPacket); namespace scsynth { ////////////////////////////////////////////////////////////////////////////////////////////////////////// static bool UnrollOSCPacket(World* inWorld, int inSize, char* inData, OSC_Packet* inPacket) { if (!strcmp(inData, "#bundle")) { // is a bundle char* data; char* dataEnd = inData + inSize; int len = 16; bool hasNestedBundle = false; // get len of nested messages only, without len of nested bundle(s) data = inData + 16; // skip bundle header while (data < dataEnd) { int32 msgSize = OSCint(data); data += sizeof(int32); if (strcmp(data, "#bundle")) // is a message len += sizeof(int32) + msgSize; else hasNestedBundle = true; data += msgSize; } if (hasNestedBundle) { if (len > 16) { // not an empty bundle // add nested messages to bundle buffer char* buf = (char*)malloc(len); inPacket->mSize = len; inPacket->mData = buf; memcpy(buf, inData, 16); // copy bundle header data = inData + 16; // skip bundle header while (data < dataEnd) { int32 msgSize = OSCint(data); data += sizeof(int32); if (strcmp(data, "#bundle")) { // is a message memcpy(buf, data - sizeof(int32), sizeof(int32) + msgSize); buf += msgSize; } data += msgSize; } // process this packet without its nested bundle(s) if (!ProcessOSCPacket(inWorld, inPacket)) { free(buf); return false; } } // process nested bundle(s) data = inData + 16; // skip bundle header while (data < dataEnd) { int32 msgSize = OSCint(data); data += sizeof(int32); if (!strcmp(data, "#bundle")) { // is a bundle OSC_Packet* packet = (OSC_Packet*)malloc(sizeof(OSC_Packet)); memcpy(packet, inPacket, sizeof(OSC_Packet)); // clone inPacket if (!UnrollOSCPacket(inWorld, msgSize, data, packet)) { free(packet); return false; } } data += msgSize; } } else { // !hasNestedBundle char* buf = (char*)malloc(inSize); inPacket->mSize = inSize; inPacket->mData = buf; memcpy(buf, inData, inSize); if (!ProcessOSCPacket(inWorld, inPacket)) { free(buf); return false; } } } else { // is a message char* buf = (char*)malloc(inSize); inPacket->mSize = inSize; inPacket->mData = buf; memcpy(buf, inData, inSize); if (!ProcessOSCPacket(inWorld, inPacket)) { free(buf); return false; } } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// SC_Thread gAsioThread; boost::asio::io_service ioService; const int kTextBufSize = 65536; static void udp_reply_func(struct ReplyAddress* addr, char* msg, int size) { using namespace boost::asio; ip::udp::socket* socket = reinterpret_cast<ip::udp::socket*>(addr->mReplyData); ip::udp::endpoint endpoint(addr->mAddress, addr->mPort); boost::system::error_code errc; socket->send_to(buffer(msg, size), endpoint, 0, errc); if (errc) printf("%s\n", errc.message().c_str()); } static void tcp_reply_func(struct ReplyAddress* addr, char* msg, int size) { // Write size as 32bit unsigned network-order integer uint32 u = sc_htonl(size); using namespace boost::asio; // FIXME: connection could be destroyed! ip::tcp::socket* socket = reinterpret_cast<ip::tcp::socket*>(addr->mReplyData); #if 0 ip::tcp::socket::message_flags flags = 0; # ifdef MSG_NOSIGNAL flags = MSG_NOSIGNAL; # endif #endif boost::system::error_code errc; write(*socket, buffer(&u, sizeof(uint32)), errc); if (errc) printf("%s\n", errc.message().c_str()); write(*socket, buffer(msg, size), errc); if (errc) printf("%s\n", errc.message().c_str()); } class SC_UdpInPort { struct World* mWorld; int mPortNum; std::string mbindTo; boost::array<char, kTextBufSize> recvBuffer; boost::asio::ip::udp::endpoint remoteEndpoint; #ifdef USE_RENDEZVOUS SC_Thread mRendezvousThread; #endif void handleReceivedUDP(const boost::system::error_code& error, std::size_t bytes_transferred) { if (error == boost::asio::error::operation_aborted) return; /* we're done */ if (error == boost::asio::error::connection_refused) { // avoid windows error message startReceiveUDP(); return; } if (error) { printf("(scsynth) SC_UdpInPort: received error - %s\n", error.message().c_str()); startReceiveUDP(); return; } if (mWorld->mDumpOSC) dumpOSC(mWorld->mDumpOSC, bytes_transferred, recvBuffer.data()); OSC_Packet* packet = (OSC_Packet*)malloc(sizeof(OSC_Packet)); packet->mReplyAddr.mProtocol = kUDP; packet->mReplyAddr.mAddress = remoteEndpoint.address(); packet->mReplyAddr.mPort = remoteEndpoint.port(); packet->mReplyAddr.mSocket = udpSocket.native_handle(); packet->mReplyAddr.mReplyFunc = udp_reply_func; packet->mReplyAddr.mReplyData = (void*)&udpSocket; packet->mSize = bytes_transferred; if (!UnrollOSCPacket(mWorld, bytes_transferred, recvBuffer.data(), packet)) free(packet); startReceiveUDP(); } void startReceiveUDP() { using namespace boost; udpSocket.async_receive_from(asio::buffer(recvBuffer), remoteEndpoint, boost::bind(&SC_UdpInPort::handleReceivedUDP, this, asio::placeholders::error, asio::placeholders::bytes_transferred)); } public: boost::asio::ip::udp::socket udpSocket; SC_UdpInPort(struct World* world, std::string bindTo, int inPortNum): mWorld(world), mPortNum(inPortNum), mbindTo(bindTo), udpSocket(ioService) { using namespace boost::asio; BOOST_AUTO(protocol, ip::udp::v4()); udpSocket.open(protocol); udpSocket.bind(ip::udp::endpoint(boost::asio::ip::address::from_string(bindTo), inPortNum)); if (inPortNum == 0) mPortNum = udpSocket.local_endpoint().port(); boost::asio::socket_base::send_buffer_size option(65536); udpSocket.set_option(option); #ifdef USE_RENDEZVOUS if (world->mRendezvous) { SC_Thread thread(boost::bind(PublishPortToRendezvous, kSCRendezvous_UDP, mPortNum)); mRendezvousThread = std::move(thread); } #endif startReceiveUDP(); } }; class SC_TcpConnection : public boost::enable_shared_from_this<SC_TcpConnection> { public: struct World* mWorld; typedef boost::shared_ptr<SC_TcpConnection> pointer; boost::asio::ip::tcp::socket socket; SC_TcpConnection(struct World* world, boost::asio::io_service& ioService, class SC_TcpInPort* parent): mWorld(world), socket(ioService), mParent(parent) {} ~SC_TcpConnection(); void start() { const int kMaxPasswordLen = 32; char buf[kMaxPasswordLen]; int32 size; int32 msglen; boost::system::error_code error; boost::asio::ip::tcp::no_delay noDelayOption(true); socket.set_option(noDelayOption, error); // first message must be the password. 4 tries. bool validated = mWorld->hw->mPassword[0] == 0; for (int i = 0; !validated && i < 4; ++i) { // FIXME: error handling! size = boost::asio::read(socket, boost::asio::buffer((void*)&msglen, sizeof(int32))); if (size < 0) return; msglen = sc_ntohl(msglen); if (msglen > kMaxPasswordLen) break; size = boost::asio::read(socket, boost::asio::buffer((void*)buf, msglen)); if (size < 0) return; validated = strcmp(buf, mWorld->hw->mPassword) == 0; std::this_thread::sleep_for(std::chrono::seconds(i + 1)); // thwart cracking. } if (validated) startReceiveMessage(); } private: void startReceiveMessage() { namespace ba = boost::asio; async_read(socket, ba::buffer(&OSCMsgLength, sizeof(OSCMsgLength)), boost::bind(&SC_TcpConnection::handleLengthReceived, shared_from_this(), ba::placeholders::error, ba::placeholders::bytes_transferred)); } int32 OSCMsgLength; char* data; class SC_TcpInPort* mParent; void handleLengthReceived(const boost::system::error_code& error, size_t bytes_transferred) { if (error) { if (error == boost::asio::error::eof) return; // connection closed printf("handleLengthReceived: error %s", error.message().c_str()); return; } namespace ba = boost::asio; // msglen is in network byte order OSCMsgLength = sc_ntohl(OSCMsgLength); data = (char*)malloc(OSCMsgLength); async_read(socket, ba::buffer(data, OSCMsgLength), boost::bind(&SC_TcpConnection::handleMsgReceived, shared_from_this(), ba::placeholders::error, ba::placeholders::bytes_transferred)); } void handleMsgReceived(const boost::system::error_code& error, size_t bytes_transferred) { if (error) { free(data); if (error == boost::asio::error::eof) return; // connection closed printf("handleMsgReceived: error %s", error.message().c_str()); return; } assert(bytes_transferred == OSCMsgLength); if (mWorld->mDumpOSC) dumpOSC(mWorld->mDumpOSC, bytes_transferred, data); OSC_Packet* packet = (OSC_Packet*)malloc(sizeof(OSC_Packet)); packet->mReplyAddr.mProtocol = kTCP; packet->mReplyAddr.mReplyFunc = tcp_reply_func; packet->mReplyAddr.mReplyData = (void*)&socket; packet->mSize = OSCMsgLength; if (!UnrollOSCPacket(mWorld, bytes_transferred, data, packet)) free(packet); startReceiveMessage(); } }; class SC_TcpInPort { struct World* mWorld; boost::asio::ip::tcp::acceptor acceptor; #ifdef USE_RENDEZVOUS SC_Thread mRendezvousThread; #endif std::atomic<int> mAvailableConnections; friend class SC_TcpConnection; public: SC_TcpInPort(struct World* world, const std::string& bindTo, int inPortNum, int inMaxConnections, int inBacklog): mWorld(world), acceptor(ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(bindTo), inPortNum)), mAvailableConnections(inMaxConnections) { // FIXME: backlog??? #ifdef USE_RENDEZVOUS if (world->mRendezvous) { SC_Thread thread(boost::bind(PublishPortToRendezvous, kSCRendezvous_TCP, inPortNum == 0 ? acceptor.local_endpoint().port() : inPortNum)); mRendezvousThread = std::move(thread); } #endif startAccept(); } void startAccept() { if (mAvailableConnections > 0) { --mAvailableConnections; SC_TcpConnection::pointer newConnection(new SC_TcpConnection(mWorld, ioService, this)); acceptor.async_accept( newConnection->socket, boost::bind(&SC_TcpInPort::handleAccept, this, newConnection, boost::asio::placeholders::error)); } } void handleAccept(SC_TcpConnection::pointer newConnection, const boost::system::error_code& error) { if (!error) newConnection->start(); startAccept(); } void connectionDestroyed() { if (!mWorld->mRunning) return; mAvailableConnections += 1; startAccept(); } }; SC_TcpConnection::~SC_TcpConnection() { mParent->connectionDestroyed(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// static void asioFunction() { /* NB: on macOS we just keep the default thread priority */ #ifdef NOVA_TT_PRIORITY_RT int priority = nova::thread_priority_interval_rt().first; nova::thread_set_priority_rt(priority); #endif boost::asio::io_service::work work(ioService); ioService.run(); } void startAsioThread() { SC_Thread asioThread(&asioFunction); gAsioThread = std::move(asioThread); } void stopAsioThread() { ioService.stop(); gAsioThread.join(); } bool asioThreadStarted() { return gAsioThread.joinable(); } } using namespace scsynth; ////////////////////////////////////////////////////////////////////////////////////////////////////////// SCSYNTH_DLLEXPORT_C bool World_SendPacketWithContext(World* inWorld, int inSize, char* inData, ReplyFunc inFunc, void* inContext) { if (inSize > 0) { if (inWorld->mDumpOSC) dumpOSC(inWorld->mDumpOSC, inSize, inData); OSC_Packet* packet = (OSC_Packet*)malloc(sizeof(OSC_Packet)); packet->mReplyAddr.mAddress = boost::asio::ip::address(); packet->mReplyAddr.mReplyFunc = inFunc; packet->mReplyAddr.mReplyData = inContext; packet->mReplyAddr.mSocket = 0; if (!UnrollOSCPacket(inWorld, inSize, inData, packet)) { free(packet); return false; } } return true; } SCSYNTH_DLLEXPORT_C bool World_SendPacket(World* inWorld, int inSize, char* inData, ReplyFunc inFunc) { return World_SendPacketWithContext(inWorld, inSize, inData, inFunc, nullptr); } template <typename T, typename... Args> static bool protectedOpenPort(const char* socketType, Args&&... args) noexcept { try { new T(std::forward<Args>(args)...); return true; } catch (const boost::system::system_error& exc) { // Special verbose message to help with common issue. Issue #3969 if (exc.code() == boost::system::errc::address_in_use) { scprintf("\n*** ERROR: failed to open %s socket: address in use.\n" "This could be because another instance of scsynth is already using it.\n" "You can use SuperCollider (sclang) to kill all running servers by running `Server.killAll`.\n" "You can also kill scsynth using a terminal or your operating system's task manager.\n", socketType); } else { scprintf("\n*** ERROR: failed to open %s socket: %s\n", socketType, exc.what()); } } catch (const std::exception& exc) { scprintf("\n*** ERROR: failed to open %s socket: %s\n", socketType, exc.what()); } catch (...) { scprintf("\n*** ERROR: failed to open %s socket: Unknown error\n", socketType); } return false; } SCSYNTH_DLLEXPORT_C int World_OpenUDP(struct World* inWorld, const char* bindTo, int inPort) { return protectedOpenPort<SC_UdpInPort>("UDP", inWorld, bindTo, inPort); } SCSYNTH_DLLEXPORT_C int World_OpenTCP(struct World* inWorld, const char* bindTo, int inPort, int inMaxConnections, int inBacklog) { return protectedOpenPort<SC_TcpInPort>("TCP", inWorld, bindTo, inPort, inMaxConnections, inBacklog); } //////////////////////////////////////////////////////////////////////////////////////////////////////////
17,639
C++
.cpp
415
33.486747
120
0.593978
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
29,910
SC_Node.cpp
supercollider_supercollider/server/scsynth/SC_Node.cpp
/* 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_Group.h" #include "SC_SynthDef.h" #include "SC_World.h" #include "SC_WorldOptions.h" #include "SC_Errors.h" #include <stdio.h> #include <stdexcept> #include <limits.h> #include "SC_Prototypes.h" #include "SC_HiddenWorld.h" #include "Unroll.h" void Node_StateMsg(Node* inNode, int inState); // create a new node int Node_New(World* inWorld, NodeDef* def, int32 inID, Node** outNode) { if (inID < 0) { if (inID == -1) { // -1 means generate an id for the event HiddenWorld* hw = inWorld->hw; inID = hw->mHiddenID = (hw->mHiddenID - 8) | 0x80000000; } else { return kSCErr_ReservedNodeID; } } if (World_GetNode(inWorld, inID)) { return kSCErr_DuplicateNodeID; } Node* node = (Node*)World_Alloc(inWorld, def->mAllocSize); if (!node) { return kSCErr_OutOfRealTimeMemory; } node->mWorld = inWorld; node->mDef = def; node->mParent = nullptr; node->mPrev = nullptr; node->mNext = nullptr; node->mIsGroup = false; node->mID = inID; node->mHash = Hash(inID); if (!World_AddNode(inWorld, node)) { World_Free(inWorld, node); return kSCErr_TooManyNodes; } inWorld->hw->mRecentID = inID; *outNode = node; return kSCErr_None; } // node destructor void Node_Dtor(Node* inNode) { Node_StateMsg(inNode, kNode_End); Node_Remove(inNode); World* world = inNode->mWorld; world->hw->mNodeLib->Remove(inNode); World_Free(world, inNode); } // remove a node from a group void Node_Remove(Node* s) { Group* group = s->mParent; if (s->mPrev) s->mPrev->mNext = s->mNext; else if (group) group->mHead = s->mNext; if (s->mNext) s->mNext->mPrev = s->mPrev; else if (group) group->mTail = s->mPrev; s->mPrev = s->mNext = nullptr; s->mParent = nullptr; } void Node_RemoveID(Node* inNode) { if (inNode->mID == 0) return; // failed World* world = inNode->mWorld; if (!World_RemoveNode(world, inNode)) { int err = kSCErr_Failed; // shouldn't happen.. throw err; } HiddenWorld* hw = world->hw; int id = hw->mHiddenID = (hw->mHiddenID - 8) | 0x80000000; inNode->mID = id; inNode->mHash = Hash(id); if (!World_AddNode(world, inNode)) { scprintf("mysterious failure in Node_RemoveID\n"); Node_Delete(inNode); // enums are uncatchable. must throw an int. int err = kSCErr_Failed; // shouldn't happen.. throw err; } // inWorld->hw->mRecentID = id; } // delete a node void Node_Delete(Node* inNode) { if (inNode->mID == 0) return; // failed if (inNode->mIsGroup) Group_Dtor((Group*)inNode); else Graph_Dtor((Graph*)inNode); } // add a node after another one void Node_AddAfter(Node* s, Node* afterThisOne) { if (!afterThisOne->mParent || s->mID == 0) return; // failed s->mParent = afterThisOne->mParent; s->mPrev = afterThisOne; s->mNext = afterThisOne->mNext; if (afterThisOne->mNext) afterThisOne->mNext->mPrev = s; else s->mParent->mTail = s; afterThisOne->mNext = s; } // add a node before another one void Node_AddBefore(Node* s, Node* beforeThisOne) { if (!beforeThisOne->mParent || s->mID == 0) return; // failed s->mParent = beforeThisOne->mParent; s->mPrev = beforeThisOne->mPrev; s->mNext = beforeThisOne; if (beforeThisOne->mPrev) beforeThisOne->mPrev->mNext = s; else s->mParent->mHead = s; beforeThisOne->mPrev = s; } void Node_Replace(Node* s, Node* replaceThisOne) { // scprintf("->Node_Replace\n"); Group* group = replaceThisOne->mParent; if (!group) return; // failed if (s->mID == 0) return; s->mParent = group; s->mPrev = replaceThisOne->mPrev; s->mNext = replaceThisOne->mNext; if (s->mPrev) s->mPrev->mNext = s; else group->mHead = s; if (s->mNext) s->mNext->mPrev = s; else group->mTail = s; replaceThisOne->mPrev = replaceThisOne->mNext = nullptr; replaceThisOne->mParent = nullptr; Node_Delete(replaceThisOne); // scprintf("<-Node_Replace\n"); } // set a node's control so that it reads from a control bus - index argument void Node_MapControl(Node* inNode, int inIndex, int inBus) { if (inNode->mIsGroup) { Group_MapControl((Group*)inNode, inIndex, inBus); } else { Graph_MapControl((Graph*)inNode, inIndex, inBus); } } // set a node's control so that it reads from a control bus - name argument void Node_MapControl(Node* inNode, int32 inHash, int32* inName, int inIndex, int inBus) { if (inNode->mIsGroup) { Group_MapControl((Group*)inNode, inHash, inName, inIndex, inBus); } else { Graph_MapControl((Graph*)inNode, inHash, inName, inIndex, inBus); } } // set a node's control so that it reads from a control bus - index argument void Node_MapAudioControl(Node* inNode, int inIndex, int inBus) { if (inNode->mIsGroup) { Group_MapAudioControl((Group*)inNode, inIndex, inBus); } else { Graph_MapAudioControl((Graph*)inNode, inIndex, inBus); } } // set a node's control so that it reads from a control bus - name argument void Node_MapAudioControl(Node* inNode, int32 inHash, int32* inName, int inIndex, int inBus) { if (inNode->mIsGroup) { Group_MapAudioControl((Group*)inNode, inHash, inName, inIndex, inBus); } else { Graph_MapAudioControl((Graph*)inNode, inHash, inName, inIndex, inBus); } } // set a node's control value - index argument void Node_SetControl(Node* inNode, int inIndex, float inValue) { if (inNode->mIsGroup) { Group_SetControl((Group*)inNode, inIndex, inValue); } else { Graph_SetControl((Graph*)inNode, inIndex, inValue); } } // set a node's control value - name argument void Node_SetControl(Node* inNode, int32 inHash, int32* inName, int inIndex, float inValue) { if (inNode->mIsGroup) { Group_SetControl((Group*)inNode, inHash, inName, inIndex, inValue); } else { Graph_SetControl((Graph*)inNode, inHash, inName, inIndex, inValue); } } // this function can be installed using Node_SetRun to cause a node to do nothing // during its execution time. void Node_NullCalc(struct Node* /*inNode*/) {} void Graph_FirstCalc(Graph* inGraph); void Graph_NullFirstCalc(Graph* inGraph); // if inRun is zero then the node's calc function is set to Node_NullCalc, // otherwise its normal calc function is installed. void Node_SetRun(Node* inNode, int inRun) { if (inRun) { if (inNode->mCalcFunc == &Node_NullCalc) { if (inNode->mIsGroup) { inNode->mCalcFunc = (NodeCalcFunc)&Group_Calc; } else { inNode->mCalcFunc = (NodeCalcFunc)&Graph_Calc; } Node_StateMsg(inNode, kNode_On); } } else { if (inNode->mCalcFunc != &Node_NullCalc) { if (!inNode->mIsGroup && inNode->mCalcFunc == (NodeCalcFunc)&Graph_FirstCalc) { inNode->mCalcFunc = (NodeCalcFunc)&Graph_NullFirstCalc; } else { inNode->mCalcFunc = (NodeCalcFunc)&Node_NullCalc; } Node_StateMsg(inNode, kNode_Off); } } } void Node_Trace(Node* inNode) { if (inNode->mIsGroup) { Group_Trace((Group*)inNode); } else { Graph_Trace((Graph*)inNode); } } void Node_End(Node* inNode) { inNode->mCalcFunc = (NodeCalcFunc)&Node_Delete; } // send a trigger from a node to a client program. // this function puts the trigger on a FIFO which is harvested by another thread that // actually does the sending. void Node_SendTrigger(Node* inNode, int triggerID, float value) { World* world = inNode->mWorld; if (!world->mRealTime) return; TriggerMsg msg; msg.mWorld = world; msg.mNodeID = inNode->mID; msg.mTriggerID = triggerID; msg.mValue = value; world->hw->mTriggers.Write(msg); } // Send a reply from a node to a client program. // // This function puts the reply on a FIFO which is harvested by another thread that // actually does the sending. // // NOTE: Only to be called from the realtime thread. void Node_SendReply(Node* inNode, int replyID, const char* cmdName, int numArgs, const float* values) { World* world = inNode->mWorld; if (!world->mRealTime) return; const int cmdNameSize = strlen(cmdName); void* mem = World_Alloc(world, cmdNameSize + numArgs * sizeof(float)); if (mem == nullptr) return; NodeReplyMsg msg; msg.mWorld = world; msg.mNodeID = inNode->mID; msg.mID = replyID; msg.mValues = (float*)((char*)mem + cmdNameSize); memcpy(msg.mValues, values, numArgs * sizeof(float)); msg.mNumArgs = numArgs; msg.mCmdName = (char*)mem; memcpy(msg.mCmdName, cmdName, cmdNameSize); msg.mCmdNameSize = cmdNameSize; msg.mRTMemory = mem; world->hw->mNodeMsgs.Write(msg); } void Node_SendReply(Node* inNode, int replyID, const char* cmdName, float value) { Node_SendReply(inNode, replyID, cmdName, 1, &value); } // notify a client program of a node's state change. // this function puts the message on a FIFO which is harvested by another thread that // actually does the sending. void Node_StateMsg(Node* inNode, int inState) { if (inNode->mID < 0 && inState != kNode_Info) return; // no notification for negative IDs World* world = inNode->mWorld; if (!world->mRealTime) return; NodeEndMsg msg; msg.mWorld = world; msg.mNodeID = inNode->mID; msg.mGroupID = inNode->mParent ? inNode->mParent->mNode.mID : -1; msg.mPrevNodeID = inNode->mPrev ? inNode->mPrev->mID : -1; msg.mNextNodeID = inNode->mNext ? inNode->mNext->mID : -1; if (inNode->mIsGroup) { Group* group = (Group*)inNode; msg.mIsGroup = 1; msg.mHeadID = group->mHead ? group->mHead->mID : -1; msg.mTailID = group->mTail ? group->mTail->mID : -1; } else { msg.mIsGroup = 0; msg.mHeadID = -1; msg.mTailID = -1; } msg.mState = inState; world->hw->mNodeEnds.Write(msg); } #include "SC_Unit.h" void Unit_DoneAction(int doneAction, Unit* unit) { switch (doneAction) { case 1: Node_SetRun(&unit->mParent->mNode, 0); break; case 2: Node_End(&unit->mParent->mNode); break; case 3: { Node_End(&unit->mParent->mNode); Node* prev = unit->mParent->mNode.mPrev; if (prev) Node_End(prev); } break; case 4: { Node_End(&unit->mParent->mNode); Node* next = unit->mParent->mNode.mNext; if (next) Node_End(next); } break; case 5: { Node_End(&unit->mParent->mNode); Node* prev = unit->mParent->mNode.mPrev; if (!prev) break; if (prev && prev->mIsGroup) Group_DeleteAll((Group*)prev); else Node_End(prev); } break; case 6: { Node_End(&unit->mParent->mNode); Node* next = unit->mParent->mNode.mNext; if (!next) break; if (next->mIsGroup) Group_DeleteAll((Group*)next); else Node_End(next); } break; case 7: { Node* node = &unit->mParent->mNode; while (node) { Node* prev = node->mPrev; Node_End(node); node = prev; } } break; case 8: { Node* node = &unit->mParent->mNode; while (node) { Node* next = node->mNext; Node_End(node); node = next; } } break; case 9: { Node_End(&unit->mParent->mNode); Node* prev = unit->mParent->mNode.mPrev; if (prev) Node_SetRun(prev, 0); } break; case 10: { Node_End(&unit->mParent->mNode); Node* next = unit->mParent->mNode.mNext; if (next) Node_SetRun(next, 0); } break; case 11: { Node_End(&unit->mParent->mNode); Node* prev = unit->mParent->mNode.mPrev; if (!prev) break; if (prev->mIsGroup) Group_DeepFreeGraphs((Group*)prev); else Node_End(prev); } break; case 12: { Node_End(&unit->mParent->mNode); Node* next = unit->mParent->mNode.mNext; if (!next) break; if (next->mIsGroup) Group_DeepFreeGraphs((Group*)next); else Node_End(next); } break; case 13: { Node* node = unit->mParent->mNode.mParent->mHead; while (node) { Node* next = node->mNext; Node_End(node); node = next; } } break; case 14: Node_End(&unit->mParent->mNode.mParent->mNode); break; case 15: { Node_End(&unit->mParent->mNode); Node* next = unit->mParent->mNode.mNext; if (next) Node_SetRun(next, 1); } break; } }
14,025
C++
.cpp
426
26.741784
103
0.619941
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
29,911
SC_GraphDef.cpp
supercollider_supercollider/server/scsynth/SC_GraphDef.cpp
/* 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 */ #ifdef _WIN32 # include "SC_Win32Utils.h" #endif #include "clz.h" #include "SC_Graph.h" #include "SC_GraphDef.h" #include "SC_Wire.h" #include "SC_WireSpec.h" #include "SC_UnitSpec.h" #include "SC_UnitDef.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include "ReadWriteMacros.h" #include "SC_Prototypes.h" #include "SC_CoreAudio.h" #include "SC_SequencedCommand.h" #include "SC_Errors.h" #include "SC_Filesystem.hpp" #include <stdio.h> #include <stdlib.h> #include <sstream> #include <stdexcept> #include <string> #include <filesystem> #include <fstream> namespace fs = std::filesystem; extern Malloc gMalloc; const size_t ERR_BUF_SIZE(256); int32 GetHash(ParamSpec* inParamSpec) { return inParamSpec->mHash; } int32* GetKey(ParamSpec* inParamSpec) { return inParamSpec->mName; } void ReadName(char*& buffer, int32* name); void ReadName(char*& buffer, int32* name) { uint32 namelen = readUInt8(buffer); if (namelen >= kSCNameByteLen) { std::ostringstream os; os << "name too long (> " << kSCNameByteLen - 1 << " chars): " << std::string(buffer, namelen); throw std::runtime_error(os.str()); } memset(name, 0, kSCNameByteLen); readData(buffer, (char*)name, namelen); } void ReadNodeDefName(char*& buffer, int32* name); void ReadNodeDefName(char*& buffer, int32* name) { uint32 namelen = readUInt8(buffer); if (namelen >= kSCNodeDefNameByteLen) { std::ostringstream os; os << "node definition name too long (> " << kSCNodeDefNameByteLen - 1 << " chars): " << std::string(buffer, namelen); throw std::runtime_error(os.str()); } memset(name, 0, kSCNodeDefNameByteLen); readData(buffer, (char*)name, namelen); } void ParamSpec_Read(ParamSpec* inParamSpec, char*& buffer); void ParamSpec_Read(ParamSpec* inParamSpec, char*& buffer) { ReadName(buffer, inParamSpec->mName); inParamSpec->mIndex = readInt32_be(buffer); inParamSpec->mHash = Hash(inParamSpec->mName); } void ParamSpec_ReadVer1(ParamSpec* inParamSpec, char*& buffer); void ParamSpec_ReadVer1(ParamSpec* inParamSpec, char*& buffer) { ReadName(buffer, inParamSpec->mName); inParamSpec->mIndex = readInt16_be(buffer); inParamSpec->mHash = Hash(inParamSpec->mName); } void InputSpec_Read(InputSpec* inInputSpec, char*& buffer); void InputSpec_Read(InputSpec* inInputSpec, char*& buffer) { inInputSpec->mFromUnitIndex = readInt32_be(buffer); inInputSpec->mFromOutputIndex = readInt32_be(buffer); inInputSpec->mWireIndex = -1; } void InputSpec_ReadVer1(InputSpec* inInputSpec, char*& buffer); void InputSpec_ReadVer1(InputSpec* inInputSpec, char*& buffer) { inInputSpec->mFromUnitIndex = (int16)readInt16_be(buffer); inInputSpec->mFromOutputIndex = (int16)readInt16_be(buffer); inInputSpec->mWireIndex = -1; } void OutputSpec_Read(OutputSpec* inOutputSpec, char*& buffer); void OutputSpec_Read(OutputSpec* inOutputSpec, char*& buffer) { inOutputSpec->mCalcRate = readInt8(buffer); inOutputSpec->mWireIndex = -1; inOutputSpec->mBufferIndex = -1; inOutputSpec->mNumConsumers = 0; } void UnitSpec_Read(UnitSpec* inUnitSpec, char*& buffer); void UnitSpec_Read(UnitSpec* inUnitSpec, char*& buffer) { int32 name[kSCNameLen]; ReadName(buffer, name); inUnitSpec->mUnitDef = GetUnitDef(name); if (!inUnitSpec->mUnitDef) { char str[ERR_BUF_SIZE]; snprintf(str, ERR_BUF_SIZE, "UGen '%s' not installed.", (char*)name); throw std::runtime_error(str); return; } inUnitSpec->mCalcRate = readInt8(buffer); inUnitSpec->mNumInputs = readInt32_be(buffer); inUnitSpec->mNumOutputs = readInt32_be(buffer); inUnitSpec->mSpecialIndex = readInt16_be(buffer); inUnitSpec->mInputSpec = (InputSpec*)malloc(sizeof(InputSpec) * inUnitSpec->mNumInputs); inUnitSpec->mOutputSpec = (OutputSpec*)malloc(sizeof(OutputSpec) * inUnitSpec->mNumOutputs); for (uint32 i = 0; i < inUnitSpec->mNumInputs; ++i) { InputSpec_Read(inUnitSpec->mInputSpec + i, buffer); } for (uint32 i = 0; i < inUnitSpec->mNumOutputs; ++i) { OutputSpec_Read(inUnitSpec->mOutputSpec + i, buffer); } uint64 numPorts = inUnitSpec->mNumInputs + inUnitSpec->mNumOutputs; inUnitSpec->mAllocSize = inUnitSpec->mUnitDef->mAllocSize + numPorts * (sizeof(Wire*) + sizeof(float*)); } void UnitSpec_ReadVer1(UnitSpec* inUnitSpec, char*& buffer); void UnitSpec_ReadVer1(UnitSpec* inUnitSpec, char*& buffer) { int32 name[kSCNameLen]; ReadName(buffer, name); inUnitSpec->mUnitDef = GetUnitDef(name); if (!inUnitSpec->mUnitDef) { char str[ERR_BUF_SIZE]; snprintf(str, ERR_BUF_SIZE, "UGen '%s' not installed.", (char*)name); throw std::runtime_error(str); return; } inUnitSpec->mCalcRate = readInt8(buffer); inUnitSpec->mNumInputs = readInt16_be(buffer); inUnitSpec->mNumOutputs = readInt16_be(buffer); inUnitSpec->mSpecialIndex = readInt16_be(buffer); inUnitSpec->mInputSpec = (InputSpec*)malloc(sizeof(InputSpec) * inUnitSpec->mNumInputs); inUnitSpec->mOutputSpec = (OutputSpec*)malloc(sizeof(OutputSpec) * inUnitSpec->mNumOutputs); for (uint32 i = 0; i < inUnitSpec->mNumInputs; ++i) { InputSpec_ReadVer1(inUnitSpec->mInputSpec + i, buffer); } for (uint32 i = 0; i < inUnitSpec->mNumOutputs; ++i) { OutputSpec_Read(inUnitSpec->mOutputSpec + i, buffer); } uint64 numPorts = inUnitSpec->mNumInputs + inUnitSpec->mNumOutputs; inUnitSpec->mAllocSize = inUnitSpec->mUnitDef->mAllocSize + numPorts * (sizeof(Wire*) + sizeof(float*)); } GraphDef* GraphDef_Read(World* inWorld, char*& buffer, GraphDef* inList, int32 inVersion); GraphDef* GraphDef_ReadVer1(World* inWorld, char*& buffer, GraphDef* inList, int32 inVersion); GraphDef* GraphDefLib_Read(World* inWorld, char* buffer, GraphDef* inList); GraphDef* GraphDefLib_Read(World* inWorld, char* buffer, GraphDef* inList) { int32 magic = readInt32_be(buffer); if (magic != (('S' << 24) | ('C' << 16) | ('g' << 8) | 'f') /*'SCgf'*/) return inList; int32 version = readInt32_be(buffer); uint32 numDefs, i; switch (version) { case 2: numDefs = readInt16_be(buffer); for (i = 0; i < numDefs; ++i) { inList = GraphDef_Read(inWorld, buffer, inList, version); } return inList; break; case 1: case 0: numDefs = readInt16_be(buffer); for (i = 0; i < numDefs; ++i) { inList = GraphDef_ReadVer1(inWorld, buffer, inList, version); // handles 1 and 0 } return inList; break; default: return inList; break; } } void ChooseMulAddFunc(GraphDef* graphDef, UnitSpec* unitSpec); void DoBufferColoring(World* inWorld, GraphDef* inGraphDef); void GraphDef_ReadVariant(World* inWorld, char*& buffer, GraphDef* inGraphDef, GraphDef* inVariant) { memcpy(inVariant, inGraphDef, sizeof(GraphDef)); inVariant->mNumVariants = 0; inVariant->mVariants = nullptr; ReadName(buffer, inVariant->mNodeDef.mName); inVariant->mNodeDef.mHash = Hash(inVariant->mNodeDef.mName); inVariant->mInitialControlValues = (float32*)malloc(sizeof(float32) * inGraphDef->mNumControls); for (uint32 i = 0; i < inGraphDef->mNumControls; ++i) { inVariant->mInitialControlValues[i] = readFloat_be(buffer); } } typedef struct IndexMap { uint32 index; uint32 paramSpecIndex; } IndexMap; static inline bool sortIndexMaps(IndexMap map1, IndexMap map2) { return map1.paramSpecIndex < map2.paramSpecIndex; } // ver 2 inline static void calcParamSpecs(GraphDef* graphDef, char*& buffer) { if (graphDef->mNumParamSpecs) { int hashTableSize = NEXTPOWEROFTWO(graphDef->mNumParamSpecs); graphDef->mParamSpecTable = new ParamSpecTable(&gMalloc, hashTableSize, false); uint32 nSpecs = graphDef->mNumParamSpecs; graphDef->mParamSpecs = (ParamSpec*)malloc(nSpecs * sizeof(ParamSpec)); IndexMap* tempMaps = (IndexMap*)malloc(nSpecs * sizeof(IndexMap)); for (uint32 i = 0; i < nSpecs; ++i) { ParamSpec* paramSpec = graphDef->mParamSpecs + i; ParamSpec_Read(paramSpec, buffer); graphDef->mParamSpecTable->Add(paramSpec); IndexMap* tempMap = tempMaps + i; tempMap->index = i; tempMap->paramSpecIndex = paramSpec->mIndex; } // calculate numChannels for each spec // printf("\n\n**************\n"); std::sort(tempMaps, tempMaps + nSpecs, sortIndexMaps); for (uint32 i = 0; i < (nSpecs - 1); ++i) { IndexMap* tempMap = tempMaps + i; IndexMap* nextTempMap = tempMap + 1; ParamSpec* paramSpec = graphDef->mParamSpecs + tempMap->index; paramSpec->mNumChannels = nextTempMap->paramSpecIndex - tempMap->paramSpecIndex; // printf("%s: numChannels = %i\n", paramSpec->mName, paramSpec->mNumChannels); } IndexMap* tempMap = tempMaps + nSpecs - 1; ParamSpec* paramSpec = graphDef->mParamSpecs + tempMap->index; paramSpec->mNumChannels = graphDef->mNumControls - tempMap->paramSpecIndex; // printf("%s: numChannels = %i\n", paramSpec->mName, paramSpec->mNumChannels, paramSpec->mIndex); free(tempMaps); } else { // empty table to eliminate test in Graph_SetControl graphDef->mParamSpecTable = new ParamSpecTable(&gMalloc, 4, false); graphDef->mParamSpecs = nullptr; } } // ver 1 inline static void calcParamSpecs1(GraphDef* graphDef, char*& buffer) { if (graphDef->mNumParamSpecs) { int hashTableSize = NEXTPOWEROFTWO(graphDef->mNumParamSpecs); graphDef->mParamSpecTable = new ParamSpecTable(&gMalloc, hashTableSize, false); uint32 nSpecs = graphDef->mNumParamSpecs; graphDef->mParamSpecs = (ParamSpec*)malloc(nSpecs * sizeof(ParamSpec)); IndexMap* tempMaps = (IndexMap*)malloc(nSpecs * sizeof(IndexMap)); for (uint32 i = 0; i < nSpecs; ++i) { ParamSpec* paramSpec = graphDef->mParamSpecs + i; ParamSpec_ReadVer1(paramSpec, buffer); // read version 1 (the only difference to ver 2). graphDef->mParamSpecTable->Add(paramSpec); IndexMap* tempMap = tempMaps + i; tempMap->index = i; tempMap->paramSpecIndex = paramSpec->mIndex; } // calculate numChannels for each spec // printf("\n\n**************\n"); std::sort(tempMaps, tempMaps + nSpecs, sortIndexMaps); for (uint32 i = 0; i < (nSpecs - 1); ++i) { IndexMap* tempMap = tempMaps + i; IndexMap* nextTempMap = tempMap + 1; ParamSpec* paramSpec = graphDef->mParamSpecs + tempMap->index; paramSpec->mNumChannels = nextTempMap->paramSpecIndex - tempMap->paramSpecIndex; // printf("%s: numChannels = %i\n", paramSpec->mName, paramSpec->mNumChannels); } IndexMap* tempMap = tempMaps + nSpecs - 1; ParamSpec* paramSpec = graphDef->mParamSpecs + tempMap->index; paramSpec->mNumChannels = graphDef->mNumControls - tempMap->paramSpecIndex; // printf("%s: numChannels = %i\n", paramSpec->mName, paramSpec->mNumChannels, paramSpec->mIndex); free(tempMaps); } else { // empty table to eliminate test in Graph_SetControl graphDef->mParamSpecTable = new ParamSpecTable(&gMalloc, 4, false); graphDef->mParamSpecs = nullptr; } } // Allocation code shared between v1 and v2. // See https://github.com/supercollider/supercollider/issues/3266 // TODO: refactor GraphDef to be less brittle. static void GraphDef_SetAllocSizes(GraphDef* graphDef) { graphDef->mWiresAllocSize = graphDef->mNumWires * sizeof(Wire); graphDef->mUnitsAllocSize = graphDef->mNumUnitSpecs * sizeof(Unit*); graphDef->mCalcUnitsAllocSize = graphDef->mNumCalcUnits * sizeof(Unit*); graphDef->mNodeDef.mAllocSize += graphDef->mWiresAllocSize; graphDef->mNodeDef.mAllocSize += graphDef->mUnitsAllocSize; graphDef->mNodeDef.mAllocSize += graphDef->mCalcUnitsAllocSize; graphDef->mControlAllocSize = graphDef->mNumControls * sizeof(float); graphDef->mNodeDef.mAllocSize += graphDef->mControlAllocSize; graphDef->mMapControlsAllocSize = graphDef->mNumControls * sizeof(float*); graphDef->mNodeDef.mAllocSize += graphDef->mMapControlsAllocSize; graphDef->mMapControlRatesAllocSize = graphDef->mNumControls * sizeof(int); graphDef->mNodeDef.mAllocSize += graphDef->mMapControlRatesAllocSize; graphDef->mAudioMapBusOffsetSize = graphDef->mNumControls * sizeof(int32); graphDef->mNodeDef.mAllocSize += graphDef->mAudioMapBusOffsetSize; } // ver 2 /** \note Relevant supernova code: \c sc_synthdef::prepare() * \note Relevant v1 code: \c GraphDef_ReadVer1() */ GraphDef* GraphDef_Read(World* inWorld, char*& buffer, GraphDef* inList, int32 inVersion) { int32 name[kSCNodeDefNameLen]; ReadNodeDefName(buffer, name); GraphDef* graphDef = (GraphDef*)calloc(1, sizeof(GraphDef)); graphDef->mOriginal = graphDef; graphDef->mNodeDef.mAllocSize = sizeof(Graph); memcpy((char*)graphDef->mNodeDef.mName, (char*)name, kSCNodeDefNameByteLen); graphDef->mNodeDef.mHash = Hash(graphDef->mNodeDef.mName); graphDef->mNumConstants = readInt32_be(buffer); graphDef->mConstants = (float*)malloc(graphDef->mNumConstants * sizeof(float)); for (uint32 i = 0; i < graphDef->mNumConstants; ++i) { graphDef->mConstants[i] = readFloat_be(buffer); } graphDef->mNumControls = readInt32_be(buffer); graphDef->mInitialControlValues = (float32*)malloc(sizeof(float32) * graphDef->mNumControls); for (uint32 i = 0; i < graphDef->mNumControls; ++i) { graphDef->mInitialControlValues[i] = readFloat_be(buffer); } graphDef->mNumParamSpecs = readInt32_be(buffer); calcParamSpecs(graphDef, buffer); graphDef->mNumWires = graphDef->mNumConstants; graphDef->mNumUnitSpecs = readInt32_be(buffer); graphDef->mUnitSpecs = (UnitSpec*)malloc(sizeof(UnitSpec) * graphDef->mNumUnitSpecs); graphDef->mNumCalcUnits = 0; for (uint32 i = 0; i < graphDef->mNumUnitSpecs; ++i) { UnitSpec* unitSpec = graphDef->mUnitSpecs + i; UnitSpec_Read(unitSpec, buffer); switch (unitSpec->mCalcRate) { case calc_ScalarRate: unitSpec->mRateInfo = &inWorld->mBufRate; break; case calc_BufRate: graphDef->mNumCalcUnits++; unitSpec->mRateInfo = &inWorld->mBufRate; break; case calc_FullRate: graphDef->mNumCalcUnits++; unitSpec->mRateInfo = &inWorld->mFullRate; break; case calc_DemandRate: unitSpec->mRateInfo = &inWorld->mBufRate; break; } graphDef->mNodeDef.mAllocSize += unitSpec->mAllocSize; graphDef->mNumWires += unitSpec->mNumOutputs; } DoBufferColoring(inWorld, graphDef); GraphDef_SetAllocSizes(graphDef); graphDef->mNext = inList; graphDef->mRefCount = 1; graphDef->mNumVariants = readInt16_be(buffer); if (graphDef->mNumVariants) { graphDef->mVariants = (GraphDef*)calloc(graphDef->mNumVariants, sizeof(GraphDef)); for (uint32 i = 0; i < graphDef->mNumVariants; ++i) { GraphDef_ReadVariant(inWorld, buffer, graphDef, graphDef->mVariants + i); } } return graphDef; } // ver 0 or 1 GraphDef* GraphDef_ReadVer1(World* inWorld, char*& buffer, GraphDef* inList, int32 inVersion) { int32 name[kSCNodeDefNameLen]; ReadNodeDefName(buffer, name); GraphDef* graphDef = (GraphDef*)calloc(1, sizeof(GraphDef)); graphDef->mOriginal = graphDef; graphDef->mNodeDef.mAllocSize = sizeof(Graph); memcpy((char*)graphDef->mNodeDef.mName, (char*)name, kSCNodeDefNameByteLen); graphDef->mNodeDef.mHash = Hash(graphDef->mNodeDef.mName); graphDef->mNumConstants = readInt16_be(buffer); graphDef->mConstants = (float*)malloc(graphDef->mNumConstants * sizeof(float)); for (uint32 i = 0; i < graphDef->mNumConstants; ++i) { graphDef->mConstants[i] = readFloat_be(buffer); } graphDef->mNumControls = readInt16_be(buffer); graphDef->mInitialControlValues = (float32*)malloc(sizeof(float32) * graphDef->mNumControls); for (uint32 i = 0; i < graphDef->mNumControls; ++i) { graphDef->mInitialControlValues[i] = readFloat_be(buffer); } graphDef->mNumParamSpecs = readInt16_be(buffer); calcParamSpecs1(graphDef, buffer); graphDef->mNumWires = graphDef->mNumConstants; graphDef->mNumUnitSpecs = readInt16_be(buffer); graphDef->mUnitSpecs = (UnitSpec*)malloc(sizeof(UnitSpec) * graphDef->mNumUnitSpecs); graphDef->mNumCalcUnits = 0; for (uint32 i = 0; i < graphDef->mNumUnitSpecs; ++i) { UnitSpec* unitSpec = graphDef->mUnitSpecs + i; UnitSpec_ReadVer1(unitSpec, buffer); switch (unitSpec->mCalcRate) { case calc_ScalarRate: unitSpec->mRateInfo = &inWorld->mBufRate; break; case calc_BufRate: graphDef->mNumCalcUnits++; unitSpec->mRateInfo = &inWorld->mBufRate; break; case calc_FullRate: graphDef->mNumCalcUnits++; unitSpec->mRateInfo = &inWorld->mFullRate; break; case calc_DemandRate: unitSpec->mRateInfo = &inWorld->mBufRate; break; } graphDef->mNodeDef.mAllocSize += unitSpec->mAllocSize; graphDef->mNumWires += unitSpec->mNumOutputs; } DoBufferColoring(inWorld, graphDef); GraphDef_SetAllocSizes(graphDef); graphDef->mNext = inList; graphDef->mRefCount = 1; if (inVersion >= 1) { graphDef->mNumVariants = readInt16_be(buffer); if (graphDef->mNumVariants) { graphDef->mVariants = (GraphDef*)calloc(graphDef->mNumVariants, sizeof(GraphDef)); for (uint32 i = 0; i < graphDef->mNumVariants; ++i) { GraphDef_ReadVariant(inWorld, buffer, graphDef, graphDef->mVariants + i); } } } return graphDef; } void GraphDef_Define(World* inWorld, GraphDef* inList) { GraphDef* graphDef = inList; while (graphDef) { GraphDef* next = graphDef->mNext; GraphDef* previousDef = World_GetGraphDef(inWorld, graphDef->mNodeDef.mName); if (previousDef) { World_RemoveGraphDef(inWorld, previousDef); if (--previousDef->mRefCount == 0) { GraphDef_DeleteMsg(inWorld, previousDef); } } World_AddGraphDef(inWorld, graphDef); graphDef->mNext = nullptr; graphDef = next; } } SCErr GraphDef_Remove(World* inWorld, int32* inName) { GraphDef* graphDef = World_GetGraphDef(inWorld, inName); if (graphDef) { World_RemoveGraphDef(inWorld, graphDef); if (--graphDef->mRefCount == 0) { return GraphDef_DeleteMsg(inWorld, graphDef); } } return kSCErr_None; } SCErr SendReplyCmd_d_removed(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { void* space = World_Alloc(inWorld, sizeof(SendReplyCmd)); if (!space) return kSCErr_OutOfRealTimeMemory; SendReplyCmd* cmd = new (space) SendReplyCmd(inWorld, inReply); if (!cmd) return kSCErr_Failed; int err = cmd->Init(inData, inSize); if (err) { cmd->~SendReplyCmd(); World_Free(inWorld, space); return err; } if (inWorld->mRealTime) cmd->CallNextStage(); else cmd->CallEveryStage(); return kSCErr_None; } SCErr GraphDef_DeleteMsg(World* inWorld, GraphDef* inDef) { DeleteGraphDefMsg msg; msg.mDef = inDef; inWorld->hw->mDeleteGraphDefs.Write(msg); small_scpacket packet; packet.adds("/d_removed"); packet.maketags(2); packet.addtag(','); packet.addtag('s'); packet.adds((char*)inDef->mNodeDef.mName); for (auto addr : *inWorld->hw->mUsers) { SCErr const err = SendReplyCmd_d_removed(inWorld, packet.size(), packet.data(), &addr); if (err != kSCErr_None) return err; } return kSCErr_None; } GraphDef* GraphDef_Recv(World* inWorld, char* buffer, GraphDef* inList) { try { inList = GraphDefLib_Read(inWorld, buffer, inList); } catch (std::exception& exc) { scprintf("exception in GraphDef_Recv: %s\n", exc.what()); } catch (...) { scprintf("unknown exception in GraphDef_Recv\n"); } return inList; } GraphDef* GraphDef_LoadGlob(World* inWorld, const char* pattern, GraphDef* inList) { SC_Filesystem::Glob* glob = SC_Filesystem::makeGlob(pattern); if (!glob) return inList; fs::path path; while (!(path = SC_Filesystem::globNext(glob)).empty()) { if (path.extension() == ".scsyndef") { inList = GraphDef_Load(inWorld, path, inList); } // why? <sk> GraphDef_Load(inWorld, path, inList); } SC_Filesystem::freeGlob(glob); return inList; } std::string load_file(const std::filesystem::path& file_path) { std::ifstream file(file_path); if (!file.is_open()) { throw std::runtime_error("Could not open file: " + file_path.string()); } std::stringstream buffer; buffer << file.rdbuf(); return buffer.str(); } GraphDef* GraphDef_Load(World* inWorld, const fs::path& path, GraphDef* inList) { try { std::string file_contents = load_file(path); inList = GraphDefLib_Read(inWorld, &file_contents[0], inList); } catch (const std::exception& e) { scprintf("exception in GraphDef_Load: %s\n", e.what()); const std::string path_utf8_str = SC_Codecvt::path_to_utf8_str(path); scprintf("while reading file: '%s'", path_utf8_str.c_str()); } catch (...) { scprintf("unknown exception in GrafDef_Load\n"); const std::string path_utf8_str = SC_Codecvt::path_to_utf8_str(path); scprintf("while reading file '%s'\n", path_utf8_str.c_str()); } return inList; } GraphDef* GraphDef_LoadDir(World* inWorld, const fs::path& dirname, GraphDef* inList) { std::error_code ec; fs::recursive_directory_iterator rditer(dirname, fs::directory_options::follow_directory_symlink, ec); if (ec) { scprintf("*** ERROR: open directory failed '%s'\n", SC_Codecvt::path_to_utf8_str(dirname).c_str()); return inList; } while (rditer != fs::end(rditer)) { const fs::path path = *rditer; if (fs::is_directory(path)) { if (SC_Filesystem::instance().shouldNotCompileDirectory(path)) rditer.disable_recursion_pending(); else ; // do nothing; recursion will happen automatically } else if (path.extension() == ".scsyndef") { // ordinary file inList = GraphDef_Load(inWorld, path, inList); } else { // ignore file, wasn't a synth def } rditer.increment(ec); if (ec) { scprintf("*** ERROR: Could not iterate on '%s': %s\n", SC_Codecvt::path_to_utf8_str(path).c_str(), ec.message().c_str()); return inList; } } return inList; } void UnitSpec_Free(UnitSpec* inUnitSpec); void UnitSpec_Free(UnitSpec* inUnitSpec) { free(inUnitSpec->mInputSpec); free(inUnitSpec->mOutputSpec); } void GraphDef_Free(GraphDef* inGraphDef) { if (inGraphDef != inGraphDef->mOriginal) return; for (uint32 i = 0; i < inGraphDef->mNumUnitSpecs; ++i) { UnitSpec_Free(inGraphDef->mUnitSpecs + i); } for (uint32 i = 0; i < inGraphDef->mNumVariants; ++i) { free(inGraphDef->mVariants[i].mInitialControlValues); } delete inGraphDef->mParamSpecTable; free(inGraphDef->mParamSpecs); free(inGraphDef->mInitialControlValues); free(inGraphDef->mConstants); free(inGraphDef->mUnitSpecs); free(inGraphDef->mVariants); free(inGraphDef); } void NodeDef_Dump(NodeDef* inNodeDef) { scprintf("mName '%s'\n", (char*)inNodeDef->mName); scprintf("mHash %d\n", inNodeDef->mHash); scprintf("mAllocSize %lu\n", inNodeDef->mAllocSize); } void GraphDef_Dump(GraphDef* inGraphDef) { NodeDef_Dump(&inGraphDef->mNodeDef); scprintf("mNumControls %d\n", inGraphDef->mNumControls); scprintf("mNumWires %d\n", inGraphDef->mNumWires); scprintf("mNumUnitSpecs %d\n", inGraphDef->mNumUnitSpecs); scprintf("mNumWireBufs %d\n", inGraphDef->mNumWireBufs); for (uint32 i = 0; i < inGraphDef->mNumControls; ++i) { scprintf(" %d mInitialControlValues %g\n", i, inGraphDef->mInitialControlValues[i]); } for (uint32 i = 0; i < inGraphDef->mNumWires; ++i) { // WireSpec_Dump(inGraphDef->mWireSpec + i); } for (uint32 i = 0; i < inGraphDef->mNumUnitSpecs; ++i) { // UnitSpec_Dump(inGraphDef->mUnitSpecs + i); } } /* SynthBufferAllocator { var nextBufIndex = 0; var stack; var refs; *new { ^super.new.init } init { refs = Bag.new; } alloc { arg count; var bufNumber; if (stack.size > 0, { bufNumber = stack.pop },{ bufNumber = nextBufIndex; nextBufIndex = nextBufIndex + 1; }); refs.add(bufNumber, count); ^bufNumber } release { arg bufNumber; refs.remove(bufNumber); if (refs.includes(bufNumber).not, { stack = stack.add(bufNumber) }); } numBufs { ^nextBufIndex } } */ struct BufColorAllocator { int16* refs; int16* stack; int16 stackPtr; int16 nextIndex; int16 refsMaxSize; int16 stackMaxSize; BufColorAllocator(); ~BufColorAllocator(); uint32 alloc(uint32 count); bool release(int inIndex); int NumBufs() { return nextIndex; } }; inline BufColorAllocator::BufColorAllocator() { refsMaxSize = 32; stackMaxSize = 32; refs = (int16*)calloc(refsMaxSize, sizeof(int16)); stack = (int16*)calloc(stackMaxSize, sizeof(int16)); stackPtr = 0; nextIndex = 0; } inline BufColorAllocator::~BufColorAllocator() { free(refs); free(stack); } inline uint32 BufColorAllocator::alloc(uint32 count) { uint32 outIndex; if (stackPtr) { outIndex = stack[--stackPtr]; } else { outIndex = nextIndex++; } if (outIndex >= refsMaxSize) { int16* tmprefs = (int16*)realloc(refs, refsMaxSize * 2 * sizeof(int16)); if (tmprefs == nullptr) { free(refs); refs = nullptr; throw std::runtime_error("buffer coloring error: reallocation failed."); } else { refs = tmprefs; } memset(refs + refsMaxSize, 0, refsMaxSize * sizeof(int16)); refsMaxSize *= 2; } refs[outIndex] = count; return outIndex; } inline bool BufColorAllocator::release(int inIndex) { if (refs[inIndex] == 0) return false; if (--refs[inIndex] == 0) { if (stackPtr >= stackMaxSize) { int16* tmpstack = (int16*)realloc(stack, stackMaxSize * 2 * sizeof(int16)); if (tmpstack == nullptr) { free(stack); stack = nullptr; throw std::runtime_error("buffer coloring error: reallocation during release failed."); } else { stack = tmpstack; } memset(stack + stackMaxSize, 0, stackMaxSize * sizeof(int16)); stackMaxSize *= 2; } stack[stackPtr++] = inIndex; } return true; } static void ReleaseInputBuffers(GraphDef* inGraphDef, UnitSpec* unitSpec, BufColorAllocator& bufColor) { for (int64 i = (int64)(unitSpec->mNumInputs) - 1; i >= 0; --i) { InputSpec* inputSpec = unitSpec->mInputSpec + i; if (inputSpec->mFromUnitIndex >= 0) { UnitSpec* outUnit = inGraphDef->mUnitSpecs + inputSpec->mFromUnitIndex; OutputSpec* outputSpec = outUnit->mOutputSpec + inputSpec->mFromOutputIndex; inputSpec->mWireIndex = outputSpec->mWireIndex; if (outputSpec->mCalcRate == calc_FullRate) { if (unitSpec->mCalcRate == calc_DemandRate) // we never release any input buffers of demand-rate ugens continue; if (!bufColor.release(outputSpec->mBufferIndex)) { scprintf("buffer coloring error: tried to release output with zero count\n"); scprintf("output: %d %s %d\n", inputSpec->mFromUnitIndex, outUnit->mUnitDef->mUnitDefName, inputSpec->mFromOutputIndex); scprintf("input: %s %d\n", unitSpec->mUnitDef->mUnitDefName, i); throw std::runtime_error("buffer coloring error."); } } } else { inputSpec->mWireIndex = inputSpec->mFromOutputIndex; } } } static void AllocOutputBuffers(UnitSpec* unitSpec, BufColorAllocator& bufColor, int32& wireIndexCtr) { // scprintf("AllocOutputBuffers %s numoutputs %d\n", unitSpec->mUnitDef->mUnitDefName, unitSpec->mNumOutputs); for (uint32 i = 0; i < unitSpec->mNumOutputs; ++i) { OutputSpec* outputSpec = unitSpec->mOutputSpec + i; outputSpec->mWireIndex = wireIndexCtr++; if (outputSpec->mCalcRate == calc_FullRate) { uint32 bufIndex = bufColor.alloc(outputSpec->mNumConsumers); outputSpec->mBufferIndex = bufIndex; } } } void DoBufferColoring(World* inWorld, GraphDef* inGraphDef) { // count consumers of outputs for (uint32 j = 0; j < inGraphDef->mNumUnitSpecs; ++j) { UnitSpec* unitSpec = inGraphDef->mUnitSpecs + j; for (uint32 i = 0; i < unitSpec->mNumInputs; ++i) { InputSpec* inputSpec = unitSpec->mInputSpec + i; if (inputSpec->mFromUnitIndex >= 0) { UnitSpec* outUnit = inGraphDef->mUnitSpecs + inputSpec->mFromUnitIndex; OutputSpec* outputSpec = outUnit->mOutputSpec + inputSpec->mFromOutputIndex; outputSpec->mNumConsumers++; } } } // buffer coloring { BufColorAllocator bufColor; int32 wireIndexCtr = inGraphDef->mNumConstants; // mNumConstants is a uint32, but limited to int32 in OSC for (uint32 j = 0; j < inGraphDef->mNumUnitSpecs; ++j) { UnitSpec* unitSpec = inGraphDef->mUnitSpecs + j; if (unitSpec->mUnitDef->mFlags & kUnitDef_CantAliasInputsToOutputs) { // set wire index, alloc outputs AllocOutputBuffers(unitSpec, bufColor, wireIndexCtr); // set wire index, release inputs ReleaseInputBuffers(inGraphDef, unitSpec, bufColor); } else { // set wire index, release inputs ReleaseInputBuffers(inGraphDef, unitSpec, bufColor); // set wire index, alloc outputs AllocOutputBuffers(unitSpec, bufColor, wireIndexCtr); } } inGraphDef->mNumWireBufs = bufColor.NumBufs(); if (inWorld->mRunning) { // cannot reallocate interconnect buffers while running audio. if (inGraphDef->mNumWireBufs > inWorld->hw->mMaxWireBufs) { throw std::runtime_error("exceeded number of interconnect buffers."); } } else { inWorld->hw->mMaxWireBufs = sc_max(inWorld->hw->mMaxWireBufs, inGraphDef->mNumWireBufs); } } // multiply buf indices by buf length for proper offset int bufLength = inWorld->mBufLength; for (uint32 j = 0; j < inGraphDef->mNumUnitSpecs; ++j) { UnitSpec* unitSpec = inGraphDef->mUnitSpecs + j; for (uint32 i = 0; i < unitSpec->mNumOutputs; ++i) { OutputSpec* outputSpec = unitSpec->mOutputSpec + i; if (outputSpec->mCalcRate == calc_FullRate) { outputSpec->mBufferIndex *= bufLength; } } } }
33,097
C++
.cpp
783
35.261814
116
0.655818
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
29,912
SC_Lib.cpp
supercollider_supercollider/server/scsynth/SC_Lib.cpp
/* 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_Lib.h" #include "SC_Lib_Cintf.h" #include "SC_SequencedCommand.h" #include "scsynthsend.h" #include <string.h> #include <ctype.h> #include "SC_Prototypes.h" #include "SC_Str4.h" #include "SC_WorldOptions.h" const size_t PATH_BUF_SIZE(256); void SendDone(ReplyAddress* inReply, const char* inCommandName) { small_scpacket packet; packet.adds("/done"); packet.maketags(2); packet.addtag(','); packet.addtag('s'); packet.adds(inCommandName); SendReply(inReply, packet.data(), packet.size()); } void SendDoneWithIntValue(ReplyAddress* inReply, const char* inCommandName, int value) { small_scpacket packet; packet.adds("/done"); packet.maketags(3); packet.addtag(','); packet.addtag('s'); packet.adds(inCommandName); packet.addtag('i'); packet.addi(value); SendReply(inReply, packet.data(), packet.size()); } static void appendVarArgs(small_scpacket& packet, const char* oscFormat, va_list args) { // support all the types the server currently does while (*oscFormat != '\0') { if (*oscFormat == 'i') { int32 i = va_arg(args, int32); packet.addtag('i'); packet.addi(i); } else if (*oscFormat == 'h') { int64 h = va_arg(args, int64); packet.addtag('h'); packet.addii(h); } else if (*oscFormat == 'f') { float32 f = (float32)va_arg(args, double); packet.addtag('f'); packet.addf(f); } else if (*oscFormat == 'd') { double d = va_arg(args, double); packet.addtag('d'); packet.addd(d); } else if (*oscFormat == 's') { const char* s = va_arg(args, char*); packet.addtag('s'); packet.adds(s); } else if (*oscFormat == 'b') { size_t len = va_arg(args, size_t); ++oscFormat; uint8* b = va_arg(args, uint8*); packet.addtag('b'); packet.addb(b, len); } ++oscFormat; } } void SendDoneWithVarArgs(struct ReplyAddress* inReply, const char* inCommandName, const char* oscFormat, ...) { small_scpacket packet; int numArgs = strlen(oscFormat); packet.adds("/done"); packet.maketags(2 + numArgs); packet.addtag(','); packet.addtag('s'); packet.adds(inCommandName); va_list args; va_start(args, oscFormat); appendVarArgs(packet, oscFormat, args); va_end(args); SendReply(inReply, packet.data(), packet.size()); } void SendFailure(ReplyAddress* inReply, const char* inCommandName, const char* errString) { small_scpacket packet; packet.adds("/fail"); packet.maketags(3); packet.addtag(','); packet.addtag('s'); packet.addtag('s'); packet.adds(inCommandName); packet.adds(errString); SendReply(inReply, packet.data(), packet.size()); } void SendFailureWithIntValue(ReplyAddress* inReply, const char* inCommandName, const char* errString, uint32 index) { small_scpacket packet; packet.adds("/fail"); packet.maketags(4); packet.addtag(','); packet.addtag('s'); packet.addtag('s'); packet.adds(inCommandName); packet.adds(errString); packet.addtag('i'); packet.addi((int)index); SendReply(inReply, packet.data(), packet.size()); } void SendFailureWithVarArgs(struct ReplyAddress* inReply, const char* inCommandName, const char* errString, const char* oscFormat, ...) { small_scpacket packet; int numArgs = strlen(oscFormat); packet.adds("/fail"); packet.maketags(3 + numArgs); packet.addtag(','); packet.addtag('s'); packet.addtag('s'); packet.adds(inCommandName); packet.adds(errString); va_list args; va_start(args, oscFormat); appendVarArgs(packet, oscFormat, args); va_end(args); SendReply(inReply, packet.data(), packet.size()); } void ReportLateness(ReplyAddress* inReply, float32 seconds) { small_scpacket packet; packet.adds("/late"); packet.maketags(2); packet.addtag(','); packet.addtag('f'); packet.addf(seconds); SendReply(inReply, packet.data(), packet.size()); } SC_NamedObj::SC_NamedObj() { SetName("?"); } SC_NamedObj::~SC_NamedObj() {} void SC_NamedObj::SetName(const int32* inName) { if (str4len(inName) > (int)kSCNameLen) return; str4cpy(mName, inName); mHash = Hash(mName); } void SC_NamedObj::SetName(const char* inName) { if (str4len(inName) > (int)kSCNameLen) return; str4cpy(mName, inName); mHash = Hash(mName); } SC_LibCmd::SC_LibCmd(SC_CommandFunc inFunc): mFunc(inFunc) {} SCErr SC_LibCmd::Perform(struct World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { SCErr err; // int kSendError = 1; // i.e., 0x01 | 0x02; try { err = (mFunc)(inWorld, inSize, inData, inReply); } catch (int iexc) { err = iexc; } catch (std::exception& exc) { if (inWorld->mLocalErrorNotification <= 0 && inWorld->mErrorNotification) { CallSendFailureCommand(inWorld, (char*)Name(), exc.what(), inReply); scprintf("FAILURE IN SERVER %s %s\n", (char*)Name(), exc.what()); } return kSCErr_Failed; } catch (...) { err = kSCErr_Failed; } if (err && (inWorld->mLocalErrorNotification <= 0 && inWorld->mErrorNotification)) { char errstr[128]; SC_ErrorString(err, errstr); CallSendFailureCommand(inWorld, (char*)Name(), errstr, inReply); scprintf("FAILURE IN SERVER %s %s\n", (char*)Name(), errstr); } return err; } SCErr NewCommand(const char* inPath, uint32 inCommandNumber, SC_CommandFunc inFunc) { char path[PATH_BUF_SIZE]; snprintf(path, PATH_BUF_SIZE, "/%s", inPath); SC_LibCmd* cmd = new SC_LibCmd(inFunc); cmd->SetName(path); gCmdLib->Add(cmd); // support OSC commands without the leading slash SC_LibCmd* cmd2 = new SC_LibCmd(inFunc); cmd2->SetName(inPath); gCmdLib->Add(cmd2); // support integer OSC commands gCmdArray[inCommandNumber] = cmd; return kSCErr_None; }
6,998
C++
.cpp
192
30.6875
117
0.649793
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
29,913
SC_UnitDef.cpp
supercollider_supercollider/server/scsynth/SC_UnitDef.cpp
/* 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 <stdlib.h> #include "SC_Endian.h" // first to avoid win32 IN clash #include "SC_Graph.h" #include "SC_InterfaceTable.h" #include "SC_Lib_Cintf.h" #include "SC_Prototypes.h" #include "SC_Str4.h" #include "SC_Unit.h" #include "SC_UnitDef.h" #include "SC_World.h" #include "sc_msg_iter.h" extern int gMissingNodeID; bool UnitDef_Create(const char* inName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags) { if (strlen(inName) >= kSCNameByteLen) return false; UnitDef* unitDef = (UnitDef*)malloc(sizeof(UnitDef)); if (!unitDef) return false; str4cpy(unitDef->mUnitDefName, inName); unitDef->mHash = Hash(unitDef->mUnitDefName); unitDef->mAllocSize = inAllocSize; unitDef->mUnitCtorFunc = inCtor; unitDef->mUnitDtorFunc = inDtor; unitDef->mCmds = nullptr; unitDef->mFlags = inFlags; if (!AddUnitDef(unitDef)) { free(unitDef); return false; } return true; } bool UnitDef_AddCmd(const char* inUnitDefName, const char* inCmdName, UnitCmdFunc inFunc) { if (strlen(inUnitDefName) >= kSCNameByteLen) return false; int32 unitDefName[kSCNameLen]; memset(unitDefName, 0, kSCNameByteLen); strcpy((char*)unitDefName, inUnitDefName); if (strlen(inCmdName) >= kSCNameByteLen) return false; UnitDef* unitDef = GetUnitDef(unitDefName); if (!unitDef) return false; if (!unitDef->mCmds) unitDef->mCmds = new HashTable<UnitCmd, Malloc>(&gMalloc, 4, true); UnitCmd* cmd = new UnitCmd(); memset(cmd->mCmdName, 0, kSCNameByteLen); strcpy((char*)cmd->mCmdName, inCmdName); cmd->mFunc = inFunc; cmd->mHash = Hash(cmd->mCmdName); unitDef->mCmds->Add(cmd); return true; } bool PlugIn_DefineCmd(const char* inCmdName, PlugInCmdFunc inFunc, void* inUserData) { if (strlen(inCmdName) >= kSCNameByteLen) return false; PlugInCmd* cmd = new PlugInCmd(); memset(cmd->mCmdName, 0, kSCNameByteLen); strcpy((char*)cmd->mCmdName, inCmdName); cmd->mFunc = inFunc; cmd->mHash = Hash(cmd->mCmdName); cmd->mUserData = inUserData; AddPlugInCmd(cmd); return true; } void Graph_FirstCalc(Graph* inGraph); void Graph_NullFirstCalc(Graph* inGraph); void Graph_QueueUnitCmd(Graph* inGraph, int inSize, const char* inData); int Unit_DoCmd(World* inWorld, int inSize, char* inData) { sc_msg_iter msg(inSize, inData); int nodeID = msg.geti(); gMissingNodeID = nodeID; Graph* graph = World_GetGraph(inWorld, nodeID); if (!graph) return kSCErr_NodeNotFound; uint32 unitID = msg.geti(); if (unitID >= graph->mNumUnits) return kSCErr_IndexOutOfRange; Unit* unit = graph->mUnits[unitID]; UnitDef* unitDef = unit->mUnitDef; int32* cmdName = msg.gets4(); if (!cmdName) return kSCErr_Failed; if (!unitDef->mCmds) return kSCErr_Failed; UnitCmd* cmd = unitDef->mCmds->Get(cmdName); if (!cmd) throw std::runtime_error(std::string((char*)cmdName) + " not found"); // only run unit command if the ctor has been called! if (graph->mNode.mCalcFunc == (NodeCalcFunc)&Graph_FirstCalc || graph->mNode.mCalcFunc == (NodeCalcFunc)&Graph_NullFirstCalc) { Graph_QueueUnitCmd(graph, inSize, inData); } else { (cmd->mFunc)(unit, &msg); } return kSCErr_None; } int PlugIn_DoCmd(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); int32* cmdName = msg.gets4(); if (!cmdName) return kSCErr_Failed; PlugInCmd* cmd = GetPlugInCmd(cmdName); if (!cmd) throw std::runtime_error(std::string((char*)cmdName) + " not found"); (cmd->mFunc)(inWorld, cmd->mUserData, &msg, (void*)inReply); return kSCErr_None; }
4,719
C++
.cpp
123
33.308943
119
0.695414
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
29,914
SC_Bela.cpp
supercollider_supercollider/server/scsynth/SC_Bela.cpp
/* Bela audio driver for SuperCollider. Copyright (c) 2016 Dan Stowell. All rights reserved. Copyright (c) 2016 Marije Baalman. All rights reserved. Copyright (c) 2016 Giulio Moro. 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 This file contains elements from SC_PortAudio.cpp and SC_Jack.cpp, copyright their authors, and published under the same licence. */ #include "SC_CoreAudio.h" #include "SC_Prototypes.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include "SC_Time.hpp" #include "SC_BelaScope.h" #include <cmath> // floor #include <cstdlib> // exit #include <cstring> // memcpy #include <cobalt/time.h> // needed for CLOCK_HOST_REALTIME #include <cobalt/stdio.h> // rt_vprintf extern "C" { // This will be wrapped by Xenomai without requiring linker flags int __wrap_clock_gettime(clockid_t clock_id, struct timespec* tp); } #include "Bela.h" // Xenomai-specific includes #include <sys/mman.h> #if (BELA_MAJOR_VERSION == 1 && BELA_MINOR_VERSION < 9) # error You need at least Bela API 1.9 #endif // Audio driver API implementation int32 server_timeseed() { return timeSeed(); } int64 gOSCoffset = 0; int64 oscTimeNow() { return OSCTime(getTime()); } void initializeScheduler() { gOSCoffset = oscTimeNow(); } class SC_BelaDriver final : public SC_AudioDriver { public: SC_BelaDriver(World* inWorld); virtual ~SC_BelaDriver(); void BelaAudioCallback(BelaContext* belaContext); bool BelaSetup(const BelaContext* belaContext); void SignalReceived(int signal); static SC_BelaDriver* s_instance; static SC_BelaDriver* Construct(World* inWorld); protected: // Driver interface methods bool DriverSetup(int* outNumSamples, double* outSampleRate) override; bool DriverStart() override; bool DriverStop() override; private: int mInputChannelCount = 0, mOutputChannelCount = 0; uint32 mSCBufLength; float mBelaSampleRate = 0; }; SC_BelaDriver* SC_BelaDriver::s_instance = nullptr; SC_AudioDriver* SC_NewAudioDriver(World* inWorld) { return SC_BelaDriver::Construct(inWorld); } SC_BelaDriver* SC_BelaDriver::Construct(World* inWorld) { if (s_instance != nullptr) { scprintf("*** ERROR: Asked to construct a second instance of SC_BelaDriver.\n"); std::exit(1); } s_instance = new SC_BelaDriver(inWorld); return s_instance; } SC_BelaDriver::SC_BelaDriver(World* inWorld): SC_AudioDriver(inWorld), mSCBufLength(inWorld->mBufLength) { mStartHostSecs = 0; } SC_BelaDriver::~SC_BelaDriver() { // Clean up any resources allocated for audio Bela_cleanupAudio(); scprintf("SC_BelaDriver: >>Bela_cleanupAudio\n"); s_instance = nullptr; delete mWorld->mBelaScope; mWorld->mBelaScope = nullptr; } // Return true on success; returning false halts the program. bool SC_BelaDriver::BelaSetup(const BelaContext* belaContext) { mBelaSampleRate = belaContext->audioSampleRate; delete mWorld->mBelaScope; mWorld->mBelaScope = nullptr; if (mWorld->mBelaMaxScopeChannels > 0) mWorld->mBelaScope = new BelaScope(mWorld->mBelaMaxScopeChannels, mBelaSampleRate, belaContext->audioFrames); return true; } // Defined in SC_World.cpp void sc_SetDenormalFlags(); void SC_BelaDriver::BelaAudioCallback(BelaContext* belaContext) { struct timespec tspec; sc_SetDenormalFlags(); // add a pointer to belaWorld mWorld->mBelaContext = belaContext; // NOTE: code here is adapted from the SC_Jack.cpp, the version not using the DLL // Use Xenomai-friendly clock_gettime() __wrap_clock_gettime(CLOCK_HOST_REALTIME, &tspec); double hostSecs = static_cast<double>(tspec.tv_sec) + static_cast<double>(tspec.tv_nsec) * 1.0e-9; double sampleTime = static_cast<double>(belaContext->audioFramesElapsed); if (mStartHostSecs == 0) { mStartHostSecs = hostSecs; mStartSampleTime = sampleTime; } else { double instSampleRate = (sampleTime - mPrevSampleTime) / (hostSecs - mPrevHostSecs); double smoothSampleRate = mSmoothSampleRate; smoothSampleRate = smoothSampleRate + 0.002 * (instSampleRate - smoothSampleRate); if (fabs(smoothSampleRate - mSampleRate) > 10.) { smoothSampleRate = mSampleRate; } mOSCincrement = static_cast<int64>(mOSCincrementNumerator / smoothSampleRate); mSmoothSampleRate = smoothSampleRate; } mPrevHostSecs = hostSecs; mPrevSampleTime = sampleTime; try { mFromEngine.Free(); mToEngine.Perform(); mOscPacketsToEngine.Perform(); const uint32_t numInputs = belaContext->audioInChannels; const uint32_t numOutputs = belaContext->audioOutChannels; int numSamples = NumSamplesPerCallback(); int bufFrames = mWorld->mBufLength; int numBufs = numSamples / bufFrames; float* inBuses = mWorld->mAudioBus + mWorld->mNumOutputs * bufFrames; float* outBuses = mWorld->mAudioBus; int minInputs = sc_min(numInputs, mWorld->mNumInputs); int minOutputs = sc_min(numOutputs, mWorld->mNumOutputs); int anaInputs = 0; if (numInputs < mWorld->mNumInputs) { anaInputs = sc_min(belaContext->analogInChannels, static_cast<int>(mWorld->mNumInputs - numInputs)); } int anaOutputs = 0; if (numOutputs < mWorld->mNumOutputs) { anaOutputs = sc_min(belaContext->analogOutChannels, static_cast<int>(mWorld->mNumOutputs - numOutputs)); } // main loop mOSCbuftime = (static_cast<int64>(tspec.tv_sec + kSECONDS_FROM_1900_to_1970) << 32) + static_cast<int64>(tspec.tv_nsec * kNanosToOSCunits); // clear out anything left over in audioOut buffer for (int i = 0; i < belaContext->audioFrames * belaContext->audioOutChannels; i++) { belaContext->audioOut[i] = 0; } for (int i = 0; i < numBufs; ++i, mWorld->mBufCounter++) { // copy+touch inputs int32* tch = mWorld->mAudioBusTouched + mWorld->mNumOutputs; std::memcpy(inBuses, belaContext->audioIn, sizeof(belaContext->audioIn[0]) * bufFrames * minInputs); for (int k = 0; k < minInputs; ++k) { *tch++ = mWorld->mBufCounter; } std::memcpy(inBuses + minInputs * bufFrames, belaContext->analogIn, sizeof(belaContext->analogIn[0]) * bufFrames * anaInputs); for (int k = minInputs; k < (minInputs + anaInputs); ++k) { *tch++ = mWorld->mBufCounter; } // run engine int64 schedTime; int64 nextTime = mOSCbuftime + mOSCincrement; while ((schedTime = mScheduler.NextTime()) <= nextTime) { float diffTime = static_cast<float>(schedTime - mOSCbuftime) * mOSCtoSamples + 0.5; float diffTimeFloor = std::floor(diffTime); mWorld->mSampleOffset = static_cast<int>(diffTimeFloor); mWorld->mSubsampleOffset = diffTime - diffTimeFloor; if (mWorld->mSampleOffset < 0) mWorld->mSampleOffset = 0; else if (mWorld->mSampleOffset >= mWorld->mBufLength) mWorld->mSampleOffset = mWorld->mBufLength - 1; SC_ScheduledEvent event = mScheduler.Remove(); event.Perform(); } mWorld->mSampleOffset = 0; mWorld->mSubsampleOffset = 0.f; World_Run(mWorld); // copy touched outputs tch = mWorld->mAudioBusTouched; for (int k = 0; k < minOutputs; ++k) { if (*tch++ == mWorld->mBufCounter) { std::memcpy(belaContext->audioOut + k * bufFrames, outBuses + k * bufFrames, sizeof(belaContext->audioOut[0]) * bufFrames); } } for (int k = minOutputs; k < (minOutputs + anaOutputs); ++k) { if (*tch++ == mWorld->mBufCounter) { unsigned int analogChannel = k - minOutputs; // starting at 0 std::memcpy(belaContext->analogOut + analogChannel * bufFrames, outBuses + k * bufFrames, sizeof(belaContext->analogOut[0]) * bufFrames); } } // advance OSC time mOSCbuftime = nextTime; } if (mWorld->mBelaScope) mWorld->mBelaScope->logBuffer(); } catch (std::exception& exc) { scprintf("SC_BelaDriver: exception in real time: %s\n", exc.what()); } catch (...) { scprintf("SC_BelaDriver: unknown exception in real time\n"); } mAudioSync.Signal(); } // ==================================================================== bool SC_BelaDriver::DriverSetup(int* outNumSamples, double* outSampleRate) { BelaInitSettings* settings = Bela_InitSettings_alloc(); Bela_defaultSettings(settings); settings->setup = [](BelaContext* belaContext, void* userData) { return static_cast<SC_BelaDriver*>(userData)->BelaSetup(belaContext); }; settings->render = [](BelaContext* belaContext, void* userData) { static_cast<SC_BelaDriver*>(userData)->BelaAudioCallback(belaContext); }; // add a callback to be called when the audio thread stops. This is useful // e.g.: to gracefully exit from scsynth when pressing the Bela button settings->audioThreadDone = [](BelaContext*, void* userData) { auto* driver = static_cast<SC_BelaDriver*>(userData); if (driver) driver->SignalReceived(0); }; settings->interleave = 0; settings->uniformSampleRate = 1; settings->analogOutputsPersist = 0; if (mPreferredHardwareBufferFrameSize) { settings->periodSize = mPreferredHardwareBufferFrameSize; } if (settings->periodSize != mSCBufLength) { scprintf("Warning in SC_BelaDriver::DriverSetup(): hardware buffer size (%i) different from SC audio buffer " "size (%i). Changed the hardware buffer size to be equal to the SC audio buffer size .\n", settings->periodSize, mSCBufLength); settings->periodSize = mSCBufLength; } // note that Bela doesn't give us an option to choose samplerate, since // it's baked-in for a given board, however this can be retrieved in sc_belaSetup() // configure the number of analog channels - this will determine their internal samplerate settings->useAnalog = 0; // explicitly requested number of analog channels int numAnalogIn = mWorld->hw->mBelaAnalogInputChannels; int numAnalogOut = mWorld->hw->mBelaAnalogOutputChannels; // Here is the deal. We need to know: // - how many real audio channels are available // - how many audio channels the user wants // - how many analog channels are available // before we can request Bela for: // - a given number of analog channels // - applying the audio expander capelet on these channels // Currently (as of 1.4.0) the Bela API does not allow to // know the number of audio channels available. BelaHwConfig* cfg = Bela_HwConfig_new(Bela_detectHw()); int extraAudioIn = mWorld->mNumInputs - cfg->audioInChannels; int extraAudioOut = mWorld->mNumOutputs - cfg->audioOutChannels; // if we need more audio channels than there actually are audio // channels, make sure we have some extra analogs if (extraAudioIn > 0) { numAnalogIn = sc_max(numAnalogIn, extraAudioIn); } if (extraAudioOut > 0) { numAnalogOut = sc_max(numAnalogOut, extraAudioOut); } // snap the number of requested analog channels to the 0, 4, 8. // 4 will give same actual sample rate as audio, 8 will give half of it. if (numAnalogIn > 0) { if (numAnalogIn < 5) { numAnalogIn = 4; } else { numAnalogIn = 8; } } if (numAnalogOut > 0) { if (numAnalogOut < 5) { numAnalogOut = 4; } else { numAnalogOut = 8; } } // final check: right now the number of analog output channels on bela needs to be the same as analog input // channels. this is likely to change in the future, that is why we factored it out if (numAnalogOut != numAnalogIn) { // Chosing the maximum of the two numAnalogOut = sc_max(numAnalogOut, numAnalogIn); numAnalogIn = numAnalogOut; scprintf("Number of analog input channels must match number of analog outputs. Using %u for both\n", numAnalogIn); } settings->numAnalogInChannels = numAnalogIn; settings->numAnalogOutChannels = numAnalogOut; if (settings->numAnalogInChannels > 0 || settings->numAnalogOutChannels > 0) { settings->useAnalog = 1; } // enable the audio expander capelet for the first few "analog as audio" channels // inputs and ... for (int n = 0; n < extraAudioIn; ++n) { scprintf("Using analog in %d as audio in %d\n", n, n + cfg->audioInChannels); settings->audioExpanderInputs |= (1 << n); } // ... outputs for (int n = 0; n < extraAudioOut; ++n) { scprintf("Using analog out %d as audio out %d\n", n, n + cfg->audioOutChannels); settings->audioExpanderOutputs |= (1 << n); } // configure the number of digital channels settings->useDigital = 0; if (mWorld->hw->mBelaDigitalChannels > 0) { settings->numDigitalChannels = mWorld->hw->mBelaDigitalChannels; settings->useDigital = 1; } if ((mWorld->hw->mBelaHeadphoneLevel >= -63.5) && (mWorld->hw->mBelaHeadphoneLevel <= 0.)) { // headphone output level (0dB max; -63.5dB min) settings->headphoneLevel = mWorld->hw->mBelaHeadphoneLevel; } if ((mWorld->hw->mBelaPgaGainLeft >= 0) && (mWorld->hw->mBelaPgaGainLeft <= 59.5)) { // (0db min; 59.5db max) settings->pgaGain[0] = mWorld->hw->mBelaPgaGainLeft; } if ((mWorld->hw->mBelaPgaGainRight >= 0) && (mWorld->hw->mBelaPgaGainRight <= 59.5)) { // (0db min; 59.5db max) settings->pgaGain[1] = mWorld->hw->mBelaPgaGainRight; } if (mWorld->hw->mBelaSpeakerMuted) { settings->beginMuted = 1; } else { settings->beginMuted = 0; } if ((mWorld->hw->mBelaDacLevel >= -63.5) && (mWorld->hw->mBelaDacLevel <= 0.)) { // (0dB max; -63.5dB min) settings->dacLevel = mWorld->hw->mBelaDacLevel; } if ((mWorld->hw->mBelaAdcLevel >= -12) && (mWorld->hw->mBelaAdcLevel <= 0.)) { // (0dB max; -12dB min) settings->adcLevel = mWorld->hw->mBelaAdcLevel; } settings->numMuxChannels = mWorld->hw->mBelaNumMuxChannels; if ((mWorld->hw->mBelaPru == 0) || (mWorld->hw->mBelaPru == 1)) { settings->pruNumber = mWorld->hw->mBelaPru; } scprintf("SC_BelaDriver: >>DriverSetup - Running on PRU (%i)\nConfigured with \n (%i) analog input and (%i) analog " "output channels, (%i) digital channels, and (%i) multiplexer channels.\n HeadphoneLevel (%f dB), " "pga_gain_left (%f dB) and pga_gain_right (%f dB)\n DAC Level (%f dB), ADC Level (%f dB) " "oscilloscope channels (%i)\n", settings->pruNumber, settings->numAnalogInChannels, settings->numAnalogOutChannels, settings->numDigitalChannels, settings->numMuxChannels, settings->headphoneLevel, settings->pgaGain[0], settings->pgaGain[1], settings->dacLevel, settings->adcLevel, mWorld->mBelaMaxScopeChannels); if (settings->beginMuted == 1) { scprintf("Speakers are muted.\n"); } else { scprintf("Speakers are not muted.\n"); } settings->verbose = mWorld->mVerbosity; // This call will initialise the rendering system, which in the process // will result in a call to the user-defined setup() function. if (Bela_initAudio(settings, this) != 0) { scprintf("Error in SC_BelaDriver::DriverSetup(): unable to initialise audio\n"); return false; } *outNumSamples = settings->periodSize; *outSampleRate = mBelaSampleRate; Bela_InitSettings_free(settings); Bela_HwConfig_delete(cfg); // Set up interrupt handler to catch Control-C and SIGTERM auto signalFunc = [](int signal) { if (SC_BelaDriver::s_instance != nullptr) SC_BelaDriver::s_instance->SignalReceived(signal); }; signal(SIGINT, signalFunc); signal(SIGTERM, signalFunc); return true; } bool SC_BelaDriver::DriverStart() { SetPrintFunc(rt_vprintf); // Use Xenomai's realtime-friendly printing function if (Bela_startAudio()) { scprintf("Error in SC_BelaDriver::DriverStart(): unable to start real-time audio\n"); return false; } return true; } bool SC_BelaDriver::DriverStop() { Bela_stopAudio(); return true; } void SC_BelaDriver::SignalReceived(int signal) { scprintf("SC_BelaDriver: signal received: %d; terminating\n", signal); mWorld->hw->mTerminating = true; mWorld->hw->mQuitProgram->post(); }
17,809
C++
.cpp
381
39.433071
120
0.657098
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
29,916
SC_CoreAudio.cpp
supercollider_supercollider/server/scsynth/SC_CoreAudio.cpp
/* 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_SequencedCommand.h" #include "SC_Prototypes.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include "SC_Endian.h" #include "SC_Lib_Cintf.h" #include "SC_Lock.h" #include "SC_Time.hpp" #include "SC_InlineBinaryOp.h" #include <stdlib.h> #include <algorithm> #ifndef _WIN32 # include <sys/time.h> #endif #ifdef SC_IPHONE # include "SC_VFP11.h" #endif #include "nova-tt/thread_priority.hpp" int64 gStartupOSCTime = -1; double gSampleRate, gSampleDur; void sc_SetDenormalFlags(); // ===================================================================== // Timing (CoreAudio) #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIO || SC_AUDIO_API == SC_AUDIO_API_AUDIOUNITS int64 gOSCoffset = 0; int32 server_timeseed() { static int32 count = 0; int64 time = AudioGetCurrentHostTime(); return (int32)(time >> 32) ^ (int32)time ^ count--; } inline int64 CoreAudioHostTimeToOSC(int64 hostTime) { return (int64)((double)AudioConvertHostTimeToNanos(hostTime) * kNanosToOSCunits) + gOSCoffset; } int64 oscTimeNow() { return CoreAudioHostTimeToOSC(AudioGetCurrentHostTime()); } static void syncOSCOffsetWithTimeOfDay() { // generate a value gOSCoffset such that // (gOSCOffset + systemTimeInOSCunits) // is equal to gettimeofday time in OSCunits. // Then if this machine is synced via NTP, we are synced with the world. // more accurate way to do this?? struct timeval tv; int64 systemTimeBefore, systemTimeAfter; int64 diff, minDiff = 0x7fffFFFFffffFFFFLL; // take best of several tries const int numberOfTries = 5; int64 newOffset = gOSCoffset; for (int i = 0; i < numberOfTries; ++i) { systemTimeBefore = AudioGetCurrentHostTime(); gettimeofday(&tv, 0); systemTimeAfter = AudioGetCurrentHostTime(); diff = systemTimeAfter - systemTimeBefore; if (diff < minDiff) { minDiff = diff; // assume that gettimeofday happens halfway between AudioGetCurrentHostTime() calls int64 systemTimeBetween = systemTimeBefore + diff / 2; int64 systemTimeInOSCunits = (int64)((double)AudioConvertHostTimeToNanos(systemTimeBetween) * kNanosToOSCunits); int64 timeOfDayInOSCunits = ((int64)(tv.tv_sec + kSECONDS_FROM_1900_to_1970) << 32) + (int64)(tv.tv_usec * kMicrosToOSCunits); newOffset = timeOfDayInOSCunits - systemTimeInOSCunits; } } gOSCoffset = newOffset; // scprintf("gOSCoffset %016llX\n", gOSCoffset); } static void resyncThreadFunc() { /* keep the default thread priority */ while (true) { sleep(20); syncOSCOffsetWithTimeOfDay(); } } void initializeScheduler() { syncOSCOffsetWithTimeOfDay(); SC_Thread resyncThread(resyncThreadFunc); resyncThread.detach(); } #endif // SC_AUDIO_API_COREAUDIO // ===================================================================== // Timing (CoreAudioIPHONE) #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIOIPHONE int64 gOSCoffset = 0; static inline int64 GetMicroseconds() { struct timeval tv; gettimeofday(&tv, 0); return (int64)tv.tv_sec * 1000000 + tv.tv_usec; } static inline int64 GetCurrentOSCTime() { struct timeval tv; uint64 s, f; gettimeofday(&tv, 0); s = (uint64)tv.tv_sec + (uint64)kSECONDS_FROM_1900_to_1970; f = (uint64)((double)tv.tv_usec * kMicrosToOSCunits); return (s << 32) + f; } int32 server_timeseed() { int64 time = GetCurrentOSCTime(); return Hash((int32)(time >> 32) + Hash((int32)time)); } int64 oscTimeNow() { return GetCurrentOSCTime(); } void initializeScheduler() { gOSCoffset = GetCurrentOSCTime(); } #endif // SC_AUDIO_API_COREAUDIO // ===================================================================== // Packets (Common) bool ProcessOSCPacket(World* inWorld, OSC_Packet* inPacket); void PerformOSCBundle(World* inWorld, OSC_Packet* inPacket); int PerformOSCMessage(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); PacketStatus PerformOSCPacket(World* world, OSC_Packet* packet, SC_ScheduledEvent::PacketFreeFunc); void Perform_ToEngine_Msg(FifoMsg* inMsg); void FreeOSCPacket(FifoMsg* inMsg); struct IsBundle { IsBundle() { str4cpy(s, "#bundle"); } bool checkIsBundle(int32* in) { return in[0] == s[0] && in[1] == s[1]; } int32 s[2]; }; IsBundle gIsBundle; bool ProcessOSCPacket(World* inWorld, OSC_Packet* inPacket) { // scprintf("ProcessOSCPacket %d, '%s'\n", inPacket->mSize, inPacket->mData); if (!inPacket) return false; bool result; static_cast<SC_Lock*>(inWorld->mDriverLock)->lock(); SC_AudioDriver* driver = AudioDriver(inWorld); if (!driver) { static_cast<SC_Lock*>(inWorld->mDriverLock)->unlock(); return false; } inPacket->mIsBundle = gIsBundle.checkIsBundle((int32*)inPacket->mData); FifoMsg fifoMsg; fifoMsg.Set(inWorld, Perform_ToEngine_Msg, FreeOSCPacket, (void*)inPacket); result = driver->SendOscPacketMsgToEngine(fifoMsg); static_cast<SC_Lock*>(inWorld->mDriverLock)->unlock(); if (!result) scprintf("command FIFO full\n"); return result; } int PerformOSCMessage(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { // scprintf("->PerformOSCMessage %d\n", inData[0]); SC_LibCmd* cmdObj; int cmdNameLen; if (inData[0] == 0) { cmdNameLen = 4; uint32 index = inData[3]; if (index >= NUMBER_OF_COMMANDS) cmdObj = nullptr; else cmdObj = gCmdArray[index]; } else { cmdNameLen = OSCstrlen(inData); cmdObj = gCmdLib->Get((int32*)inData); } if (!cmdObj) { CallSendFailureCommand(inWorld, inData, "Command not found", inReply); scprintf("FAILURE IN SERVER: %s Command not found\n", inData); return kSCErr_NoSuchCommand; } int err = cmdObj->Perform(inWorld, inSize - cmdNameLen, inData + cmdNameLen, inReply); // scprintf("<-PerformOSCMessage %d\n", inData[0]); return err; } void PerformOSCBundle(World* inWorld, OSC_Packet* inPacket) { // scprintf("->PerformOSCBundle %d\n", inPacket->mSize); char* data = inPacket->mData + 16; char* dataEnd = inPacket->mData + inPacket->mSize; while (data < dataEnd) { int32 msgSize = sc_ntohl(*(int32*)data); data += sizeof(int32); // scprintf("msgSize %d\n", msgSize); PerformOSCMessage(inWorld, msgSize, data, &inPacket->mReplyAddr); data += msgSize; } // reset so next command uses permanent error notification status inWorld->mLocalErrorNotification = 0; // scprintf("<-PerformOSCBundle %d\n", inPacket->mSize); } PacketStatus PerformOSCPacket(World* world, OSC_Packet* packet, SC_ScheduledEvent::PacketFreeFunc freeFunc) { SC_AudioDriver* driver = world->hw->mAudioDriver; if (!packet->mIsBundle) { PerformOSCMessage(world, packet->mSize, packet->mData, &packet->mReplyAddr); world->mLocalErrorNotification = 0; return PacketPerformed; } else { // in real time engine, schedule the packet int64 time = OSCtime(packet->mData + 8); if (time == 0 || time == 1) { PerformOSCBundle(world, packet); return PacketPerformed; } else { if ((time < driver->mOSCbuftime) && (world->mVerbosity >= 0)) { double seconds = (driver->mOSCbuftime - time) * kOSCtoSecs; scprintf("late %.9f\n", seconds); // FifoMsg outMsg; // ReportLateness(packet->mReply, seconds) } // DEBUG // else // scprintf("scheduled in %.6f at time %.6f\n", // (time-driver->mOSCbuftime)*kOSCtoSecs, // (time-gStartupOSCTime)*kOSCtoSecs); SC_ScheduledEvent event(world, time, packet, freeFunc); driver->AddEvent(event); return PacketScheduled; } } } //////////////////////////////////////////////////////////////////////////// void Perform_ToEngine_Msg(FifoMsg* inMsg) { World* world = inMsg->mWorld; OSC_Packet* packet = (OSC_Packet*)inMsg->mData; if (!packet) return; PacketStatus status = PerformOSCPacket(world, packet, SC_ScheduledEvent::FreeInNRT); if (status == PacketScheduled) { // Transfer ownership inMsg->mData = nullptr; inMsg->mFreeFunc = nullptr; } } PacketStatus PerformCompletionMsg(World* inWorld, const OSC_Packet& inPacket) { OSC_Packet* packet = (OSC_Packet*)World_Alloc(inWorld, sizeof(OSC_Packet)); if (packet == NULL) throw std::runtime_error("PerformCompletionMsg allocation failed: out of memory!\n"); *packet = inPacket; packet->mIsBundle = gIsBundle.checkIsBundle((int32*)packet->mData); PacketStatus status = PerformOSCPacket(inWorld, packet, SC_ScheduledEvent::FreeInRT); if (status == PacketPerformed) { World_Free(inWorld, packet); } return status; } void FreeOSCPacket(FifoMsg* inMsg) { OSC_Packet* packet = (OSC_Packet*)inMsg->mData; if (packet) { inMsg->mData = nullptr; #if _MSC_VER == 1310 # pragma message("$$$todo fixme hack for the 'uninitialized packet->mData ptr when using MSVC 7.1 debug") if (packet->mData != reinterpret_cast<char*>(0xcdcdcdcd)) free(packet->mData); #else //#ifdef _MSC_VER free(packet->mData); #endif //#ifdef _MSC_VER free(packet); } } void Free_FromEngine_Msg(FifoMsg* inMsg); void Free_FromEngine_Msg(FifoMsg* inMsg) { World_Free(inMsg->mWorld, inMsg->mData); } // ===================================================================== // Audio driver (Common) SC_AudioDriver::SC_AudioDriver(struct World* inWorld): mWorld(inWorld), mSampleTime(0), mNumSamplesPerCallback(0), mSafetyClipThreshold(1.26) {} SC_AudioDriver::~SC_AudioDriver() { mRunThreadFlag = false; mAudioSync.Signal(); mThread.join(); } void SC_AudioDriver::RunThread() { /* NB: on macOS we just keep the default thread priority */ #ifdef NOVA_TT_PRIORITY_RT int priority = nova::thread_priority_interval_rt().first; nova::thread_set_priority_rt(priority); #endif TriggersFifo* trigfifo = &mWorld->hw->mTriggers; NodeReplyFifo* nodereplyfifo = &mWorld->hw->mNodeMsgs; NodeEndsFifo* nodeendfifo = &mWorld->hw->mNodeEnds; DeleteGraphDefsFifo* deletegraphfifo = &mWorld->hw->mDeleteGraphDefs; while (mRunThreadFlag) { // wait for sync mAudioSync.WaitNext(); #ifdef SC_BELA rt_print_flush_buffers(); #endif // SC_BELA reinterpret_cast<SC_Lock*>(mWorld->mNRTLock)->lock(); // send /tr messages trigfifo->Perform(); // send node reply messages nodereplyfifo->Perform(); // send node status messages nodeendfifo->Perform(); // free GraphDefs deletegraphfifo->Perform(); // perform messages mFromEngine.Perform(); reinterpret_cast<SC_Lock*>(mWorld->mNRTLock)->unlock(); } } bool SC_AudioDriver::SendMsgFromEngine(FifoMsg& inMsg) { return mFromEngine.Write(inMsg); } bool SC_AudioDriver::SendMsgToEngine(FifoMsg& inMsg) { mToEngine.Free(); return mToEngine.Write(inMsg); } bool SC_AudioDriver::SendOscPacketMsgToEngine(FifoMsg& inMsg) { mOscPacketsToEngine.Free(); return mOscPacketsToEngine.Write(inMsg); } void SC_ScheduledEvent::FreeInRT(struct World* world, OSC_Packet* packet) { World_Free(world, packet->mData); World_Free(world, packet); } void SC_ScheduledEvent::FreeInNRT(struct World* world, OSC_Packet* packet) { FifoMsg msg; msg.Set(world, FreeOSCPacket, nullptr, (void*)packet); world->hw->mAudioDriver->SendMsgFromEngine(msg); } void SC_ScheduledEvent::Perform() { PerformOSCBundle(mWorld, mPacket); (*mPacketFreeFunc)(mWorld, mPacket); } bool SC_AudioDriver::Setup() { mRunThreadFlag = true; SC_Thread thread(std::bind(&SC_AudioDriver::RunThread, this)); mThread = std::move(thread); int numSamples; double sampleRate; if (!DriverSetup(&numSamples, &sampleRate)) return false; mNumSamplesPerCallback = numSamples; // scprintf("mNumSamplesPerCallback %d\n", mNumSamplesPerCallback); // scprintf("mHardwareBufferSize %lu\n", mHardwareBufferSize); // compute a per sample increment to the OpenSoundControl Time mOSCincrementNumerator = (double)mWorld->mBufLength * pow(2., 32.); mOSCincrement = (int64)(mOSCincrementNumerator / sampleRate); mOSCtoSamples = sampleRate / pow(2., 32.); World_SetSampleRate(mWorld, sampleRate); mSampleRate = mSmoothSampleRate = sampleRate; mBuffersPerSecond = sampleRate / mNumSamplesPerCallback; mMaxPeakCounter = (int)mBuffersPerSecond; if (mWorld->mVerbosity >= 0) { scprintf("SC_AudioDriver: sample rate = %f, driver's block size = %d\n", sampleRate, mNumSamplesPerCallback); } return true; } bool SC_AudioDriver::Start() { mAvgCPU = 0.; mPeakCPU = 0.; mPeakCounter = 0; mStartHostSecs = 0.; mPrevHostSecs = 0.; mStartSampleTime = 0.; mPrevSampleTime = 0.; World_Start(mWorld); gStartupOSCTime = oscTimeNow(); return DriverStart(); } bool SC_AudioDriver::Stop() { if (!DriverStop()) return false; return true; } // ===================================================================== // Audio driver (CoreAudio) #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIO SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld) { return new SC_CoreAudioDriver(inWorld); } #endif #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIO || SC_AUDIO_API == SC_AUDIO_API_AUDIOUNITS SC_CoreAudioDriver::SC_CoreAudioDriver(struct World* inWorld): SC_AudioDriver(inWorld), mInputBufList(0) {} SC_CoreAudioDriver::~SC_CoreAudioDriver() { if (mInputBufList) { int i; for (i = 0; i < mInputBufList->mNumberBuffers; i++) { free(mInputBufList->mBuffers[i].mData); } free(mInputBufList); } } std::vector<AudioValueRange> GetAvailableNominalSampleRates(const AudioDeviceID& device) { std::vector<AudioValueRange> result; OSStatus err; UInt32 size; UInt32 count; std::unique_ptr<AudioValueRange[]> validSampleRateRanges; AudioObjectPropertyAddress addr = { kAudioDevicePropertyAvailableNominalSampleRates, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; err = AudioObjectGetPropertyDataSize(device, &addr, 0, NULL, &size); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyAvailableNominalSampleRates data size error %4.4s\n", (char*)&err); } else { if (size > 0) { count = size / sizeof(AudioValueRange); validSampleRateRanges = std::unique_ptr<AudioValueRange[]>(new AudioValueRange[count]); err = AudioObjectGetPropertyData(device, &addr, 0, NULL, &size, validSampleRateRanges.get()); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyAvailableNominalSampleRates error %4.4s\n", (char*)&err); } else { for (int i = 0; i < count; i++) { result.push_back(validSampleRateRanges[i]); } } } } return result; } bool SC_CoreAudioDriver::DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate) { OSStatus err = kAudioHardwareNoError; UInt32 count; mOutputDevice = kAudioDeviceUnknown; mInputDevice = kAudioDeviceUnknown; AudioObjectPropertyAddress propertyAddress; propertyAddress.mSelector = kAudioHardwarePropertyDevices; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; // scprintf("SC_CoreAudioDriver::Setup world %p\n", mWorld); //////////////////////////////////////////////////////////////////////////////////////////////// do { // err = AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices, &count, 0); propertyAddress.mSelector = kAudioHardwarePropertyDevices; err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count); if (err != noErr) { scprintf("get kAudioHardwarePropertyDevices error %4.4s\n", (char*)&err); break; } AudioDeviceID* devices = (AudioDeviceID*)malloc(count); // err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &count, devices); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count, devices); if (err != kAudioHardwareNoError) { scprintf("get kAudioHardwarePropertyDevices error %4.4s\n", (char*)&err); free(devices); break; } int numdevices = count / sizeof(AudioDeviceID); if (mWorld->mVerbosity >= 0) { scprintf("Number of Devices: %d\n", numdevices); } for (int i = 0; i < numdevices; ++i) { propertyAddress.mSelector = kAudioDevicePropertyDeviceName; // err = AudioDeviceGetPropertyInfo(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, 0); err = AudioObjectGetPropertyDataSize(devices[i], &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyDeviceName error %4.4s A %d %p\n", (char*)&err, i, devices[i]); break; } char* name = (char*)malloc(count); // err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, name); err = AudioObjectGetPropertyData(devices[i], &propertyAddress, 0, NULL, &count, name); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyDeviceName error %4.4s A %d %p\n", (char*)&err, i, devices[i]); free(name); break; } if (mWorld->mVerbosity >= 0) { scprintf(" %d : \"%s\"\n", i, name); } free(name); } free(devices); if (mWorld->mVerbosity >= 0) { scprintf("\n"); } } while (false); if (mWorld->hw->mInDeviceName || mWorld->hw->mOutDeviceName) { propertyAddress.mSelector = kAudioHardwarePropertyDevices; // err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &count, 0); err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioHardwarePropertyDevices error %4.4s\n", (char*)&err); return false; } AudioDeviceID* devices = (AudioDeviceID*)malloc(count); // err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &count, devices); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count, devices); if (err != kAudioHardwareNoError) { scprintf("get kAudioHardwarePropertyDevices error %4.4s\n", (char*)&err); return false; } int numdevices = count / sizeof(AudioDeviceID); for (int i = 0; i < numdevices; ++i) { // err = AudioDeviceGetPropertyInfo(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, 0); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; err = AudioObjectGetPropertyDataSize(devices[i], &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyDeviceName error %4.4s B %d %p\n", (char*)&err, i, devices[i]); break; } char* name = (char*)malloc(count); // err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &count, name); err = AudioObjectGetPropertyData(devices[i], &propertyAddress, 0, NULL, &count, name); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyDeviceName error %4.4s B %d %p\n", (char*)&err, i, devices[i]); return false; } if (strcmp(name, mWorld->hw->mInDeviceName) == 0) { mInputDevice = devices[i]; } if (strcmp(name, mWorld->hw->mOutDeviceName) == 0) { mOutputDevice = devices[i]; } free(name); if (mInputDevice != kAudioDeviceUnknown && mOutputDevice != kAudioDeviceUnknown) break; } free(devices); if (mOutputDevice == kAudioDeviceUnknown || mInputDevice == kAudioDeviceUnknown) goto getDefault; } else { getDefault: // get the default output device for the HAL if (mOutputDevice == kAudioDeviceUnknown) { count = sizeof(mOutputDevice); // get the output device: // err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) & // mOutputDevice); propertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count, (void*)&mOutputDevice); if (err != kAudioHardwareNoError) { scprintf("get kAudioHardwarePropertyDefaultOutputDevice error %4.4s\n", (char*)&err); return false; } } // get the input device if (mInputDevice == kAudioDeviceUnknown) { count = sizeof(mInputDevice); // err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &count, (void *) & // mInputDevice); propertyAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &count, (void*)&mInputDevice); // get the input device: if (err != kAudioHardwareNoError) { scprintf("get kAudioHardwarePropertyDefaultInputDevice error %4.4s\n", (char*)&err); return false; } } } //////////////////////////////////////////////////////////////////////////////////////////////// AudioTimeStamp now; now.mFlags = kAudioTimeStampHostTimeValid; now.mHostTime = AudioGetCurrentHostTime(); if (mPreferredHardwareBufferFrameSize) { count = sizeof(UInt32); // err = AudioDeviceSetProperty(mOutputDevice, &now, 0, false, kAudioDevicePropertyBufferFrameSize, count, //&mPreferredHardwareBufferFrameSize); propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectSetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, count, &mPreferredHardwareBufferFrameSize); if (err != kAudioHardwareNoError) { scprintf("set kAudioDevicePropertyBufferFrameSize error %4.4s\n", (char*)&err); // return false; } if (UseSeparateIO()) { count = sizeof(UInt32); // err = AudioDeviceSetProperty(mOutputDevice, &now, 0, false, kAudioDevicePropertyBufferFrameSize, count, // &mPreferredHardwareBufferFrameSize); propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectSetPropertyData(mInputDevice, &propertyAddress, 0, NULL, count, &mPreferredHardwareBufferFrameSize); if (err != kAudioHardwareNoError) { scprintf("set kAudioDevicePropertyNominalSampleRate error %4.4s\n", (char*)&err); // return false; } } } if (mPreferredSampleRate) { Float64 sampleRate = mPreferredSampleRate; count = sizeof(Float64); bool sampleRateSupported = false; auto availableSampleRates = GetAvailableNominalSampleRates(mOutputDevice); // If we've got two devices, we need to use a sample rate list from both // This won't account for cases where there are overlapping ranges, but // that seems sufficiently edge-case to ignore for now. if (UseSeparateIO()) { auto inputSampleRates = GetAvailableNominalSampleRates(mInputDevice); std::vector<AudioValueRange> availableSampleRatesInputOutput( std::min(availableSampleRates.size(), inputSampleRates.size())); auto rateListIter = std::set_union(availableSampleRates.begin(), availableSampleRates.end(), inputSampleRates.begin(), inputSampleRates.end(), availableSampleRatesInputOutput.begin(), [](const AudioValueRange& lhs, const AudioValueRange& rhs) { return (lhs.mMaximum != rhs.mMaximum) ? (lhs.mMaximum < rhs.mMaximum) : (lhs.mMinimum < rhs.mMinimum); }); availableSampleRatesInputOutput.resize(rateListIter - availableSampleRatesInputOutput.begin()); availableSampleRates = availableSampleRatesInputOutput; } for (const AudioValueRange& range : availableSampleRates) { if (mPreferredSampleRate >= range.mMinimum && mPreferredSampleRate <= range.mMaximum) { sampleRateSupported = true; break; } } if (!sampleRateSupported) { # define SR_MAX_VALUE 9999999 # define SR_MIN_VALUE -9999999 Float64 nextHighestMatch = SR_MAX_VALUE; Float64 nextLowestMatch = SR_MIN_VALUE; for (const AudioValueRange& range : availableSampleRates) { if (range.mMinimum > mPreferredSampleRate && range.mMinimum < nextHighestMatch) { nextHighestMatch = range.mMinimum; } if (range.mMaximum < mPreferredSampleRate && range.mMaximum > nextLowestMatch) { nextLowestMatch = range.mMaximum; } } if (nextHighestMatch != SR_MAX_VALUE) { sampleRate = nextHighestMatch; sampleRateSupported = true; } else if (nextLowestMatch != SR_MIN_VALUE) { sampleRate = nextLowestMatch; sampleRateSupported = true; } else { sampleRateSupported = false; } if (sampleRateSupported) { scprintf("Requested sample rate %f was not available - attempting to use sample rate of %f\n", (double)mPreferredSampleRate, (double)sampleRate); } else { scprintf("Could not set requested sample rate of %f\n", (double)mPreferredSampleRate); scprintf("Available sample rates:\n"); for (const AudioValueRange& range : availableSampleRates) { if (range.mMaximum == range.mMinimum) { scprintf("\t%f\n", range.mMaximum); } else { scprintf("\t%f - %f\n", range.mMinimum, range.mMaximum); } } } } // Requested sample rate is available - we're going to set and, if we don't hit an error, // assume that our set was successful. if (sampleRateSupported) { bool sampleRateSetSuccess = true; propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectSetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, count, &sampleRate); if (err != kAudioHardwareNoError) { sampleRateSetSuccess = false; scprintf("set kAudioDevicePropertyNominalSampleRate error %4.4s\n", (char*)&err); } if (UseSeparateIO()) { count = sizeof(Float64); propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectSetPropertyData(mInputDevice, &propertyAddress, 0, NULL, count, &sampleRate); if (err != kAudioHardwareNoError) { sampleRateSetSuccess = false; scprintf("set kAudioDevicePropertyNominalSampleRate error %4.4s\n", (char*)&err); } } if (sampleRateSetSuccess) { mExplicitSampleRate = sampleRate; } else { return false; } } } // get the buffersize for the out device count = sizeof(mHardwareBufferSize); // err = AudioDeviceGetProperty(mOutputDevice, 0, false, kAudioDevicePropertyBufferSize, &count, // &mHardwareBufferSize); propertyAddress.mSelector = kAudioDevicePropertyBufferSize; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &count, &mHardwareBufferSize); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyBufferSize error %4.4s\n", (char*)&err); return false; } // scprintf("mHardwareBufferSize = %ld\n", mHardwareBufferSize); // get a description of the data format used by the output device count = sizeof(AudioStreamBasicDescription); // err = AudioDeviceGetProperty(mOutputDevice, 0, false, kAudioDevicePropertyStreamFormat, &count, // &outputStreamDesc); propertyAddress.mSelector = kAudioDevicePropertyStreamFormat; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &count, &outputStreamDesc); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamFormat error %4.4s\n", (char*)&err); return false; } if (mInputDevice != kAudioDeviceUnknown) { // get a description of the data format used by the input device count = sizeof(AudioStreamBasicDescription); // err = AudioDeviceGetProperty(mInputDevice, 0, true, kAudioDevicePropertyStreamFormat, &count, // &inputStreamDesc); propertyAddress.mSelector = kAudioDevicePropertyStreamFormat; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &count, &inputStreamDesc); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamFormat error on input %4.4s\n", (char*)&err); return false; } if ( // We do not support mismatched input and output sample rates, but there's no harm in skipping // this check if numInputBusChannels == 0. This allows the user to disable input entirely as // a workaround for a sample rate mismatch. mWorld->mNumInputs > 0 && !mExplicitSampleRate && inputStreamDesc.mSampleRate != outputStreamDesc.mSampleRate) { scprintf("ERROR: Input sample rate is %g, but output is %g. " "Mismatched sample rates are not supported. " "To disable input, set the number of input channels to 0.\n", inputStreamDesc.mSampleRate, outputStreamDesc.mSampleRate); return false; } } //////////////////////////////////////////////////////////////////////////////////////////////// do { // err = AudioDeviceGetPropertyInfo(mInputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, 0); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectGetPropertyDataSize(mInputDevice, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyDeviceName error %4.4s C %p\n", (char*)&err, mInputDevice); break; } char* name = (char*)malloc(count); // err = AudioDeviceGetProperty(mInputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, name); err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &count, name); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyDeviceName error %4.4s C %p\n", (char*)&err, mInputDevice); free(name); break; } if (mWorld->mVerbosity >= 0) { scprintf("\"%s\" Input Device\n", name); } free(name); Boolean writeable; // err = AudioDeviceGetPropertyInfo(mInputDevice, 0, 1, kAudioDevicePropertyStreamConfiguration, &count, // &writeable); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectIsPropertySettable(mInputDevice, &propertyAddress, &writeable); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyStreamConfiguration settable error %4.4s\n", (char*)&err); break; } err = AudioObjectGetPropertyDataSize(mInputDevice, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyStreamConfiguration size error %4.4s\n", (char*)&err); break; } AudioBufferList* bufList = (AudioBufferList*)malloc(count); // err = AudioDeviceGetProperty(mInputDevice, 0, 1, kAudioDevicePropertyStreamConfiguration, &count, bufList); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &count, bufList); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamConfiguration error %4.4s\n", (char*)&err); free(bufList); break; } if (mWorld->mVerbosity >= 0) { scprintf(" Streams: %d\n", bufList->mNumberBuffers); for (unsigned int j = 0; j < bufList->mNumberBuffers; ++j) { scprintf(" %d channels %d\n", j, bufList->mBuffers[j].mNumberChannels); } } free(bufList); } while (false); if (mWorld->mVerbosity >= 0) { scprintf("\n"); } //////////////////////////////////////////////////////////////////////////////////////////////// do { // err = AudioDeviceGetPropertyInfo(mOutputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, 0); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &count); char* name = (char*)malloc(count); // err = AudioDeviceGetProperty(mOutputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, name); err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &count, name); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyDeviceName error %4.4s\n", (char*)&err); free(name); break; } if (mWorld->mVerbosity >= 0) { scprintf("\"%s\" Output Device\n", name); } free(name); Boolean writeable; // err = AudioDeviceGetPropertyInfo(mOutputDevice, 0, 0, kAudioDevicePropertyStreamConfiguration, &count, // &writeable); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectIsPropertySettable(mOutputDevice, &propertyAddress, &writeable); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyStreamConfiguration settable error %4.4s\n", (char*)&err); break; } err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyStreamConfiguration size error %4.4s\n", (char*)&err); break; } AudioBufferList* bufList = (AudioBufferList*)malloc(count); // err = AudioDeviceGetProperty(mOutputDevice, 0, 0, kAudioDevicePropertyStreamConfiguration, &count, bufList); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &count, bufList); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamConfiguration error %4.4s\n", (char*)&err); free(bufList); break; } if (mWorld->mVerbosity >= 0) { scprintf(" Streams: %d\n", bufList->mNumberBuffers); for (unsigned int j = 0; j < bufList->mNumberBuffers; ++j) { scprintf(" %d channels %d\n", j, bufList->mBuffers[j].mNumberChannels); } } free(bufList); } while (false); if (mWorld->mVerbosity >= 0) { scprintf("\n"); } //////////////////////////////////////////////////////////////////////////////////////////////// if (UseSeparateIO()) { count = sizeof(UInt32); // err = AudioDeviceGetProperty(mInputDevice, 0, true, kAudioDevicePropertySafetyOffset, &count, // &mSafetyOffset); propertyAddress.mSelector = kAudioDevicePropertySafetyOffset; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &count, &mSafetyOffset); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertySafetyOffset error %4.4s\n", (char*)&err); return false; } if (mWorld->mVerbosity >= 1) { scprintf("mSafetyOffset %lu\n", mSafetyOffset); } Boolean writeable; // err = AudioDeviceGetPropertyInfo(mInputDevice, 0, true, kAudioDevicePropertyStreamConfiguration, &count, //&writeable); propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propertyAddress.mScope = kAudioDevicePropertyScopeInput; err = AudioObjectIsPropertySettable(mInputDevice, &propertyAddress, &writeable); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamConfiguration writeable error %4.4s\n", (char*)&err); return false; } err = AudioObjectGetPropertyDataSize(mInputDevice, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamConfiguration size error %4.4s\n", (char*)&err); return false; } mInputBufList = (AudioBufferList*)malloc(count); // err = AudioDeviceGetProperty(mInputDevice, 0, true, kAudioDevicePropertyStreamConfiguration, &count, // mInputBufList); err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &count, mInputBufList); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyStreamConfiguration error %4.4s\n", (char*)&err); return false; } if (mWorld->mVerbosity >= 1) { scprintf("mNumberBuffers %lu\n", mInputBufList->mNumberBuffers); } for (uint32 i = 0; i < mInputBufList->mNumberBuffers; ++i) { if (mWorld->mVerbosity >= 1) { scprintf(" mDataByteSize %d %lu\n", i, mInputBufList->mBuffers[i].mDataByteSize); } mInputBufList->mBuffers[i].mData = zalloc(1, mInputBufList->mBuffers[i].mDataByteSize); } /* AudioTimeStamp now; now.mFlags = kAudioTimeStampHostTimeValid; now.mHostTime = AudioGetCurrentHostTime(); err = AudioDeviceSetProperty(mInputDevice, &now, 0, true, kAudioDevicePropertyRegisterBufferList, count, mInputBufList); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyRegisterBufferList error %4.4s\n", (char*)&err); return false; } */ } *outNumSamplesPerCallback = mHardwareBufferSize / outputStreamDesc.mBytesPerFrame; if (mExplicitSampleRate) { *outSampleRate = mExplicitSampleRate.get(); } else { *outSampleRate = outputStreamDesc.mSampleRate; } if (mWorld->mVerbosity >= 1) { scprintf("<-SC_CoreAudioDriver::Setup world %p\n", mWorld); } // check if using built-in output, and thus whether there could be headphone plug/un-plug issues // our assumption otherwise is that we don't respond, and SC will stay with the pre-arranged or default device, and // not restart just because headphones switched // err = AudioDeviceGetPropertyInfo(mOutputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, 0); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &count); if (err != kAudioHardwareNoError) { scprintf("info kAudioDevicePropertyDeviceName error %4.4s %p\n", (char*)&err, mOutputDevice); return false; } char* outputname = (char*)malloc(count); const char* testname = "Built-in Output"; // err = AudioDeviceGetProperty(mOutputDevice, 0, false, kAudioDevicePropertyDeviceName, &count, outputname); err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &count, outputname); if (err != kAudioHardwareNoError) { scprintf("get kAudioDevicePropertyDeviceName error %4.4s %p\n", (char*)&err, mOutputDevice); return false; } builtinoutputflag_ = 0; if (strcmp(testname, outputname) == 0) { builtinoutputflag_ = 1; } // else { // // //check for an Aggregate Devices with a subdevice which is Built-in Output // //http://lists.apple.com/archives/coreaudio-api/2009/Oct/msg00182.html // // // } free(outputname); return true; } /* OSStatus appIOProc2 (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr); OSStatus appIOProc2 (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { SC_CoreAudioDriver* def = (SC_CoreAudioDriver*)defptr; int64 oscTime = CoreAudioHostTimeToOSC(inOutputTime->mHostTime); AudioTimeStamp readTime; readTime.mSampleTime = inNow->mSampleTime - def->SafetyOffset() - def->NumSamplesPerCallback(); readTime.mFlags = kAudioTimeStampSampleTimeValid; AudioDeviceRead(def->InputDevice(), &readTime, def->GetInputBufferList()); def->Run(def->GetInputBufferList(), outOutputData, oscTime); return kAudioHardwareNoError; } */ OSStatus appIOProcSeparateIn(AudioDeviceID device, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { SC_CoreAudioDriver* def = (SC_CoreAudioDriver*)defptr; // copy input data to driver's private buffer list int i; for (i = 0; i < inInputData->mNumberBuffers; i++) { memcpy(def->mInputBufList->mBuffers[i].mData, inInputData->mBuffers[i].mData, inInputData->mBuffers[i].mDataByteSize); } return kAudioHardwareNoError; } template <bool IsClipping> OSStatus appIOProc(AudioDeviceID device, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { SC_CoreAudioDriver* def = (SC_CoreAudioDriver*)defptr; int64 oscTime = CoreAudioHostTimeToOSC(inOutputTime->mHostTime); double hostSecs = (double)AudioConvertHostTimeToNanos(inOutputTime->mHostTime) * 1e-9; double sampleTime = inOutputTime->mSampleTime; if (def->mStartHostSecs == 0) { def->mStartHostSecs = hostSecs; def->mStartSampleTime = sampleTime; } else { double instSampleRate = (sampleTime - def->mPrevSampleTime) / (hostSecs - def->mPrevHostSecs); double smoothSampleRate = def->mSmoothSampleRate; smoothSampleRate = smoothSampleRate + 0.002 * (instSampleRate - smoothSampleRate); def->mOSCincrement = (int64)(def->mOSCincrementNumerator / smoothSampleRate); def->mSmoothSampleRate = smoothSampleRate; # if 0 double avgSampleRate = (sampleTime - def->mStartSampleTime)/(hostSecs - def->mStartHostSecs); double jitter = (smoothSampleRate * (hostSecs - def->mPrevHostSecs)) - (sampleTime - def->mPrevSampleTime); double drift = (smoothSampleRate - def->mSampleRate) * (hostSecs - def->mStartHostSecs); //if (fabs(jitter) > 0.01) { scprintf("avgSR %.6f smoothSR %.6f instSR %.6f jitter %.6f drift %.6f inc %lld\n", avgSampleRate, smoothSampleRate, instSampleRate, jitter, drift, def->mOSCincrement); //} # endif } def->mPrevHostSecs = hostSecs; def->mPrevSampleTime = sampleTime; if (!def->UseSeparateIO()) { def->Run<IsClipping>(inInputData, outOutputData, oscTime); return kAudioHardwareNoError; } def->Run<IsClipping>(def->mInputBufList, outOutputData, oscTime); return kAudioHardwareNoError; } template <bool IsClipping> void SC_CoreAudioDriver::Run(const AudioBufferList* inInputData, AudioBufferList* outOutputData, int64 oscTime) { int64 systemTimeBefore = AudioGetCurrentHostTime(); World* world = mWorld; try { int numSamplesPerCallback = NumSamplesPerCallback(); mOSCbuftime = oscTime; # ifdef __APPLE__ // FIXME: aren't denormal flags set per-process? sc_SetDenormalFlags(); # endif mFromEngine.Free(); /*if (mToEngine.HasData()) { scprintf("oscTime %.9f %.9f\n", oscTime*kOSCtoSecs, CoreAudioHostTimeToOSC(AudioGetCurrentHostTime())*kOSCtoSecs); }*/ mToEngine.Perform(); mOscPacketsToEngine.Perform(); int bufFrames = world->mBufLength; int numBufs = numSamplesPerCallback / bufFrames; int numInputBuses = world->mNumInputs; int numOutputBuses = world->mNumOutputs; float* inputBuses = world->mAudioBus + world->mNumOutputs * bufFrames; float* outputBuses = world->mAudioBus; int32* inputTouched = world->mAudioBusTouched + world->mNumOutputs; int32* outputTouched = world->mAudioBusTouched; int numInputStreams = inInputData ? inInputData->mNumberBuffers : 0; int numOutputStreams = outOutputData ? outOutputData->mNumberBuffers : 0; // static int go = 0; int64 oscInc = mOSCincrement; double oscToSamples = mOSCtoSamples; int bufFramePos = 0; for (int i = 0; i < numBufs; ++i, world->mBufCounter++, bufFramePos += bufFrames) { int32 bufCounter = world->mBufCounter; // de-interleave input if (inInputData) { const AudioBuffer* inInputDataBuffers = inInputData->mBuffers; for (int s = 0, b = 0; b < numInputBuses && s < numInputStreams; s++) { const AudioBuffer* buf = inInputDataBuffers + s; int nchan = buf->mNumberChannels; if (buf->mData) { float* busdata = inputBuses + b * bufFrames; float* bufdata = (float*)buf->mData + bufFramePos * nchan; if (nchan == 1) { for (int k = 0; k < bufFrames; ++k) { busdata[k] = bufdata[k]; } inputTouched[b] = bufCounter; } else { int minchan = sc_min(nchan, numInputBuses - b); for (int j = 0; j < minchan; ++j, busdata += bufFrames) { for (int k = 0, m = j; k < bufFrames; ++k, m += nchan) { busdata[k] = bufdata[m]; } inputTouched[b + j] = bufCounter; } } b += nchan; } } } // count++; int64 schedTime; int64 nextTime = oscTime + oscInc; /*if (mScheduler.Ready(nextTime)) { double diff = (mScheduler.NextTime() - mOSCbuftime)*kOSCtoSecs; scprintf("rdy %.9f %.9f %.9f\n", (mScheduler.NextTime()-gStartupOSCTime) * kOSCtoSecs, (mOSCbuftime-gStartupOSCTime)*kOSCtoSecs, diff); }*/ while ((schedTime = mScheduler.NextTime()) <= nextTime) { float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5; float diffTimeFloor = floor(diffTime); world->mSampleOffset = (int)diffTimeFloor; world->mSubsampleOffset = diffTime - diffTimeFloor; if (world->mSampleOffset < 0) world->mSampleOffset = 0; else if (world->mSampleOffset >= world->mBufLength) world->mSampleOffset = world->mBufLength - 1; SC_ScheduledEvent event = mScheduler.Remove(); event.Perform(); } world->mSampleOffset = 0; world->mSubsampleOffset = 0.f; World_Run(world); // interleave output AudioBuffer* outOutputDataBuffers = outOutputData->mBuffers; for (int s = 0, b = 0; b < numOutputBuses && s < numOutputStreams; s++) { AudioBuffer* buf = outOutputDataBuffers + s; int nchan = buf->mNumberChannels; if (buf->mData) { float* busdata = outputBuses + b * bufFrames; float* bufdata = (float*)buf->mData + bufFramePos * nchan; if (nchan == 1) { if (outputTouched[b] == bufCounter) { for (int k = 0; k < bufFrames; ++k) { if (IsClipping) bufdata[k] = sc_clip2(busdata[k], mSafetyClipThreshold); else bufdata[k] = busdata[k]; } } } else { int minchan = sc_min(nchan, numOutputBuses - b); for (int j = 0; j < minchan; ++j, busdata += bufFrames) { if (outputTouched[b + j] == bufCounter) { for (int k = 0, m = j; k < bufFrames; ++k, m += nchan) { if (IsClipping) bufdata[m] = sc_clip2(busdata[k], mSafetyClipThreshold); else bufdata[m] = busdata[k]; } } } } b += nchan; } } oscTime = mOSCbuftime = nextTime; } } catch (std::exception& exc) { scprintf("exception in real time: %s\n", exc.what()); } catch (...) { scprintf("unknown exception in real time\n"); } int64 systemTimeAfter = AudioGetCurrentHostTime(); double calcTime = (double)AudioConvertHostTimeToNanos(systemTimeAfter - systemTimeBefore) * 1e-9; double cpuUsage = calcTime * mBuffersPerSecond * 100.; mAvgCPU = mAvgCPU + 0.1 * (cpuUsage - mAvgCPU); if (cpuUsage > mPeakCPU || --mPeakCounter <= 0) { mPeakCPU = cpuUsage; mPeakCounter = mMaxPeakCounter; } mAudioSync.Signal(); } ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // These are not linked in yet, but we'll need to listen for the properties and stop/restart synthesis // if sample-rate, format, or device change. OSStatus hardwareListenerProc(AudioHardwarePropertyID inPropertyID, void* inClientData) { OSStatus err = noErr; char cStr[255]; UInt32 outSize; Boolean outWritable; AudioDeviceID deviceID; AudioObjectPropertyAddress propertyAddress; propertyAddress.mSelector = kAudioHardwarePropertyDevices; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; switch (inPropertyID) { case kAudioHardwarePropertyDefaultOutputDevice: scprintf("%s\n", "***** HARDWARE NOTIFICATION - kAudioHardwarePropertyDefaultOutputDevice\r"); // err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDefaultOutputDevice, &outSize, &outWritable); propertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(kAudioObjectSystemObject, &propertyAddress, &outWritable); if (err) break; // err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &outSize, &deviceID); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize, &deviceID); if (err) break; // err = AudioDeviceGetPropertyInfo(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, //&outWritable); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; err = AudioObjectGetPropertyDataSize(deviceID, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(deviceID, &propertyAddress, &outWritable); if (err) break; // err = AudioDeviceGetProperty(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, cStr); err = AudioObjectGetPropertyData(deviceID, &propertyAddress, 0, NULL, &outSize, cStr); if (err) break; // do something break; case kAudioHardwarePropertyDefaultInputDevice: scprintf("%s\n", "***** HARDWARE NOTIFICATION - kAudioHardwarePropertyDefaultInputDevice\r"); // err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDefaultInputDevice, &outSize, &outWritable); propertyAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(kAudioObjectSystemObject, &propertyAddress, &outWritable); if (err) break; // err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &outSize, &deviceID); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize, &deviceID); if (err) break; // err = AudioDeviceGetPropertyInfo(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, // &outWritable); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; err = AudioObjectGetPropertyDataSize(deviceID, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(deviceID, &propertyAddress, &outWritable); if (err) break; // err = AudioDeviceGetProperty(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, cStr); err = AudioObjectGetPropertyData(deviceID, &propertyAddress, 0, NULL, &outSize, cStr); if (err) break; // do something break; case kAudioHardwarePropertyDefaultSystemOutputDevice: scprintf("%s\n", "***** HARDWARE NOTIFICATION - kAudioHardwarePropertyDefaultSystemOutputDevice\r"); // err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDefaultSystemOutputDevice, &outSize, // &outWritable); propertyAddress.mSelector = kAudioHardwarePropertyDefaultSystemOutputDevice; err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(kAudioObjectSystemObject, &propertyAddress, &outWritable); if (err) break; // err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultSystemOutputDevice, &outSize, &deviceID); err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &outSize, &deviceID); if (err) break; // err = AudioDeviceGetPropertyInfo(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, // &outWritable); propertyAddress.mSelector = kAudioDevicePropertyDeviceName; err = AudioObjectGetPropertyDataSize(deviceID, &propertyAddress, 0, NULL, &outSize); if (err) break; err = AudioObjectIsPropertySettable(deviceID, &propertyAddress, &outWritable); if (err) break; // err = AudioDeviceGetProperty(deviceID, 0, false, kAudioDevicePropertyDeviceName, &outSize, cStr); err = AudioObjectGetPropertyData(deviceID, &propertyAddress, 0, NULL, &outSize, cStr); if (err) break; // do something break; case kAudioHardwarePropertyDevices: { scprintf("%s\n", "***** HARDWARE NOTIFICATION - kAudioHardwarePropertyDevices\r"); } break; default: scprintf("%s\n", "***** HARDWARE NOTIFICATION - %4.4s\r", &inPropertyID); } fflush(stdout); return (noErr); } OSStatus AddDeviceListeners(AudioDeviceID inDevice, void* inClientData); bool SC_CoreAudioDriver::DriverStart() { if (mWorld->mVerbosity >= 1) { scprintf("->SC_CoreAudioDriver::DriverStart\n"); } auto appIOProcFunc = isClippingEnabled() ? appIOProc<true> : appIOProc<false>; OSStatus err = kAudioHardwareNoError; // AudioTimeStamp now; UInt32 propertySize; Boolean writable; AudioObjectPropertyAddress propertyAddress; propertyAddress.mSelector = kAudioHardwarePropertyDevices; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; if (mWorld->mVerbosity >= 1) { scprintf("start UseSeparateIO?: %d\n", UseSeparateIO()); } try { if (UseSeparateIO()) { // err = AudioDeviceAddIOProc(mOutputDevice, appIOProc, (void *) this); // setup Out device with an // IO proc err = AudioDeviceCreateIOProcID(mOutputDevice, appIOProcFunc, (void*)this, &mOutputID); if (err != kAudioHardwareNoError) { scprintf("AudioDeviceAddIOProc failed %s %d\n", &err, (int)err); return false; } // err = AudioDeviceAddIOProc(mInputDevice, appIOProcSeparateIn, (void *) this); // setup In // device with an IO proc err = AudioDeviceCreateIOProcID(mInputDevice, appIOProcSeparateIn, (void*)this, &mInputID); if (err != kAudioHardwareNoError) { scprintf("AudioDeviceAddIOProc failed %s %d\n", &err, (int)err); return false; } if (mWorld->hw->mInputStreamsEnabled) { propertyAddress.mSelector = kAudioDevicePropertyIOProcStreamUsage; propertyAddress.mScope = kAudioDevicePropertyScopeInput; propertyAddress.mElement = 0; err = AudioObjectGetPropertyDataSize(mInputDevice, &propertyAddress, 0, NULL, &propertySize); err = AudioObjectIsPropertySettable(mInputDevice, &propertyAddress, &writable); AudioHardwareIOProcStreamUsage* su = (AudioHardwareIOProcStreamUsage*)malloc(propertySize); su->mIOProc = (void*)appIOProcSeparateIn; err = AudioObjectGetPropertyData(mInputDevice, &propertyAddress, 0, NULL, &propertySize, su); int len = std::min(su->mNumberStreams, (UInt32)strlen(mWorld->hw->mInputStreamsEnabled)); for (int i = 0; i < len; ++i) { su->mStreamIsOn[i] = mWorld->hw->mInputStreamsEnabled[i] == '1'; } err = AudioObjectSetPropertyData(mInputDevice, &propertyAddress, 0, NULL, propertySize, su); } if (mWorld->hw->mOutputStreamsEnabled) { propertyAddress.mSelector = kAudioDevicePropertyIOProcStreamUsage; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &propertySize); err = AudioObjectIsPropertySettable(mOutputDevice, &propertyAddress, &writable); AudioHardwareIOProcStreamUsage* su = (AudioHardwareIOProcStreamUsage*)malloc(propertySize); su->mIOProc = (void*)appIOProcFunc; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &propertySize, su); int len = std::min(su->mNumberStreams, (UInt32)strlen(mWorld->hw->mOutputStreamsEnabled)); for (int i = 0; i < len; ++i) { su->mStreamIsOn[i] = mWorld->hw->mOutputStreamsEnabled[i] == '1'; } err = AudioObjectSetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, propertySize, su); } err = AudioDeviceStart(mInputDevice, appIOProcSeparateIn); // start playing sound through the device if (err != kAudioHardwareNoError) { scprintf("AudioDeviceStart failed %d\n", (int)err); return false; } err = AudioDeviceStart(mOutputDevice, appIOProcFunc); // start playing sound through the device if (err != kAudioHardwareNoError) { scprintf("AudioDeviceStart failed %d\n", (int)err); err = AudioDeviceStop(mInputDevice, appIOProcSeparateIn); // stop playing sound through the device return false; } } else { // err = AudioDeviceAddIOProc(mOutputDevice, appIOProc, (void *) this); // setup our device with an IO proc err = AudioDeviceCreateIOProcID(mOutputDevice, appIOProcFunc, (void*)this, &mOutputID); if (err != kAudioHardwareNoError) { scprintf("AudioDeviceAddIOProc failed %d\n", (int)err); return false; } if (mWorld->hw->mInputStreamsEnabled) { propertyAddress.mSelector = kAudioDevicePropertyIOProcStreamUsage; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &propertySize); err = AudioObjectIsPropertySettable(mOutputDevice, &propertyAddress, &writable); AudioHardwareIOProcStreamUsage* su = (AudioHardwareIOProcStreamUsage*)malloc(propertySize); su->mIOProc = (void*)appIOProcFunc; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &propertySize, su); int len = std::min(su->mNumberStreams, (UInt32)strlen(mWorld->hw->mInputStreamsEnabled)); for (int i = 0; i < len; ++i) { su->mStreamIsOn[i] = mWorld->hw->mInputStreamsEnabled[i] == '1'; } err = AudioObjectSetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, propertySize, su); } if (mWorld->hw->mOutputStreamsEnabled) { propertyAddress.mSelector = kAudioDevicePropertyIOProcStreamUsage; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; err = AudioObjectGetPropertyDataSize(mOutputDevice, &propertyAddress, 0, NULL, &propertySize); err = AudioObjectIsPropertySettable(mOutputDevice, &propertyAddress, &writable); AudioHardwareIOProcStreamUsage* su = (AudioHardwareIOProcStreamUsage*)malloc(propertySize); su->mIOProc = (void*)appIOProcFunc; err = AudioObjectGetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, &propertySize, su); int len = std::min(su->mNumberStreams, (UInt32)strlen(mWorld->hw->mOutputStreamsEnabled)); for (int i = 0; i < len; ++i) { su->mStreamIsOn[i] = mWorld->hw->mOutputStreamsEnabled[i] == '1'; } err = AudioObjectSetPropertyData(mOutputDevice, &propertyAddress, 0, NULL, propertySize, su); } err = AudioDeviceStart(mOutputDevice, appIOProcFunc); // start playing sound through the device if (err != kAudioHardwareNoError) { scprintf("AudioDeviceStart failed %d\n", (int)err); return false; } } } catch (...) { scprintf("exception in SC_CoreAudioDriver::DriverStart\n"); } if (mWorld->mVerbosity >= 1) { scprintf("<-SC_CoreAudioDriver::DriverStart\n"); } // http://lists.apple.com/archives/coreaudio-api/2010/Aug/msg00114.html CFRunLoopRef theRunLoop = NULL; AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; AudioObjectSetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop); // for now no spotting of hardware changes, assumption is that ServerOptions inviolate. However, if a device was // unplugged, could react to loss of that device by switching to system default? note that the number of listeners // is stripped down to only one for now, to react to headphone swaps in the case of Built-in Output AddDeviceListeners(mOutputDevice, this); return true; } bool SC_CoreAudioDriver::StopStart() { bool test = DriverStop(); bool test2 = DriverStart(); return test && test2; } bool SC_CoreAudioDriver::DriverStop() { if (mWorld->mVerbosity >= 1) { scprintf("->SC_CoreAudioDriver::DriverStop\n"); } OSStatus err = kAudioHardwareNoError; auto appIOProcFunc = isClippingEnabled() ? appIOProc<true> : appIOProc<false>; if (UseSeparateIO()) { err = AudioDeviceStop(mOutputDevice, appIOProcFunc); if (err != kAudioHardwareNoError) { scprintf("Output AudioDeviceStop failed %p\n", err); return false; } err = AudioDeviceDestroyIOProcID(mOutputDevice, mOutputID); if (err != kAudioHardwareNoError) { scprintf("Output AudioDeviceDestroyIOProcID failed %p\n", err); return false; } err = AudioDeviceStop(mInputDevice, appIOProcSeparateIn); if (err != kAudioHardwareNoError) { scprintf("Input AudioDeviceStop failed %p\n", err); return false; } err = AudioDeviceDestroyIOProcID(mInputDevice, mInputID); if (err != kAudioHardwareNoError) { scprintf("Input AudioDeviceDestroyIOProcID failed %p\n", err); return false; } } else { err = AudioDeviceStop(mOutputDevice, appIOProcFunc); if (err != kAudioHardwareNoError) { scprintf("AudioDeviceStop B failed %p\n", err); return false; } err = AudioDeviceDestroyIOProcID(mOutputDevice, mOutputID); if (err != kAudioHardwareNoError) { scprintf("AudioDeviceDestroyIOProcID B failed %p\n", err); return false; } } if (mWorld->mVerbosity >= 1) { scprintf("<-SC_CoreAudioDriver::DriverStop\n"); } return true; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Listen for Device Properties and update interface and globals OSStatus deviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void* inClientData) { OSStatus err = noErr; SC_CoreAudioDriver* coredriver = (SC_CoreAudioDriver*)inClientData; for (int i = 0; i < inNumberAddresses; i++) { AudioObjectPropertyAddress propAddress = inAddresses[i]; if (inObjectID == kAudioObjectSystemObject && propAddress.mSelector == kAudioHardwarePropertyDefaultOutputDevice) { coredriver->StopStart(); } } return (err); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OSStatus AddDeviceListeners(AudioDeviceID inDevice, void* inClientData) { OSStatus err = noErr; AudioObjectPropertyAddress propertyAddress; // ONLY REACTING TO HEADPHONE SWAPS FOR NOW - see version control history for removed dead code propertyAddress.mSelector = kAudioHardwarePropertyDevices; propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; propertyAddress.mElement = kAudioObjectPropertyElementMaster; err = AudioObjectAddPropertyListener(inDevice, &propertyAddress, deviceListenerProc, inClientData); if (err) return err; return (err); } #endif // SC_AUDIO_API_COREAUDIO // ===================================================================== // Audio driver (CoreAudioIPHONE) #if SC_AUDIO_API == SC_AUDIO_API_COREAUDIOIPHONE SC_iCoreAudioDriver::SC_iCoreAudioDriver(struct World* inWorld): SC_AudioDriver(inWorld) { receivedIn = 0; } SC_iCoreAudioDriver::~SC_iCoreAudioDriver() {} /* OSStatus appIOProc2 (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr); OSStatus appIOProc2 (AudioDeviceID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { SC_CoreAudioDriver* def = (SC_CoreAudioDriver*)defptr; int64 oscTime = CoreAudioHostTimeToOSC(inOutputTime->mHostTime); AudioTimeStamp readTime; readTime.mSampleTime = inNow->mSampleTime - def->SafetyOffset() - def->NumSamplesPerCallback(); readTime.mFlags = kAudioTimeStampSampleTimeValid; AudioDeviceRead(def->InputDevice(), &readTime, def->GetInputBufferList()); def->Run(def->GetInputBufferList(), outOutputData, oscTime); return kAudioHardwareNoError; } */ OSStatus InputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) { SC_iCoreAudioDriver* driver = (SC_iCoreAudioDriver*)inRefCon; if (driver->receivedIn) { // printf("exit input with no data \n"); return noErr; } OSStatus ret = AudioUnitRender(driver->inputUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, driver->buflist); if (ret) { // printf("no input !\n"); return noErr; } driver->receivedIn = 1; return noErr; } OSStatus RenderCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) { SC_iCoreAudioDriver* driver = (SC_iCoreAudioDriver*)inRefCon; # ifndef SC_IPHONE if (!driver->receivedIn) { // printf("exit output with no data \n"); return noErr; } # endif // float *fbuffer = (float *) driver->converter_buffer; int i; for (i = 0; i < inNumberFrames; i++) { signed short s = ((signed short*)driver->buflist->mBuffers[0].mData)[i]; int k = s + 0x43c00000; float f = *((float*)&k); ((float*)driver->floatInputList->mBuffers[0].mData)[i] = f - 384.0f; } int64 oscTime = GetCurrentOSCTime(); // driver->Run(driver->floatInputList, driver->floatOutputList, oscTime); driver->Run(driver->floatInputList, ioData, oscTime); for (i = 0; i < inNumberFrames; i++) { float f1 = ((float*)ioData->mBuffers[0].mData)[i]; float f2 = ((float*)ioData->mBuffers[1].mData)[i]; ((int*)ioData->mBuffers[0].mData)[i] = (int)(f1 * 16777216); ((int*)ioData->mBuffers[1].mData)[i] = (int)(f2 * 16777216); } /* unsigned long size = 2*1024*sizeof(unsigned long); OSStatus ret = AudioConverterConvertBuffer(driver->converter_in_to_F32, driver->buflist->mBuffers[0].mDataByteSize, driver->buflist->mBuffers[0].mData, &size, driver->converter_buffer); if (ret) { printf("couldn't convert !\n"); return noErr; } int i; for (i=0; i<inNumberFrames; i++) { ((int *)ioData->mBuffers[0].mData)[i] = ((int *)ioData->mBuffers[1].mData)[i] = driver->converter_buffer[2*i]; } */ driver->receivedIn = 0; return noErr; } void SC_iCoreAudioDriver::Run(const AudioBufferList* inInputData, AudioBufferList* outOutputData, int64 oscTime) { int64 systemTimeBefore = GetMicroseconds(); World* world = mWorld; try { int numSamplesPerCallback = NumSamplesPerCallback(); mOSCbuftime = oscTime; # ifdef __APPLE__ // FIXME: does iOS support x86? sc_SetDenormalFlags(); # endif mFromEngine.Free(); mToEngine.Perform(); mOscPacketsToEngine.Perform(); // printf("mOscPacketsToEngine : %d micros\n", (int) (GetMicroseconds()-systemTimeBefore)); int bufFrames = world->mBufLength; int numBufs = numSamplesPerCallback / bufFrames; int numInputBuses = world->mNumInputs; int numOutputBuses = world->mNumOutputs; float* inputBuses = world->mAudioBus + world->mNumOutputs * bufFrames; float* outputBuses = world->mAudioBus; int32* inputTouched = world->mAudioBusTouched + world->mNumOutputs; int32* outputTouched = world->mAudioBusTouched; int numInputStreams = inInputData ? inInputData->mNumberBuffers : 0; int numOutputStreams = outOutputData ? outOutputData->mNumberBuffers : 0; // static int go = 0; int64 oscInc = mOSCincrement; double oscToSamples = mOSCtoSamples; int bufFramePos = 0; for (int i = 0; i < numBufs; ++i, world->mBufCounter++, bufFramePos += bufFrames) { int32 bufCounter = world->mBufCounter; // de-interleave input if (inInputData) { const AudioBuffer* inInputDataBuffers = inInputData->mBuffers; for (int s = 0, b = 0; b < numInputBuses && s < numInputStreams; s++) { const AudioBuffer* buf = inInputDataBuffers + s; int nchan = buf->mNumberChannels; if (buf->mData) { float* busdata = inputBuses + b * bufFrames; float* bufdata = (float*)buf->mData + bufFramePos * nchan; if (nchan == 1) { # ifdef IPHONE_VEC vcopy(busdata, bufdata, bufFrames); # else for (int k = 0; k < bufFrames; ++k) { busdata[k] = bufdata[k]; } # endif inputTouched[b] = bufCounter; } else { int minchan = sc_min(nchan, numInputBuses - b); for (int j = 0; j < minchan; ++j, busdata += bufFrames) { for (int k = 0, m = j; k < bufFrames; ++k, m += nchan) { busdata[k] = bufdata[m]; } inputTouched[b + j] = bufCounter; } } b += nchan; } } } // count++; int64 schedTime; int64 nextTime = oscTime + oscInc; while ((schedTime = mScheduler.NextTime()) <= nextTime) { float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5; float diffTimeFloor = floor(diffTime); world->mSampleOffset = (int)diffTimeFloor; world->mSubsampleOffset = diffTime - diffTimeFloor; if (world->mSampleOffset < 0) world->mSampleOffset = 0; else if (world->mSampleOffset >= world->mBufLength) world->mSampleOffset = world->mBufLength - 1; SC_ScheduledEvent event = mScheduler.Remove(); event.Perform(); } world->mSampleOffset = 0; world->mSubsampleOffset = 0.f; // int64 now = GetMicroseconds(); World_Run(world); // printf("world run : %fms\n", (float) (GetMicroseconds()-now)/1000); // interleave output AudioBuffer* outOutputDataBuffers = outOutputData->mBuffers; for (int s = 0, b = 0; b < numOutputBuses && s < numOutputStreams; s++) { AudioBuffer* buf = outOutputDataBuffers + s; int nchan = buf->mNumberChannels; if (buf->mData) { float* busdata = outputBuses + b * bufFrames; float* bufdata = (float*)buf->mData + bufFramePos * nchan; if (nchan == 1) { if (outputTouched[b] == bufCounter) { # ifdef IPHONE_VEC vcopy(bufdata, busdata, bufFrames); # else for (int k = 0; k < bufFrames; ++k) { bufdata[k] = busdata[k]; } # endif } } else { int minchan = sc_min(nchan, numOutputBuses - b); for (int j = 0; j < minchan; ++j, busdata += bufFrames) { if (outputTouched[b + j] == bufCounter) { for (int k = 0, m = j; k < bufFrames; ++k, m += nchan) { bufdata[m] = busdata[k]; } } } } b += nchan; } } oscTime = mOSCbuftime = nextTime; } } catch (std::exception& exc) { scprintf("exception in real time: %s\n", exc.what()); } catch (...) { scprintf("unknown exception in real time\n"); } int64 systemTimeAfter = GetMicroseconds(); double calcTime = (double)(systemTimeAfter - systemTimeBefore) * 1e-6; double cpuUsage = calcTime * mBuffersPerSecond * 100.; mAvgCPU = mAvgCPU + 0.1 * (cpuUsage - mAvgCPU); if (cpuUsage > mPeakCPU || --mPeakCounter <= 0) { mPeakCPU = cpuUsage; mPeakCounter = mMaxPeakCounter; } mAudioSync.Signal(); } /* OSStatus appIOProc (AudioDeviceID device, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* defptr) { SC_CoreAudioDriver* def = (SC_CoreAudioDriver*)defptr; int64 oscTime = CoreAudioHostTimeToOSC(inOutputTime->mHostTime); double hostSecs = (double)AudioConvertHostTimeToNanos(inOutputTime->mHostTime) * 1e-9; double sampleTime = inOutputTime->mSampleTime; if (def->mStartHostSecs == 0) { def->mStartHostSecs = hostSecs; def->mStartSampleTime = sampleTime; } else { double instSampleRate = (sampleTime - def->mPrevSampleTime)/(hostSecs - def->mPrevHostSecs); double smoothSampleRate = def->mSmoothSampleRate; smoothSampleRate = smoothSampleRate + 0.002 * (instSampleRate - smoothSampleRate); def->mOSCincrement = (int64)(def->mOSCincrementNumerator / smoothSampleRate); def->mSmoothSampleRate = smoothSampleRate; #if 0 double avgSampleRate = (sampleTime - def->mStartSampleTime)/(hostSecs - def->mStartHostSecs); double jitter = (smoothSampleRate * (hostSecs - def->mPrevHostSecs)) - (sampleTime - def->mPrevSampleTime); double drift = (smoothSampleRate - def->mSampleRate) * (hostSecs - def->mStartHostSecs); //if (fabs(jitter) > 0.01) { scprintf("avgSR %.6f smoothSR %.6f instSR %.6f jitter %.6f drift %.6f inc %lld\n", avgSampleRate, smoothSampleRate, instSampleRate, jitter, drift, def->mOSCincrement); //} #endif } def->mPrevHostSecs = hostSecs; def->mPrevSampleTime = sampleTime; if (!def->UseSeparateIO()) { def->Run(inInputData, outOutputData, oscTime); return kAudioHardwareNoError; } def->Run(lastInputData, outOutputData, oscTime); lastInputData = 0; return kAudioHardwareNoError; } */ void AudioSessionInterruptionCbk(void* inClientData, UInt32 inInterruptionState) {} bool SC_iCoreAudioDriver::DriverSetup(int* outNumSamplesPerCallback, double* outSampleRate) { AudioSessionInitialize(0, 0, AudioSessionInterruptionCbk, 0); unsigned long category = kAudioSessionCategory_PlayAndRecord; # ifdef SC_IPHONE UInt32 micInput, micInputSize = sizeof(&micInput); AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &micInputSize, &micInput); if (!micInput) { category = kAudioSessionCategory_MediaPlayback; scprintf("SC_IPHONE: WARNING - no audio input available\n"); } # endif AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category); if (mPreferredHardwareBufferFrameSize) { Float32 preferredBufferSize = (float)mPreferredHardwareBufferFrameSize / 44100.f; AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof(preferredBufferSize), &preferredBufferSize); } AudioSessionSetActive(true); float actualBufferDuration; UInt32 size = sizeof(actualBufferDuration); AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareIOBufferDuration, &size, &actualBufferDuration); *outNumSamplesPerCallback = (int)(actualBufferDuration * 44100.f + 0.5f); *outSampleRate = 44100; AudioComponentDescription desc; desc.componentType = kAudioUnitType_Output; desc.componentSubType = kAudioUnitSubType_RemoteIO; desc.componentManufacturer = kAudioUnitManufacturer_Apple; NewAUGraph(&graph); AUNode node; AudioUnit unit; OSStatus ret = AUGraphAddNode(graph, &desc, &node); // printf("node : %d\n", node); AUGraphOpen(graph); ret = AUGraphNodeInfo(graph, node, &desc, &unit); // printf("%d\n", unit); AudioComponent remoteIOComp = AudioComponentFindNext(0, &desc); if (AudioComponentInstanceNew(remoteIOComp, &inputUnit) != noErr) { // printf("error instantiating RemoteIO\n"); return false; } // printf("instantiated : %d\n", inputUnit); int enableIO = 1; ret = AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO)); if (ret != noErr) { // printf("can't set input : %d\n", ret); return false; } enableIO = 0; ret = AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO)); if (ret != noErr) { // printf("can't set output : %d\n", ret); return false; } AudioUnitInitialize(inputUnit); unsigned long bufferSizeBytes = 1024 * sizeof(unsigned long); buflist = (AudioBufferList*)malloc(sizeof(AudioBufferList)); buflist->mNumberBuffers = 1; buflist->mBuffers[0].mDataByteSize = bufferSizeBytes; buflist->mBuffers[0].mData = malloc(bufferSizeBytes); buflist->mBuffers[0].mNumberChannels = 1; floatInputList = (AudioBufferList*)malloc(sizeof(AudioBufferList)); floatInputList->mNumberBuffers = 1; floatInputList->mBuffers[0].mDataByteSize = bufferSizeBytes; floatInputList->mBuffers[0].mData = malloc(bufferSizeBytes); floatInputList->mBuffers[0].mNumberChannels = 1; /* floatOutputList = (AudioBufferList *) malloc(sizeof(AudioBufferList)+sizeof(AudioBuffer)); floatOutputList->mNumberBuffers = 2; floatOutputList->mBuffers[0].mDataByteSize = bufferSizeBytes; floatOutputList->mBuffers[0].mData = malloc(bufferSizeBytes); floatOutputList->mBuffers[0].mNumberChannels = 1; floatOutputList->mBuffers[1].mDataByteSize = bufferSizeBytes; floatOutputList->mBuffers[1].mData = malloc(bufferSizeBytes); floatOutputList->mBuffers[1].mNumberChannels = 1; */ AURenderCallbackStruct inputStruct; inputStruct.inputProc = InputCallback; inputStruct.inputProcRefCon = this; ret = AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Input, 0, &inputStruct, sizeof(inputStruct)); AURenderCallbackStruct renderStruct; renderStruct.inputProc = RenderCallback; renderStruct.inputProcRefCon = this; ret = AudioUnitSetProperty(unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderStruct, sizeof(renderStruct)); AudioStreamBasicDescription streamFormat; streamFormat.mFormatID = kAudioFormatLinearPCM; streamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kLinearPCMFormatFlagIsNonInterleaved | (24 << kLinearPCMFormatFlagsSampleFractionShift); streamFormat.mSampleRate = 44100; streamFormat.mBitsPerChannel = 32; streamFormat.mChannelsPerFrame = 2; streamFormat.mFramesPerPacket = 1; streamFormat.mBytesPerFrame = (streamFormat.mBitsPerChannel / 8); streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket; ret = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(streamFormat)); AudioStreamBasicDescription audioFormat; audioFormat.mSampleRate = 44100.00; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; audioFormat.mFramesPerPacket = 1; audioFormat.mChannelsPerFrame = 1; audioFormat.mBitsPerChannel = 16; audioFormat.mBytesPerPacket = 2; audioFormat.mBytesPerFrame = 2; ret = AudioUnitSetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &audioFormat, sizeof(audioFormat)); /* AudioStreamBasicDescription d; size = sizeof(d); ret = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &d, &size); AudioStreamBasicDescription inputFormat; AudioStreamBasicDescription outputFormat; AudioStreamBasicDescription f32Format; size = sizeof(AudioStreamBasicDescription); ret = AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inputFormat, &size); ret = AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &inputFormat, &size); ret = AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &outputFormat, &size); ret = AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &outputFormat, &size); outputFormat.mChannelsPerFrame = 1; f32Format.mSampleRate = inputFormat.mSampleRate; f32Format.mFormatID = inputFormat.mFormatID; f32Format.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; f32Format.mBytesPerPacket = 4; f32Format.mFramesPerPacket = 1; f32Format.mBytesPerFrame = 4; f32Format.mChannelsPerFrame = 1; f32Format.mBitsPerChannel = 32; f32Format.mReserved = 0; ret = AudioConverterNew(&inputFormat, &f32Format, &converter_in_to_F32); ret = AudioConverterNew(&f32Format, &outputFormat, &converter_F32_to_out); ret = AudioConverterNew(&inputFormat, &outputFormat, &converter_in_to_out); */ AUGraphInitialize(graph); if (mWorld->mVerbosity >= 0) { scprintf("<-SC_CoreAudioDriver::Setup world %p\n", mWorld); } return true; } bool SC_iCoreAudioDriver::DriverStart() { if (mWorld->mVerbosity >= 0) { scprintf("->SC_CoreAudioDriver::DriverStart\n"); } try { OSStatus ret = AUGraphStart(graph); AudioOutputUnitStart(inputUnit); } catch (...) { scprintf("exception in SC_CoreAudioDriver::DriverStart\n"); } if (mWorld->mVerbosity >= 0) { scprintf("<-SC_CoreAudioDriver::DriverStart\n"); } return true; } bool SC_iCoreAudioDriver::DriverStop() { if (mWorld->mVerbosity >= 0) { scprintf("->SC_CoreAudioDriver::DriverStop\n"); } AUGraphStop(graph); AudioOutputUnitStop(inputUnit); if (mWorld->mVerbosity >= 0) { scprintf("<-SC_CoreAudioDriver::DriverStop\n"); } return true; } #endif // SC_AUDIO_API_COREAUDIOIPHONE
93,074
C++
.cpp
1,882
39.472901
120
0.633042
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
29,917
SC_Unit.cpp
supercollider_supercollider/server/scsynth/SC_Unit.cpp
/* 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 <stdio.h> #include "SC_Endian.h" #include "SC_Unit.h" #include "SC_UnitSpec.h" #include "SC_UnitDef.h" #include "SC_World.h" #include "SC_Wire.h" #include "Unroll.h" #include "SC_Prototypes.h" void Unit_ChooseMulAddFunc(Unit* unit); Unit* Unit_New(World* inWorld, UnitSpec* inUnitSpec, char*& memory) { UnitDef* def = inUnitSpec->mUnitDef; Unit* unit = (Unit*)memory; memory += def->mAllocSize; unit->mWorld = inWorld; unit->mUnitDef = def; uint32 numInputs = inUnitSpec->mNumInputs; uint32 numOutputs = inUnitSpec->mNumOutputs; unit->mNumInputs = numInputs; unit->mNumOutputs = numOutputs; uint64 numPorts = numInputs + numOutputs; unit->mInput = (Wire**)memory; memory += numPorts * sizeof(Wire*); unit->mOutput = unit->mInput + numInputs; unit->mInBuf = (float**)memory; memory += numPorts * sizeof(float*); unit->mOutBuf = unit->mInBuf + numInputs; unit->mCalcRate = inUnitSpec->mCalcRate; unit->mSpecialIndex = inUnitSpec->mSpecialIndex; Rate* rateInfo = unit->mRate = inUnitSpec->mRateInfo; unit->mBufLength = rateInfo->mBufLength; unit->mDone = false; return unit; } void Unit_Dtor(Unit* inUnit) {} void Unit_ZeroOutputs(Unit* unit, int inNumSamples) { uint32 numOuts = unit->mNumOutputs; for (uint32 i = 0; i < numOuts; ++i) { float* out = OUT(i); Clear(inNumSamples, out); } } void Unit_EndCalc(Unit* inUnit, int inNumSamples) { inUnit->mDone = true; Unit_ZeroOutputs(inUnit, inNumSamples); } void Unit_End(Unit* inUnit) { inUnit->mCalcFunc = (UnitCalcFunc)&Unit_EndCalc; }
2,507
C++
.cpp
63
35.603175
81
0.714816
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
29,918
SC_AU.cpp
supercollider_supercollider/server/scsynth/SC_AU.cpp
/* AudioUnits driver interface. Copyright (c) 2006-2008 Gerard Roma. ==================================================================== 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_AU.h" void AUCallback(SC_AUAudioDriver* driver, AudioBufferList* in, AudioBufferList* out, AudioTimeStamp* inTimeStamp, UInt32 inFramesToProcess, Float64 sampleRate, int64 oscTime) { driver->Callback(in, out, inTimeStamp, inFramesToProcess, sampleRate, oscTime); } void sc_SetDenormalFlags(); SC_AudioDriver* SC_NewAudioDriver(struct World* inWorld) { return new SC_AUAudioDriver(inWorld); } SC_AUAudioDriver::SC_AUAudioDriver(struct World* inWorld): SC_CoreAudioDriver(inWorld) {} SC_AUAudioDriver::~SC_AUAudioDriver() {} bool SC_AUAudioDriver::DriverSetup(int* outNumSamples, double* outSampleRate) { // params are set into the wolrd options at AU initialize if (!mPreferredSampleRate && !mPreferredHardwareBufferFrameSize) return false; *outSampleRate = mPreferredSampleRate; *outNumSamples = mPreferredHardwareBufferFrameSize; return true; } bool SC_AUAudioDriver::DriverStart() { return true; } bool SC_AUAudioDriver::DriverStop() { return true; } void SC_AUAudioDriver::Callback(const AudioBufferList* in, AudioBufferList* out, AudioTimeStamp* inTimeStamp, UInt32 inFramesToProcess, Float64 sampleRate, int64 oscTime) { this->mNumSamplesPerCallback = inFramesToProcess; this->mOSCincrement = (int64)(this->mOSCincrementNumerator / sampleRate); this->Run(in, out, oscTime); } #endif
2,474
C++
.cpp
46
48.956522
113
0.73466
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
29,919
SC_BufGen.cpp
supercollider_supercollider/server/scsynth/SC_BufGen.cpp
/* 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_BufGen.h" #include "SC_World.h" #include "SC_Unit.h" #include "SC_InterfaceTable.h" #include <stdio.h> #include <stdlib.h> #ifndef _MSC_VER # include <dirent.h> #endif //_MSC_VER #include <string.h> #include "SC_Prototypes.h" #include "SC_Str4.h" extern InterfaceTable gInterfaceTable; bool BufGen_Create(const char* inName, BufGenFunc inFunc) { BufGen* bufGen = (BufGen*)malloc(sizeof(BufGen)); str4cpy(bufGen->mBufGenName, inName); bufGen->mHash = Hash(bufGen->mBufGenName); bufGen->mBufGenFunc = inFunc; if (!AddBufGen(bufGen)) { free(bufGen); return false; } return true; }
1,517
C++
.cpp
40
34.2
81
0.736376
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
29,920
SC_Graph.cpp
supercollider_supercollider/server/scsynth/SC_Graph.cpp
/* 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_Win32Utils.h" #include "SC_Graph.h" #include "SC_GraphDef.h" #include "SC_Unit.h" #include "SC_UnitSpec.h" #include "SC_UnitDef.h" #include "SC_HiddenWorld.h" #include "SC_WorldOptions.h" #include "SC_Wire.h" #include "SC_WireSpec.h" #include <stdio.h> #include <string.h> #include "SC_Prototypes.h" #include "SC_Errors.h" #include "Unroll.h" void Unit_ChooseMulAddFunc(Unit* unit); struct QueuedCmd { struct QueuedCmd* mNext; int mSize; char mData[1]; }; //////////////////////////////////////////////////////////////////////////////// void Graph_FirstCalc(Graph* inGraph); void Graph_NullFirstCalc(Graph* inGraph); void Graph_Dtor(Graph* inGraph) { // scprintf("->Graph_Dtor %d\n", inGraph->mNode.mID); World* world = inGraph->mNode.mWorld; uint32 numUnits = inGraph->mNumUnits; Unit** graphUnits = inGraph->mUnits; if (inGraph->mNode.mCalcFunc != (NodeCalcFunc)Graph_FirstCalc && inGraph->mNode.mCalcFunc != (NodeCalcFunc)(Graph_NullFirstCalc)) { // the above test insures that dtors are not called if ctors have not been called. for (uint32 i = 0; i < numUnits; ++i) { Unit* unit = graphUnits[i]; UnitDtorFunc dtor = unit->mUnitDef->mUnitDtorFunc; if (dtor) (dtor)(unit); } } // free queued Unit commands // AFAICT this can only happen if a Graph is created, Unit commands are sent and the Graph // is deleted all at the same time stamp. QueuedCmd* cmd = (QueuedCmd*)inGraph->mPrivate; while (cmd) { QueuedCmd* next = cmd->mNext; World_Free(inGraph->mNode.mWorld, cmd); cmd = next; } world->mNumUnits -= numUnits; world->mNumGraphs--; GraphDef* def = GRAPHDEF(inGraph); if (--def->mRefCount <= 0) { if (world->mRealTime) GraphDef_DeleteMsg(world, def); else GraphDef_Free(def); } Node_Dtor(&inGraph->mNode); // scprintf("<-Graph_Dtor\n"); } //////////////////////////////////////////////////////////////////////////////// int Graph_New(struct World* inWorld, struct GraphDef* inGraphDef, int32 inID, struct sc_msg_iter* args, Graph** outGraph, bool argtype) // true for normal args , false for setn type args { Graph* graph; int err = Node_New(inWorld, &inGraphDef->mNodeDef, inID, (Node**)&graph); if (err) return err; Graph_Ctor(inWorld, inGraphDef, graph, args, argtype); *outGraph = graph; return err; } void Graph_Ctor(World* inWorld, GraphDef* inGraphDef, Graph* graph, sc_msg_iter* msg, bool argtype) // true for normal args , false for setn type args { // scprintf("->Graph_Ctor\n"); // hit the memory allocator only once. char* memory = (char*)graph + sizeof(Graph); // allocate space for children uint32 numUnits = inGraphDef->mNumUnitSpecs; graph->mNumUnits = numUnits; inWorld->mNumUnits += numUnits; inWorld->mNumGraphs++; graph->mUnits = (Unit**)memory; memory += inGraphDef->mUnitsAllocSize; // set calc func graph->mNode.mCalcFunc = (NodeCalcFunc)&Graph_FirstCalc; // allocate wires graph->mNumWires = inGraphDef->mNumWires; graph->mWire = (Wire*)memory; memory += inGraphDef->mWiresAllocSize; graph->mNumCalcUnits = inGraphDef->mNumCalcUnits; graph->mCalcUnits = (Unit**)memory; memory += inGraphDef->mCalcUnitsAllocSize; // initialize controls uint32 numControls = inGraphDef->mNumControls; graph->mNumControls = numControls; graph->mControls = (float*)memory; memory += inGraphDef->mControlAllocSize; graph->mAudioBusOffsets = (int32*)memory; memory += inGraphDef->mAudioMapBusOffsetSize; graph->mMapControls = (float**)memory; memory += inGraphDef->mMapControlsAllocSize; graph->mControlRates = (int*)memory; memory += inGraphDef->mMapControlRatesAllocSize; { float* graphControls = graph->mControls; float* initialControlValues = inGraphDef->mInitialControlValues; float** graphMapControls = graph->mMapControls; /* add */ int* graphControlRates = graph->mControlRates; for (uint32 i = 0; i < numControls; ++i, ++graphControls) { *graphControls = initialControlValues[i]; graphMapControls[i] = graphControls; /* add */ graphControlRates[i] = 0; // init to 0 for now... control bus is 1, audio is 2 graph->mAudioBusOffsets[i] = -1; } } // set controls // if argtype == true -> normal args as always // if argtype == false -> setn type args if (argtype) { while (msg->remain() >= 8) { int i = 0; int loop = 0; if (msg->nextTag('i') == 's') { int32* name = msg->gets4(); int32 hash = Hash(name); do { switch (msg->nextTag('f')) { case 'f': case 'i': { float32 value = msg->getf(); Graph_SetControl(graph, hash, name, i, value); break; } case 's': { const char* string = msg->gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Graph_MapControl(graph, hash, name, i, bus); } else { if (*string == 'a') { int bus = sc_atoi(string + 1); Graph_MapAudioControl(graph, hash, name, i, bus); } } break; } case ']': msg->count++; loop -= 1; break; case '[': msg->count++; loop += 1; i -= 1; break; } ++i; } while (loop); } else { int32 index = msg->geti(); do { switch (msg->nextTag('f')) { case 'f': case 'i': { float32 value = msg->getf(); Graph_SetControl(graph, index + i, value); break; } case 's': { const char* string = msg->gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Graph_MapControl(graph, index + i, bus); } else { if (*string == 'a') { int bus = sc_atoi(string + 1); Graph_MapAudioControl(graph, index + i, bus); } } break; } case ']': msg->count++; loop -= 1; break; case '[': msg->count++; loop += 1; i -= 1; break; } ++i; } while (loop); } } } //{ // while( msg->remain()>=8) { // int i = 0; // int loop = 0; // if (msg->nextTag('i') == 's') { // int32* name = msg->gets4(); // int32 hash = Hash(name); // if (msg->nextTag('f') == '[' ) { // msg->count++; // loop = 1; // } // do { // if (msg->nextTag('f') == 's' ) { // const char* string = msg->gets(); // if ( *string == 'c') { // int bus = sc_atoi(string+1); // Graph_MapControl(graph, hash, name, i, bus); // } // } else { // if (msg->nextTag('f') == ']' ) { // msg->count++; // loop = 0; // } else { // float32 value = msg->getf(); // Graph_SetControl(graph, hash, name, i, value); // } // } // ++i; // } // while (loop); // } else { // int32 index = msg->geti(); // if (msg->nextTag('f') == '[' ) { // msg->count++; // loop = 1; // } // do { // if (msg->nextTag('f') == 's') { // const char* string = msg->gets(); // if (*string == 'c') { // int bus = sc_atoi(string+1); // Graph_MapControl(graph, index + i, bus); // } // } else { // if (msg->nextTag('f') == ']' ) { // msg->count++; // loop = 0; // } else { // float32 value = msg->getf(); // Graph_SetControl(graph, index + i, value); // } // } // ++i; // } // while (loop); // } // } // // } else { while (msg->remain()) { if (msg->nextTag('i') == 's') { int32* name = msg->gets4(); int32 hash = Hash(name); int32 n = msg->geti(); for (int i = 0; msg->remain() && i < n; ++i) { if (msg->nextTag('f') == 's') { const char* string = msg->gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Graph_MapControl(graph, hash, name, i, bus); // Node_MapControl(node, hash, name, i, bus); } else { if (*string == 'a') { int bus = sc_atoi(string + 1); Graph_MapAudioControl(graph, hash, name, i, bus); } } } else { float32 value = msg->getf(); Graph_SetControl(graph, hash, name, i, value); // Node_SetControl(node, hash, name, i, value); } } } else { int32 index = msg->geti(); int32 n = msg->geti(); for (int i = 0; msg->remain() && i < n; ++i) { if (msg->nextTag('f') == 's') { const char* string = msg->gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Graph_MapControl(graph, index + i, bus); // Node_MapControl(node, index+i, bus); } else { if (*string == 'a') { int bus = sc_atoi(string + 1); Graph_MapAudioControl(graph, index + i, bus); } } } else { float32 value = msg->getf(); Graph_SetControl(graph, index + i, value); // Node_SetControl(node, index+i, value); } } } } } // set up scalar values Wire* graphWires = graph->mWire; int numConstants = inGraphDef->mNumConstants; { float* constants = inGraphDef->mConstants; Wire* wire = graphWires; for (int i = 0; i < numConstants; ++i, ++wire) { wire->mFromUnit = nullptr; wire->mCalcRate = calc_ScalarRate; wire->mBuffer = &wire->mScalarValue; wire->mScalarValue = constants[i]; } } graph->mSampleOffset = inWorld->mSampleOffset; graph->mSubsampleOffset = inWorld->mSubsampleOffset; graph->mRGen = inWorld->mRGen; // defaults to rgen zero. graph->mLocalAudioBusUnit = nullptr; graph->mLocalControlBusUnit = nullptr; graph->localBufNum = 0; graph->localMaxBufNum = 0; // this is set from synth // so far mPrivate is only used for queued unit commands, // i.e. it just points to the head of the list. graph->mPrivate = nullptr; // initialize units // scprintf("initialize units\n"); Unit** calcUnits = graph->mCalcUnits; Unit** graphUnits = graph->mUnits; int calcCtr = 0; float* bufspace = inWorld->hw->mWireBufSpace; uint32 wireCtr = numConstants; // never more than numConstants + numOutputs UnitSpec* unitSpec = inGraphDef->mUnitSpecs; for (uint32 i = 0; i < numUnits; ++i, ++unitSpec) { // construct unit from spec Unit* unit = Unit_New(inWorld, unitSpec, memory); // set parent unit->mParent = graph; unit->mParentIndex = i; graphUnits[i] = unit; { // hook up unit inputs // scprintf("hook up unit inputs\n"); InputSpec* inputSpec = unitSpec->mInputSpec; Wire** unitInput = unit->mInput; float** unitInBuf = unit->mInBuf; uint32 numInputs = unitSpec->mNumInputs; for (uint32 j = 0; j < numInputs; ++j, ++inputSpec) { Wire* wire = graphWires + inputSpec->mWireIndex; unitInput[j] = wire; unitInBuf[j] = wire->mBuffer; } } { // hook up unit outputs // scprintf("hook up unit outputs\n"); Wire** unitOutput = unit->mOutput; float** unitOutBuf = unit->mOutBuf; uint32 numOutputs = unitSpec->mNumOutputs; Wire* wire = graphWires + wireCtr; wireCtr += numOutputs; int unitCalcRate = unit->mCalcRate; if (unitCalcRate == calc_FullRate) { OutputSpec* outputSpec = unitSpec->mOutputSpec; for (uint32 j = 0; j < numOutputs; ++j, ++wire, ++outputSpec) { wire->mFromUnit = unit; wire->mCalcRate = calc_FullRate; wire->mBuffer = bufspace + outputSpec->mBufferIndex; unitOutput[j] = wire; unitOutBuf[j] = wire->mBuffer; } calcUnits[calcCtr++] = unit; } else { for (uint32 j = 0; j < numOutputs; ++j, ++wire) { wire->mFromUnit = unit; wire->mCalcRate = unitCalcRate; wire->mBuffer = &wire->mScalarValue; unitOutput[j] = wire; unitOutBuf[j] = wire->mBuffer; } if (unitCalcRate == calc_BufRate) { calcUnits[calcCtr++] = unit; } } } } inGraphDef->mRefCount++; } void Graph_QueueUnitCmd(Graph* inGraph, int inSize, const char* inData) { // put the unit command on a queue and dispatch it right after the first // calc function, i.e. after calling the unit constructors. // scprintf("->Graph_QueueUnitCmd\n"); QueuedCmd* cmd = (QueuedCmd*)World_Alloc(inGraph->mNode.mWorld, sizeof(QueuedCmd) + inSize); cmd->mNext = nullptr; cmd->mSize = inSize; memcpy(cmd->mData, inData, inSize); if (inGraph->mPrivate) { // add to tail QueuedCmd* ptr = (QueuedCmd*)inGraph->mPrivate; while (ptr->mNext) ptr = ptr->mNext; ptr->mNext = cmd; } else { inGraph->mPrivate = cmd; } } static void Graph_DispatchUnitCmds(Graph* inGraph) { QueuedCmd* item = (QueuedCmd*)inGraph->mPrivate; while (item) { QueuedCmd* next = item->mNext; sc_msg_iter msg(item->mSize, item->mData); // error checking has already be done in Unit_DoCmd() int nodeID = msg.geti(); assert(nodeID == inGraph->mNode.mID); uint32 unitID = msg.geti(); Unit* unit = inGraph->mUnits[unitID]; UnitDef* unitDef = unit->mUnitDef; int32* cmdName = msg.gets4(); UnitCmd* cmd = unitDef->mCmds->Get(cmdName); (cmd->mFunc)(unit, &msg); World_Free(inGraph->mNode.mWorld, item); item = next; } inGraph->mPrivate = nullptr; } void Graph_FirstCalc(Graph* inGraph) { // scprintf("->Graph_FirstCalc\n"); uint32 numUnits = inGraph->mNumUnits; Unit** units = inGraph->mUnits; for (uint32 i = 0; i < numUnits; ++i) { Unit* unit = units[i]; // call constructor (*unit->mUnitDef->mUnitCtorFunc)(unit); } // scprintf("<-Graph_FirstCalc\n"); inGraph->mNode.mCalcFunc = (NodeCalcFunc)&Graph_Calc; // after setting the calc function! Graph_DispatchUnitCmds(inGraph); // now do actual graph calculation Graph_Calc(inGraph); } void Node_NullCalc(struct Node* /*inNode*/); void Graph_NullFirstCalc(Graph* inGraph) { // scprintf("->Graph_FirstCalc\n"); uint32 numUnits = inGraph->mNumUnits; Unit** units = inGraph->mUnits; for (uint32 i = 0; i < numUnits; ++i) { Unit* unit = units[i]; // call constructor (*unit->mUnitDef->mUnitCtorFunc)(unit); } // scprintf("<-Graph_FirstCalc\n"); inGraph->mNode.mCalcFunc = &Node_NullCalc; // after setting the calc function! Graph_DispatchUnitCmds(inGraph); } inline void Graph_Calc_unit(Unit* unit) { (unit->mCalcFunc)(unit, unit->mBufLength); } void Graph_Calc(Graph* inGraph) { // scprintf("->Graph_Calc\n"); uint32 numCalcUnits = inGraph->mNumCalcUnits; Unit** calcUnits = inGraph->mCalcUnits; int unroll8 = numCalcUnits / 8; int remain8 = numCalcUnits % 8; int i = 0; for (int j = 0; j != unroll8; i += 8, ++j) { Graph_Calc_unit(calcUnits[i]); Graph_Calc_unit(calcUnits[i + 1]); Graph_Calc_unit(calcUnits[i + 2]); Graph_Calc_unit(calcUnits[i + 3]); Graph_Calc_unit(calcUnits[i + 4]); Graph_Calc_unit(calcUnits[i + 5]); Graph_Calc_unit(calcUnits[i + 6]); Graph_Calc_unit(calcUnits[i + 7]); } int unroll4 = remain8 / 4; int remain4 = remain8 % 4; if (unroll4) { Graph_Calc_unit(calcUnits[i]); Graph_Calc_unit(calcUnits[i + 1]); Graph_Calc_unit(calcUnits[i + 2]); Graph_Calc_unit(calcUnits[i + 3]); i += 4; } int unroll2 = remain4 / 2; int remain2 = remain4 % 2; if (unroll2) { Graph_Calc_unit(calcUnits[i]); Graph_Calc_unit(calcUnits[i + 1]); i += 2; } if (remain2) Graph_Calc_unit(calcUnits[i]); // scprintf("<-Graph_Calc\n"); } void Graph_CalcTrace(Graph* inGraph); void Graph_CalcTrace(Graph* inGraph) { uint32 numCalcUnits = inGraph->mNumCalcUnits; Unit** calcUnits = inGraph->mCalcUnits; scprintf("\nTRACE %d %s #units: %d\n", inGraph->mNode.mID, inGraph->mNode.mDef->mName, numCalcUnits); for (uint32 i = 0; i < numCalcUnits; ++i) { Unit* unit = calcUnits[i]; scprintf(" unit %d %s\n in ", i, (char*)unit->mUnitDef->mUnitDefName); for (uint32 j = 0; j < unit->mNumInputs; ++j) { scprintf(" %g", ZIN0(j)); } scprintf("\n"); (unit->mCalcFunc)(unit, unit->mBufLength); scprintf(" out"); for (uint32 j = 0; j < unit->mNumOutputs; ++j) { scprintf(" %g", ZOUT0(j)); } scprintf("\n"); } inGraph->mNode.mCalcFunc = (NodeCalcFunc)&Graph_Calc; } void Graph_Trace(Graph* inGraph) { if (inGraph->mNode.mCalcFunc == (NodeCalcFunc)&Graph_Calc) { inGraph->mNode.mCalcFunc = (NodeCalcFunc)&Graph_CalcTrace; } } int Graph_GetControl(Graph* inGraph, uint32 inIndex, float& outValue) { if (inIndex >= GRAPHDEF(inGraph)->mNumControls) return kSCErr_IndexOutOfRange; outValue = inGraph->mControls[inIndex]; return kSCErr_None; } int Graph_GetControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, float& outValue) { ParamSpecTable* table = GRAPH_PARAM_TABLE(inGraph); ParamSpec* spec = table->Get(inHash, inName); if (!spec || inIndex >= spec->mNumChannels) return kSCErr_IndexOutOfRange; return Graph_GetControl(inGraph, spec->mIndex + inIndex, outValue); } void Graph_SetControl(Graph* inGraph, uint32 inIndex, float inValue) { if (inIndex >= GRAPHDEF(inGraph)->mNumControls) return; inGraph->mControlRates[inIndex] = 0; float* ptr = inGraph->mControls + inIndex; inGraph->mMapControls[inIndex] = ptr; // unmap the control *ptr = inValue; } void Graph_SetControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, float inValue) { ParamSpecTable* table = GRAPH_PARAM_TABLE(inGraph); ParamSpec* spec = table->Get(inHash, inName); if (!spec || inIndex >= spec->mNumChannels) return; // printf("setting: %s: to value %f\n", spec->mName, inValue); Graph_SetControl(inGraph, spec->mIndex + inIndex, inValue); } void Graph_MapControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus) { ParamSpecTable* table = GRAPH_PARAM_TABLE(inGraph); ParamSpec* spec = table->Get(inHash, inName); if (!spec || inIndex >= spec->mNumChannels) return; // printf("mapping: %s: to bus index %i\n", spec->mName, inBus); Graph_MapControl(inGraph, spec->mIndex + inIndex, inBus); } void Graph_MapControl(Graph* inGraph, uint32 inIndex, uint32 inBus) { if (inIndex >= GRAPHDEF(inGraph)->mNumControls) return; World* world = inGraph->mNode.mWorld; if (inBus >= 0x80000000) { inGraph->mControlRates[inIndex] = 0; inGraph->mMapControls[inIndex] = inGraph->mControls + inIndex; } else if (inBus < world->mNumControlBusChannels) { inGraph->mControlRates[inIndex] = 1; inGraph->mMapControls[inIndex] = world->mControlBus + inBus; } } void Graph_MapAudioControl(Graph* inGraph, int32 inHash, int32* inName, uint32 inIndex, uint32 inBus) { ParamSpecTable* table = GRAPH_PARAM_TABLE(inGraph); ParamSpec* spec = table->Get(inHash, inName); if (!spec || inIndex >= spec->mNumChannels) return; // printf("mapping: %s: to bus index %i\n", spec->mName, inBus); if (spec) Graph_MapAudioControl(inGraph, spec->mIndex + inIndex, inBus); } void Graph_MapAudioControl(Graph* inGraph, uint32 inIndex, uint32 inBus) { if (inIndex >= GRAPHDEF(inGraph)->mNumControls) return; World* world = inGraph->mNode.mWorld; /* what is the below doing??? it is unmapping by looking for negative ints */ if (inBus >= 0x80000000) { inGraph->mControlRates[inIndex] = 0; inGraph->mMapControls[inIndex] = inGraph->mControls + inIndex; } else if (inBus < world->mNumAudioBusChannels) { inGraph->mControlRates[inIndex] = 2; inGraph->mAudioBusOffsets[inIndex] = inBus; inGraph->mMapControls[inIndex] = world->mAudioBus + (inBus * world->mBufLength); } }
23,985
C++
.cpp
615
29.004878
109
0.532709
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
29,921
Rendezvous.cpp
supercollider_supercollider/server/scsynth/Rendezvous.cpp
/* * Rendezvous.cpp * SC3synth * * Created by C. Ramakrishnan on Wed Dec 18 2002. * Illposed Software * * Avahi implementation (c) 2006 stefan kersten * Howl implementation (c) 2005 2006 stefan kersten */ /* 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 "Rendezvous.h" #include "SC_Export.h" SCSYNTH_DLLEXPORT_C int scprintf(const char* fmt, ...); #ifndef __APPLE__ static const char* kSCRendezvousServiceName = "SuperCollider"; static const char* SCRendezvousProtocolString(SCRendezvousProtocol proto) { switch (proto) { case kSCRendezvous_UDP: return "_osc._udp."; case kSCRendezvous_TCP: return "_osc._tcp."; default: return nullptr; }; } #endif #if defined(__APPLE__) && !defined(SC_IPHONE) # include <CoreServices/CoreServices.h> void PublishPortToRendezvous(SCRendezvousProtocol protocol, short portNum) { scprintf("PublishPortToRendezvous %d %hu\n", protocol, portNum); CFStringRef serviceType = 0; switch (protocol) { case kSCRendezvous_UDP: serviceType = CFSTR("_osc._udp."); break; case kSCRendezvous_TCP: serviceType = CFSTR("_osc._tcp."); break; } CFNetServiceRef netServiceRef = CFNetServiceCreate(NULL, // use default allocator CFSTR(""), // use default domain serviceType, CFSTR("SuperCollider"), portNum); // DEBUG if (!netServiceRef) { scprintf("Couldn't create a Rendezvous net service.\n"); return; } CFNetServiceRegisterWithOptions(netServiceRef, 0, NULL); // don't care about the error CFRelease(netServiceRef); } #elif HAVE_AVAHI # include <avahi-client/client.h> # include <avahi-client/publish.h> # include <avahi-common/alternative.h> # include <avahi-common/error.h> # include <avahi-common/malloc.h> # include <avahi-common/thread-watch.h> # include <avahi-common/timeval.h> # include <stdlib.h> # include <stdio.h> # include <SC_Lock.h> struct AvahiEntry { AvahiEntry* mNext; SCRendezvousProtocol mProto; short mPort; bool mRegistered; }; struct AvahiSession { AvahiSession(); ~AvahiSession(); void PublishPort(SCRendezvousProtocol proto, short port); void CreateServices(AvahiClient* client); void CreateServices() { CreateServices(mClient); } void ResetServices(); void RenameService(); static void client_cb(AvahiClient* client, AvahiClientState state, void* data); static void group_cb(AVAHI_GCC_UNUSED AvahiEntryGroup*, AvahiEntryGroupState state, void* data); static void modify_cb(AVAHI_GCC_UNUSED AvahiTimeout*, void* data); AvahiThreadedPoll* mPoll; AvahiClient* mClient; AvahiEntryGroup* mGroup; AvahiEntry* mEntries; SC_Lock mMutex; char* mServiceName; }; struct AvahiSessionInstance { AvahiSessionInstance(): mSession(nullptr) {} ~AvahiSessionInstance() { if (mSession) { delete mSession; } } AvahiSession* GetSession() { if (!mSession) { mSession = new AvahiSession(); } return mSession; } private: AvahiSession* mSession; }; static AvahiSessionInstance gAvahiSession; AvahiSession::AvahiSession(): mPoll(nullptr), mClient(nullptr), mGroup(nullptr), mEntries(nullptr), mServiceName(nullptr) { int err; mServiceName = avahi_strdup(kSCRendezvousServiceName); mPoll = avahi_threaded_poll_new(); if (!mPoll) { scprintf("Zeroconf: failed to create poll API\n"); return; } mClient = avahi_client_new(avahi_threaded_poll_get(mPoll), (AvahiClientFlags)0, client_cb, this, &err); if (!mClient) { scprintf("Zeroconf: failed to create client: %s\n", avahi_strerror(err)); avahi_threaded_poll_free(mPoll); mPoll = nullptr; return; } avahi_threaded_poll_start(mPoll); } AvahiSession::~AvahiSession() { if (mClient) { avahi_threaded_poll_stop(mPoll); avahi_client_free(mClient); avahi_threaded_poll_free(mPoll); AvahiEntry* entry = mEntries; while (entry) { AvahiEntry* next = entry->mNext; delete entry; entry = next; } } free(mServiceName); } void AvahiSession::client_cb(AvahiClient* client, AvahiClientState state, void* data) { AvahiSession* self = (AvahiSession*)data; switch (state) { case AVAHI_CLIENT_S_RUNNING: self->CreateServices(client); break; case AVAHI_CLIENT_S_COLLISION: self->ResetServices(); break; case AVAHI_CLIENT_FAILURE: scprintf("Zeroconf: client failure: %s\n", avahi_strerror(avahi_client_errno(self->mClient))); break; case AVAHI_CLIENT_CONNECTING: case AVAHI_CLIENT_S_REGISTERING: break; } } void AvahiSession::group_cb(AVAHI_GCC_UNUSED AvahiEntryGroup*, AvahiEntryGroupState state, void* data) { AvahiSession* self = (AvahiSession*)data; switch (state) { case AVAHI_ENTRY_GROUP_ESTABLISHED: scprintf("Zeroconf: registered service '%s'\n", self->mServiceName); break; case AVAHI_ENTRY_GROUP_COLLISION: { self->RenameService(); self->CreateServices(); break; } case AVAHI_ENTRY_GROUP_FAILURE: case AVAHI_ENTRY_GROUP_UNCOMMITED: case AVAHI_ENTRY_GROUP_REGISTERING: break; } } void AvahiSession::modify_cb(AVAHI_GCC_UNUSED AvahiTimeout* e, void* data) { AvahiSession* self = (AvahiSession*)data; if (avahi_client_get_state(self->mClient) == AVAHI_CLIENT_S_RUNNING) self->CreateServices(); } void AvahiSession::PublishPort(SCRendezvousProtocol proto, short port) { if (!mClient) return; AvahiEntry* entry = new AvahiEntry; entry->mProto = proto; entry->mPort = port; entry->mRegistered = false; mMutex.lock(); entry->mNext = mEntries; mEntries = entry; mMutex.unlock(); avahi_threaded_poll_lock(mPoll); struct timeval tv; avahi_threaded_poll_get(mPoll)->timeout_new(avahi_threaded_poll_get(mPoll), avahi_elapse_time(&tv, 0, 0), modify_cb, this); avahi_threaded_poll_unlock(mPoll); } void AvahiSession::CreateServices(AvahiClient* client) { int err; if (mGroup) { avahi_entry_group_reset(mGroup); } else { mGroup = avahi_entry_group_new(client, group_cb, this); if (!mGroup) { scprintf("Zeroconf: failed to create entry group: %s\n", avahi_strerror(avahi_client_errno(client))); return; } } mMutex.lock(); AvahiEntry* entry = mEntries; while (entry) { const char* type = SCRendezvousProtocolString(entry->mProto); err = avahi_entry_group_add_service(mGroup, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, (AvahiPublishFlags)0, mServiceName, type, nullptr, nullptr, entry->mPort, NULL); if (err == AVAHI_ERR_COLLISION) { // BUG: shouldn't this actually be triggered in the entry // group callback? RenameService(); err = avahi_entry_group_add_service(mGroup, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, (AvahiPublishFlags)0, mServiceName, type, nullptr, nullptr, entry->mPort, NULL); } if (err < 0) { scprintf("Zeroconf: failed to register service '%s': %s\n", mServiceName, avahi_strerror(err)); } entry = entry->mNext; } mMutex.unlock(); if (!avahi_entry_group_is_empty(mGroup)) { err = avahi_entry_group_commit(mGroup); if (err < 0) { scprintf("Zeroconf: failed to commit entry group: %s\n", avahi_strerror(err)); return; } } } void AvahiSession::ResetServices() { if (mGroup) avahi_entry_group_reset(mGroup); } void AvahiSession::RenameService() { char* name = avahi_alternative_service_name(mServiceName); avahi_free(mServiceName); mServiceName = name; } void PublishPortToRendezvous(SCRendezvousProtocol proto, short port) { gAvahiSession.GetSession()->PublishPort(proto, port); } #elif HAVE_HOWL # include <howl.h> # include <sys/poll.h> # include <SC_Lock.h> struct HowlSession { HowlSession(); ~HowlSession(); void PublishPort(SCRendezvousProtocol protocol, short portNum); void PublishPort(sw_discovery session, SCRendezvousProtocol protocol, short portNum); sw_discovery mSession; SC_Lock mMutex; }; struct HowlSessionInstance { HowlSessionInstance(): mSession(0) {} ~HowlSessionInstance() { if (mSession) { delete mSession; } } HowlSession* GetSession() { if (!mSession) { mSession = new HowlSession(); } return mSession; } private: HowlSession* mSession; }; static HowlSessionInstance gHowlSession; HowlSession::HowlSession(): mSession(0) {} HowlSession::~HowlSession() { if (mSession) sw_discovery_fina(mSession); } void HowlSession::PublishPort(SCRendezvousProtocol protocol, short portNum) { mMutex.lock(); if (!mSession) sw_discovery_init(&mSession); if (mSession) PublishPort(mSession, protocol, portNum); mMutex.unlock(); } sw_result howl_publish_reply_func(sw_discovery, sw_discovery_oid, sw_discovery_publish_status, sw_opaque) { return SW_OKAY; } void HowlSession::PublishPort(sw_discovery session, SCRendezvousProtocol protocol, short portNum) { const char* serviceType = SCRendezvousProtocolString(protocol); sw_discovery_oid oid; sw_result res = sw_discovery_publish(session, 0, // interface kSCRendezvousServiceName, // name serviceType, // type 0, // domain (.local) 0, // host portNum, // port 0, 0, // text records howl_publish_reply_func, 0, // reply func &oid // request id ); scprintf("Zeroconf: publishing service %s on port %hu %s\n", serviceType, portNum, res == SW_OKAY ? "succeeded" : "failed"); } void PublishPortToRendezvous(SCRendezvousProtocol protocol, short portNum) { gHowlSession.GetSession()->PublishPort(protocol, portNum); } #else // !__APPLE__ && !HAVE_AVAHI && !HAVE_HOWL void PublishPortToRendezvous(SCRendezvousProtocol protocol, short portNum) {} #endif // __APPLE__ || HAVE_AVAHI || HAVE_HOWL
11,698
C++
.cpp
328
28.597561
120
0.646388
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
29,922
SC_MiscCmds.cpp
supercollider_supercollider/server/scsynth/SC_MiscCmds.cpp
/* 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_Lib.h" #include "SC_CoreAudio.h" #include "SC_HiddenWorld.h" #include "SC_Graph.h" #include "SC_GraphDef.h" #include "SC_Group.h" #include "SC_UnitDef.h" #include <stdexcept> #include "SC_Lib_Cintf.h" #include "SC_SequencedCommand.h" #include <new> #include "SC_Prototypes.h" #include "scsynthsend.h" #include "SC_WorldOptions.h" #include "SC_Version.hpp" extern int gMissingNodeID; // returns number of bytes in an OSC string. int OSCstrlen(char* strin); Node* Msg_GetNode(World* inWorld, sc_msg_iter& msg) { Node* node; if (msg.nextTag('i') == 's') { const char* loc = msg.gets(); int32 nodeID = msg.geti(); gMissingNodeID = nodeID; node = World_GetNode(inWorld, nodeID); while (*loc) { if (!node) return nullptr; switch (*loc) { case 'h': if (!node->mIsGroup) return nullptr; node = ((Group*)node)->mHead; break; case 't': if (!node->mIsGroup) return nullptr; node = ((Group*)node)->mTail; break; case 'u': node = &node->mParent->mNode; break; case 'p': node = node->mPrev; break; case 'n': node = node->mNext; break; } loc++; } } else { int32 nodeID = msg.geti(); gMissingNodeID = nodeID; node = World_GetNode(inWorld, nodeID); } return node; } Group* Msg_GetGroup(World* inWorld, sc_msg_iter& msg) { Node* node = Msg_GetNode(inWorld, msg); return node && node->mIsGroup ? (Group*)node : nullptr; } Graph* Msg_GetGraph(World* inWorld, sc_msg_iter& msg) { Node* node = Msg_GetNode(inWorld, msg); return !node || node->mIsGroup ? nullptr : (Graph*)node; } SCErr meth_none(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_none(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { return kSCErr_None; } SCErr meth_sync(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_sync(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(SyncCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_alloc(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_alloc(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufAllocCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_free(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_free(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufFreeCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_close(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_close(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufCloseCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_allocRead(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_allocRead(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufAllocReadCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_read(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_read(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufReadCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_allocReadChannel(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_allocReadChannel(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufAllocReadChannelCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_readChannel(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_readChannel(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufReadChannelCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_write(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_write(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufWriteCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_b_zero(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_zero(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufZeroCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_u_cmd(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_u_cmd(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { return Unit_DoCmd(inWorld, inSize, inData); }; SCErr meth_cmd(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_cmd(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { return PlugIn_DoCmd(inWorld, inSize, inData, inReply); }; /* SCErr meth_n_cmd(World *inWorld, int inSize, char *inData, ReplyAddress *inReply); SCErr meth_n_cmd(World *inWorld, int inSize, char *inData, ReplyAddress *inReply) { sc_msg_iter msg(inSize, inData); Node *node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; char *args = msg.rdpos; int arglen = msg.remain(); //!! (node->mDef->fNodeCmd)(node, arglen, args); return kSCErr_None; } */ SCErr meth_n_trace(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_trace(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Node_Trace(node); } return kSCErr_None; } SCErr meth_g_dumpTree(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_dumpTree(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; int32 flag = msg.geti(); if (flag) { Group_DumpTreeAndControls(group); } else { Group_DumpTree(group); } } return kSCErr_None; } // SCErr meth_g_queryTree(World *inWorld, int inSize, char *inData, ReplyAddress *inReply); // SCErr meth_g_queryTree(World *inWorld, int inSize, char *inData, ReplyAddress* inReply) //{ // sc_msg_iter msg(inSize, inData); // while (msg.remain()) { // Group *group = Msg_GetGroup(inWorld, msg); // if (!group) return kSCErr_GroupNotFound; // // // first count the total number of nodes to know how many tags the packet should have // int numNodes = 1; // include this one // // Group_CountNodes(group, &numNodes); // // big_scpacket packet; // packet.adds("/g_queryTree.reply"); // packet.maketags(numNodes * 3 + 1); // packet.addtag(','); // // Group_QueryTree(group, &packet); // // if (packet.size()) { // CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); // } // } // return kSCErr_None; //} SCErr meth_g_queryTree(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_queryTree(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; big_scpacket packet; packet.adds("/g_queryTree.reply"); int32 flag = msg.geti(); if (flag) { // first count the total number of nodes to know how many tags the packet should have int numNodes = 1; // include this one int numControlsAndDefs = 0; Group_CountNodeAndControlTags(group, &numNodes, &numControlsAndDefs); // nodeID and numChildren + numControlsAndDefs + controlFlag packet.maketags(numNodes * 2 + numControlsAndDefs + 2); packet.addtag(','); packet.addtag('i'); packet.addi(1); // include controls flag Group_QueryTreeAndControls(group, &packet); } else { // first count the total number of nodes to know how many tags the packet should have int numNodeTags = 2; // include this one Group_CountNodeTags(group, &numNodeTags); packet.maketags(numNodeTags + 2); // nodeID and numChildren packet.addtag(','); packet.addtag('i'); packet.addi(0); // include controls flag Group_QueryTree(group, &packet); } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } } return kSCErr_None; } SCErr meth_n_run(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_run(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; int32 run = msg.geti(); Node_SetRun(node, run); } return kSCErr_None; } SCErr meth_n_map(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_map(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 8) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int bus = msg.geti(); Node_MapControl(node, Hash(name), name, 0, bus); } else { int32 index = msg.geti(); int32 bus = msg.geti(); Node_MapControl(node, index, bus); } } return kSCErr_None; } SCErr meth_n_mapn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_mapn(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 12) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); int bus = msg.geti(); int n = msg.geti(); for (int i = 0; i < n; ++i) { Node_MapControl(node, hash, name, i, bus == -1 ? -1 : bus + i); } } else { int32 index = msg.geti(); int32 bus = msg.geti(); int n = msg.geti(); for (int i = 0; i < n; ++i) { Node_MapControl(node, index + i, bus == -1 ? -1 : bus + i); } } } return kSCErr_None; } SCErr meth_n_mapa(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_mapa(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 8) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int bus = msg.geti(); Node_MapAudioControl(node, Hash(name), name, 0, bus); } else { int32 index = msg.geti(); int32 bus = msg.geti(); Node_MapAudioControl(node, index, bus); } } return kSCErr_None; } SCErr meth_n_mapan(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_mapan(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 12) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); int bus = msg.geti(); int n = msg.geti(); for (int i = 0; i < n; ++i) { Node_MapAudioControl(node, hash, name, i, bus == -1 ? -1 : bus + i); } } else { int32 index = msg.geti(); int32 bus = msg.geti(); int n = msg.geti(); for (int i = 0; i < n; ++i) { Node_MapAudioControl(node, index + i, bus == -1 ? -1 : bus + i); } } } return kSCErr_None; } SCErr meth_n_set(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_set(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 8) { int i = 0; int loop = 0; if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); do { switch (msg.nextTag('f')) { case 'f': case 'i': { float32 value = msg.getf(); Node_SetControl(node, hash, name, i, value); ++i; break; } case 's': { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Node_MapControl(node, hash, name, i, bus); ++i; } if (*string == 'a') { int bus = sc_atoi(string + 1); Node_MapAudioControl(node, hash, name, i, bus); ++i; } break; } case ']': msg.count++; loop--; break; case '[': msg.count++; loop++; break; } } while (loop); } else { int32 index = msg.geti(); do { switch (msg.nextTag('f')) { case 'f': case 'i': { float32 value = msg.getf(); Node_SetControl(node, index + i, value); ++i; break; } case 's': { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Node_MapControl(node, index + i, bus); ++i; } if (*string == 'a') { int bus = sc_atoi(string + 1); Node_MapAudioControl(node, index + i, bus); ++i; } break; } case ']': msg.count++; loop--; break; case '[': msg.count++; loop++; break; } } while (loop); } } //{ // int i = 0; // int loop = 0; // if (msg.nextTag('i') == 's') { // int32* name = msg.gets4(); // int32 hash = Hash(name); // if (msg.nextTag('f') == '[' ) { // msg.count++; // loop = 1; // } // do { // if (msg.nextTag('f') == 's' ) { // const char* string = msg.gets(); // if ( *string == 'c') { // int bus = sc_atoi(string+1); // Node_MapControl(node, hash, name, i, bus); // } // } else { // if (msg.nextTag('f') == ']' ) { // msg.count++; // loop = 0; // } else { // float32 value = msg.getf(); // Node_SetControl(node, hash, name, i, value); // } // } // ++i; // } while (loop); // } else { // int32 index = msg.geti(); // if (msg.nextTag('f') == '[' ) { // msg.count++; // loop = 1; // } // do { // if (msg.nextTag('f') == 's') { // const char* string = msg.gets(); // if (*string == 'c') { // int bus = sc_atoi(string+1); // Node_MapControl(node, index + i, bus); // } // } else { // if (msg.nextTag('f') == ']' ) { // msg.count++; // loop = 0; // } else { // float32 value = msg.getf(); // Node_SetControl(node, index + i, value); // } // } // ++i; // } while (loop); // } // } return kSCErr_None; } SCErr meth_n_setn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_setn(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain()) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); int32 n = msg.geti(); for (int i = 0; msg.remain() && i < n; ++i) { if (msg.nextTag('f') == 's') { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Node_MapControl(node, hash, name, i, bus); } if (*string == 'a') { int bus = sc_atoi(string + 1); Node_MapAudioControl(node, hash, name, i, bus); } } else { float32 value = msg.getf(); Node_SetControl(node, hash, name, i, value); } } } else { int32 index = msg.geti(); int32 n = msg.geti(); for (int i = 0; msg.remain() && i < n; ++i) { if (msg.nextTag('f') == 's') { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); Node_MapControl(node, index + i, bus); } if (*string == 'a') { int bus = sc_atoi(string + 1); Node_MapAudioControl(node, index + i, bus); } } else { float32 value = msg.getf(); Node_SetControl(node, index + i, value); } } } } return kSCErr_None; } SCErr meth_n_fill(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_fill(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; while (msg.remain() >= 12) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); int32 n = msg.geti(); float32 value = msg.getf(); for (int i = 0; i < n; ++i) { Node_SetControl(node, hash, name, i, value); } if (msg.nextTag('f') == 's') { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); for (int i = 0; i < n; ++i) { Node_MapControl(node, hash, name, i, bus + i); } } } else { float32 value = msg.getf(); for (int i = 0; i < n; ++i) { Node_SetControl(node, hash, name, i, value); } } } else { int32 index = msg.geti(); int32 n = msg.geti(); float32 value = msg.getf(); for (int i = 0; i < n; ++i) { Node_SetControl(node, index + i, value); } if (msg.nextTag('f') == 's') { const char* string = msg.gets(); if (*string == 'c') { int bus = sc_atoi(string + 1); for (int i = 0; i < n; ++i) { Node_MapControl(node, index + i, bus + i); } } } else { float32 value = msg.getf(); for (int i = 0; i < n; ++i) { Node_SetControl(node, index + i, value); } } } } return kSCErr_None; } SCErr meth_n_query(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_query(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Node_StateMsg(node, kNode_Info); } return kSCErr_None; } SCErr meth_b_query(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_query(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); small_scpacket packet; int numbufs = msg.remain() >> 2; packet.adds("/b_info"); packet.maketags(numbufs * 4 + 1); packet.addtag(','); while (msg.remain()) { int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); packet.addtag('i'); packet.addtag('i'); packet.addtag('i'); packet.addtag('f'); packet.addi(bufindex); packet.addi(buf->frames); packet.addi(buf->channels); packet.addf(buf->samplerate); } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_d_load(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_d_load(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(LoadSynthDefCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_d_recv(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_d_recv(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(RecvSynthDefCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_d_loadDir(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_d_loadDir(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(LoadSynthDefDirCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_d_freeAll(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_d_freeAll(World* inWorld, int /*inSize*/, char* /*inData*/, ReplyAddress* /*inReply*/) { World_FreeAllGraphDefs(inWorld); return kSCErr_None; } SCErr meth_d_free(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_d_free(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { int32* defname = msg.gets4(); if (!defname) return kSCErr_SynthDefNotFound; SCErr err = GraphDef_Remove(inWorld, defname); if (err != kSCErr_None) return err; } return kSCErr_None; } SCErr meth_s_new(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_s_new(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { SCErr err; sc_msg_iter msg(inSize, inData); int32* defname = msg.gets4(); if (!defname) return kSCErr_WrongArgType; int32 nodeID = msg.geti(); int32 addAction = msg.geti(); GraphDef* def = World_GetGraphDef(inWorld, defname); if (!def) { scprintf("*** ERROR: SynthDef %s not found\n", (char*)defname); return kSCErr_SynthDefNotFound; } Graph* graph = nullptr; switch (addAction) { case 0: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, true); // true for normal args if (err) return err; if (!graph) return kSCErr_Failed; Group_AddHead(group, &graph->mNode); } break; case 1: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, true); if (err) return err; Group_AddTail(group, &graph->mNode); } break; case 2: { Node* beforeThisNode = Msg_GetNode(inWorld, msg); if (!beforeThisNode) return kSCErr_NodeNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, true); if (err) return err; Node_AddBefore(&graph->mNode, beforeThisNode); } break; case 3: { Node* afterThisNode = Msg_GetNode(inWorld, msg); if (!afterThisNode) return kSCErr_NodeNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, true); if (err) return err; Node_AddAfter(&graph->mNode, afterThisNode); } break; case 4: { Node* replaceThisNode = Msg_GetNode(inWorld, msg); if (!replaceThisNode) return kSCErr_NodeNotFound; Node_RemoveID(replaceThisNode); err = Graph_New(inWorld, def, nodeID, &msg, &graph, true); if (err) return err; Node_Replace(&graph->mNode, replaceThisNode); } break; default: return kSCErr_Failed; } Node_StateMsg(&graph->mNode, kNode_Go); return kSCErr_None; } SCErr meth_s_newargs(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_s_newargs(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { SCErr err; sc_msg_iter msg(inSize, inData); int32* defname = msg.gets4(); if (!defname) return kSCErr_WrongArgType; int32 nodeID = msg.geti(); int32 addAction = msg.geti(); GraphDef* def = World_GetGraphDef(inWorld, defname); if (!def) { scprintf("*** ERROR: SynthDef %s not found\n", (char*)defname); return kSCErr_SynthDefNotFound; } Graph* graph = nullptr; switch (addAction) { case 0: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, false); // false for setn type args if (err) return err; if (!graph) return kSCErr_Failed; Group_AddHead(group, &graph->mNode); } break; case 1: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, false); if (err) return err; Group_AddTail(group, &graph->mNode); } break; case 2: { Node* beforeThisNode = Msg_GetNode(inWorld, msg); if (!beforeThisNode) return kSCErr_NodeNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, false); if (err) return err; Node_AddBefore(&graph->mNode, beforeThisNode); } break; case 3: { Node* afterThisNode = Msg_GetNode(inWorld, msg); if (!afterThisNode) return kSCErr_NodeNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, false); if (err) return err; Node_AddAfter(&graph->mNode, afterThisNode); } break; case 4: { Node* replaceThisNode = Msg_GetNode(inWorld, msg); if (!replaceThisNode) return kSCErr_NodeNotFound; err = Graph_New(inWorld, def, nodeID, &msg, &graph, false); if (err) return err; Node_Replace(&graph->mNode, replaceThisNode); } break; default: return kSCErr_Failed; } Node_StateMsg(&graph->mNode, kNode_Go); return kSCErr_None; } SCErr meth_g_new(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_new(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { SCErr err; sc_msg_iter msg(inSize, inData); while (msg.remain()) { int32 newGroupID = msg.geti(); int32 addAction = msg.geti(); Group* newGroup = nullptr; switch (addAction) { case 0: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Group_New(inWorld, newGroupID, &newGroup); if (err) { if (err == kSCErr_DuplicateNodeID) { newGroup = World_GetGroup(inWorld, newGroupID); if (!newGroup || !newGroup->mNode.mParent || newGroup->mNode.mParent != group) return err; } else return err; } else { Group_AddHead(group, &newGroup->mNode); } } break; case 1: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; err = Group_New(inWorld, newGroupID, &newGroup); if (err) { if (err == kSCErr_DuplicateNodeID) { newGroup = World_GetGroup(inWorld, newGroupID); if (!newGroup || !newGroup->mNode.mParent || newGroup->mNode.mParent != group) return err; } else return err; } else { Group_AddTail(group, &newGroup->mNode); } } break; case 2: { Node* beforeThisNode = Msg_GetNode(inWorld, msg); if (!beforeThisNode) return kSCErr_TargetNodeNotFound; err = Group_New(inWorld, newGroupID, &newGroup); if (err) { if (err == kSCErr_DuplicateNodeID) { newGroup = World_GetGroup(inWorld, newGroupID); if (!newGroup || !newGroup->mNode.mParent || newGroup->mNode.mParent->mNode.mID != beforeThisNode->mParent->mNode.mID) return err; } else return err; } else { Node_AddBefore(&newGroup->mNode, beforeThisNode); } } break; case 3: { Node* afterThisNode = Msg_GetNode(inWorld, msg); if (!afterThisNode) return kSCErr_TargetNodeNotFound; err = Group_New(inWorld, newGroupID, &newGroup); if (err) { if (err == kSCErr_DuplicateNodeID) { newGroup = World_GetGroup(inWorld, newGroupID); if (!newGroup || !newGroup->mNode.mParent || newGroup->mNode.mParent->mNode.mID != afterThisNode->mParent->mNode.mID) return err; } else return err; } else { Node_AddAfter(&newGroup->mNode, afterThisNode); } } break; case 4: { Node* replaceThisNode = Msg_GetNode(inWorld, msg); if (!replaceThisNode) return kSCErr_TargetNodeNotFound; if (replaceThisNode->mID == 0) return kSCErr_ReplaceRootGroup; Node_RemoveID(replaceThisNode); err = Group_New(inWorld, newGroupID, &newGroup); if (err) return err; Node_Replace(&newGroup->mNode, replaceThisNode); } break; default: return kSCErr_Failed; } Node_StateMsg(&newGroup->mNode, kNode_Go); } return kSCErr_None; } SCErr meth_p_new(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_p_new(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { /* we emulate the concept of parallel groups by using sequential groups */ return meth_g_new(inWorld, inSize, inData, inReply); } SCErr meth_n_free(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_free(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Node_Delete(node); } return kSCErr_None; } SCErr meth_n_before(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_before(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* prevNode = nullptr; Node* prevTarget = nullptr; while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); Node* target = Msg_GetNode(inWorld, msg); if (!node || !target) continue; // tolerate failure if (prevNode && prevNode != node) { // move the last pair that succeeded Node_Remove(prevNode); Node_AddBefore(prevNode, prevTarget); Node_StateMsg(prevNode, kNode_Move); } prevNode = node; prevTarget = target; } if (prevNode && prevNode != prevTarget) { // move the last pair that succeeded Node_Remove(prevNode); Node_AddBefore(prevNode, prevTarget); Node_StateMsg(prevNode, kNode_Move); } return kSCErr_None; } SCErr meth_n_after(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_after(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); Node* prevNode = nullptr; Node* prevTarget = nullptr; while (msg.remain()) { Node* node = Msg_GetNode(inWorld, msg); Node* target = Msg_GetNode(inWorld, msg); if (!node || !target) continue; // tolerate failure if (prevNode && prevNode != node) { // move the last pair that succeeded Node_Remove(prevNode); Node_AddAfter(prevNode, prevTarget); Node_StateMsg(prevNode, kNode_Move); } prevNode = node; prevTarget = target; } if (prevNode) { // move the last pair that succeeded Node_Remove(prevNode); Node_AddAfter(prevNode, prevTarget); Node_StateMsg(prevNode, kNode_Move); } return kSCErr_None; } SCErr meth_n_order(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_n_order(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { Node* prevNode = nullptr; Node* node = nullptr; sc_msg_iter msg(inSize, inData); int32 addAction = msg.geti(); // place the first node in the list based on target and addAction switch (addAction) { case 0: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; while (!node && msg.remain()) { node = Msg_GetNode(inWorld, msg); if (!node) scprintf("Warning Node not found\n"); } if (!node) return kSCErr_NodeNotFound; Group* prevGroup = node->mParent; Node_Remove(node); Group_AddHead(group, node); if (group != prevGroup) { Node_StateMsg(node, kNode_Move); } prevNode = node; } break; case 1: { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; while (!node && msg.remain()) { node = Msg_GetNode(inWorld, msg); if (!node) scprintf("Warning Node not found\n"); } if (!node) return kSCErr_NodeNotFound; Group* prevGroup = node->mParent; Node_Remove(node); Group_AddTail(group, node); if (group != prevGroup) { Node_StateMsg(node, kNode_Move); } prevNode = node; } break; case 2: { Node* beforeNode = Msg_GetNode(inWorld, msg); if (!beforeNode) return kSCErr_TargetNodeNotFound; while (!node && msg.remain()) { node = Msg_GetNode(inWorld, msg); if (!node) scprintf("Warning Node not found\n"); } if (!node) return kSCErr_NodeNotFound; Node_Remove(node); Node_AddBefore(node, beforeNode); Node_StateMsg(node, kNode_Move); prevNode = node; } break; case 3: { Node* afterNode = Msg_GetNode(inWorld, msg); if (!afterNode) return kSCErr_TargetNodeNotFound; while (!node && msg.remain()) { node = Msg_GetNode(inWorld, msg); if (!node) scprintf("Warning Node not found\n"); } if (!node) return kSCErr_NodeNotFound; Node_Remove(node); Node_AddAfter(node, afterNode); Node_StateMsg(node, kNode_Move); prevNode = node; } break; default: return kSCErr_Failed; } // now iterate through in order while (msg.remain()) { node = Msg_GetNode(inWorld, msg); if (!node) { scprintf("Warning Node not found\n"); continue; } Node_Remove(node); Node_AddAfter(node, prevNode); Node_StateMsg(node, kNode_Move); prevNode = node; } return kSCErr_None; } SCErr meth_g_head(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_head(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Node_Remove(node); Group_AddHead(group, node); Node_StateMsg(node, kNode_Move); } return kSCErr_None; } SCErr meth_g_tail(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_tail(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Node_Remove(node); Group_AddTail(group, node); Node_StateMsg(node, kNode_Move); } return kSCErr_None; } SCErr meth_g_insert(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_insert(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; Node* node = Msg_GetNode(inWorld, msg); if (!node) return kSCErr_NodeNotFound; Group* prevGroup = node->mParent; int index = msg.geti(); Node_Remove(node); Group_Insert(group, node, index); if (group != prevGroup) { Node_StateMsg(node, kNode_Move); } } return kSCErr_None; } SCErr meth_g_freeAll(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_freeAll(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; Group_DeleteAll(group); } return kSCErr_None; } SCErr meth_g_deepFree(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_g_deepFree(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Group* group = Msg_GetGroup(inWorld, msg); if (!group) return kSCErr_GroupNotFound; Group_DeepFreeGraphs(group); } return kSCErr_None; } SCErr meth_status(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_status(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(AudioStatusCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_rtMemoryStatus(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_rtMemoryStatus(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(RTMemStatusCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_quit(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_quit(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(AudioQuitCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_clearSched(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_clearSched(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { if (inWorld->mRealTime) { inWorld->hw->mAudioDriver->ClearSched(); } return kSCErr_None; } SCErr meth_dumpOSC(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_dumpOSC(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); inWorld->mDumpOSC = msg.geti(); return kSCErr_None; } SCErr meth_version(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_version(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); small_scpacket packet; packet.adds("/version.reply"); packet.maketags(7); packet.addtag(','); packet.addtag('s'); packet.adds("scsynth"); packet.addtag('i'); packet.addi(SC_VersionMajor); packet.addtag('i'); packet.addi(SC_VersionMinor); packet.addtag('s'); packet.adds(SC_VersionPostfix); packet.addtag('s'); packet.adds(SC_BranchOrTag); packet.addtag('s'); packet.adds(SC_CommitHash); CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); return kSCErr_None; } SCErr meth_b_set(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_set(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); if (!buf) return kSCErr_Failed; float* data = buf->data; uint32 numSamples = buf->samples; while (msg.remain() >= 8) { uint32 sampleIndex = msg.geti(); float32 value = msg.getf(); if (sampleIndex < numSamples) { data[sampleIndex] = value; } else return kSCErr_IndexOutOfRange; } return kSCErr_None; } SCErr meth_b_setn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_setn(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); if (!buf) return kSCErr_Failed; float* data = buf->data; int numSamples = buf->samples; while (msg.remain()) { int32 start = msg.geti(); int32 n = msg.geti(); int32 end = start + n - 1; if (end < 0 || start >= numSamples) continue; start = sc_clip(start, 0, numSamples - 1); end = sc_clip(end, 0, numSamples - 1); for (int i = start; msg.remain() && i <= end; ++i) { float32 value = msg.getf(); data[i] = value; } } return kSCErr_None; } SCErr meth_b_fill(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_fill(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); if (!buf) return kSCErr_Failed; float* data = buf->data; int numSamples = buf->samples; while (msg.remain() >= 12) { int32 start = msg.geti(); int32 n = msg.geti(); float32 value = msg.getf(); int32 end = start + n - 1; if (end < 0 || start >= numSamples) continue; start = sc_clip(start, 0, numSamples - 1); end = sc_clip(end, 0, numSamples - 1); for (int i = start; i <= end; ++i) data[i] = value; } return kSCErr_None; } SCErr meth_b_gen(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_gen(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(BufGenCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_c_set(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_c_set(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); float* data = inWorld->mControlBus; int32* touched = inWorld->mControlBusTouched; int32 bufCounter = inWorld->mBufCounter; uint32 maxIndex = inWorld->mNumControlBusChannels; while (msg.remain() >= 8) { uint32 index = msg.geti(); float32 value = msg.getf(); if (index < maxIndex) { data[index] = value; touched[index] = bufCounter; } else return kSCErr_IndexOutOfRange; } return kSCErr_None; } SCErr meth_c_setn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_c_setn(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); float* data = inWorld->mControlBus; int32* touched = inWorld->mControlBusTouched; int32 bufCounter = inWorld->mBufCounter; int maxIndex = inWorld->mNumControlBusChannels; while (msg.remain()) { int32 start = msg.geti(); int32 n = msg.geti(); int32 end = start + n - 1; if (start < 0 || end >= maxIndex || start > end) return kSCErr_IndexOutOfRange; for (int i = start; msg.remain() && i <= end; ++i) { float32 value = msg.getf(); data[i] = value; touched[i] = bufCounter; } } return kSCErr_None; } SCErr meth_c_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_c_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); float* data = inWorld->mControlBus; uint32 maxIndex = inWorld->mNumControlBusChannels; int numheads = msg.remain() >> 2; big_scpacket packet; packet.adds("/c_set"); packet.maketags(numheads * 2 + 1); packet.addtag(','); while (msg.remain() >= 4) { uint32 index = msg.geti(); if (index >= maxIndex) return kSCErr_IndexOutOfRange; packet.addtag('i'); packet.addtag('f'); packet.addi(index); packet.addf(data[index]); } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_c_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_c_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); float* data = inWorld->mControlBus; int maxIndex = inWorld->mNumControlBusChannels; // figure out how many tags to allocate int numcontrols = 0; int numheads = msg.remain() >> 3; while (msg.remain()) { msg.geti(); // skip start int32 n = msg.geti(); numcontrols += n; } big_scpacket packet; packet.adds("/c_setn"); packet.maketags(numheads * 2 + numcontrols + 1); packet.addtag(','); // start over at beginning of message msg.init(inSize, inData); while (msg.remain()) { int32 start = msg.geti(); int32 n = msg.geti(); int32 end = start + n - 1; if (start < 0 || end >= maxIndex || start > end) return kSCErr_IndexOutOfRange; packet.addtag('i'); packet.addtag('i'); packet.addi(start); packet.addi(n); for (int i = start; i <= end; ++i) { packet.addtag('f'); packet.addf(data[i]); } } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_c_fill(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_c_fill(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); float* data = inWorld->mControlBus; int32* touched = inWorld->mControlBusTouched; int32 bufCounter = inWorld->mBufCounter; int maxIndex = inWorld->mNumControlBusChannels; while (msg.remain() >= 12) { int32 start = msg.geti(); int32 n = msg.geti(); float32 value = msg.getf(); int32 end = start + n - 1; if (end < 0 || start >= maxIndex) continue; start = sc_clip(start, 0, maxIndex - 1); end = sc_clip(end, 0, maxIndex - 1); for (int i = start; i <= end; ++i) { data[i] = value; touched[i] = bufCounter; } } return kSCErr_None; } SCErr meth_b_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); if (!buf) return kSCErr_Failed; float* data = buf->data; uint32 maxIndex = buf->samples; int numheads = msg.remain() >> 2; big_scpacket packet; packet.adds("/b_set"); packet.maketags(numheads * 2 + 2); packet.addtag(','); packet.addtag('i'); packet.addi(bufindex); while (msg.remain() >= 4) { uint32 index = msg.geti(); if (index >= maxIndex) return kSCErr_IndexOutOfRange; packet.addtag('i'); packet.addtag('f'); packet.addi(index); packet.addf(data[index]); } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_b_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_b_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); int bufindex = msg.geti(); SndBuf* buf = World_GetBuf(inWorld, bufindex); if (!buf) return kSCErr_Failed; float* data = buf->data; int32 maxIndex = buf->samples; // figure out how many tags to allocate int numcontrols = 0; int numheads = msg.remain() >> 3; while (msg.remain()) { msg.geti(); // skip start int32 n = msg.geti(); numcontrols += n; } big_scpacket packet; packet.adds("/b_setn"); packet.maketags(numheads * 2 + numcontrols + 2); packet.addtag(','); // start over at beginning of message msg.init(inSize, inData); msg.geti(); // skip buf index packet.addtag('i'); packet.addi(bufindex); while (msg.remain()) { int32 start = msg.geti(); int32 n = msg.geti(); int32 end = start + n - 1; if (start < 0 || end >= maxIndex || start > end) return kSCErr_IndexOutOfRange; packet.addtag('i'); packet.addtag('i'); packet.addi(start); packet.addi(n); for (int i = start; i <= end; ++i) { packet.addtag('f'); packet.addf(data[i]); } } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_s_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_s_get(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); Graph* graph = Msg_GetGraph(inWorld, msg); if (!graph) return kSCErr_NodeNotFound; int numheads = msg.tags ? strlen(msg.tags) - 1 : msg.remain() >> 2; big_scpacket packet; packet.adds("/n_set"); packet.maketags(numheads * 2 + 2); packet.addtag(','); packet.addtag('i'); packet.addi(graph->mNode.mID); while (msg.remain() >= 4) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); float32 value = 0.f; Graph_GetControl(graph, hash, name, 0, value); packet.addtag('s'); packet.addtag('f'); packet.adds((char*)name); packet.addf(value); } else { int32 index = msg.geti(); float32 value = 0.f; Graph_GetControl(graph, index, value); packet.addtag('i'); packet.addtag('f'); packet.addi(index); packet.addf(value); } } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_s_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_s_getn(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); Graph* graph = Msg_GetGraph(inWorld, msg); if (!graph) return kSCErr_NodeNotFound; // figure out how many tags to allocate int numcontrols = 0; int numheads = msg.tags ? (strlen(msg.tags) - 1) >> 1 : msg.remain() >> 3; while (msg.remain()) { msg.geti(); // skip start int32 n = msg.geti(); numcontrols += n; } big_scpacket packet; packet.adds("/n_setn"); packet.maketags(numheads * 2 + numcontrols + 2); packet.addtag(','); // start over at beginning of message msg.init(inSize, inData); msg.geti(); // skip buf index packet.addtag('i'); packet.addi(graph->mNode.mID); while (msg.remain()) { if (msg.nextTag('i') == 's') { int32* name = msg.gets4(); int32 hash = Hash(name); int32 n = msg.geti(); packet.addtag('s'); packet.addtag('i'); packet.adds((char*)name); packet.addi(n); for (int i = 0; i < n; ++i) { float32 value = 0.f; Graph_GetControl(graph, hash, name, i, value); packet.addtag('f'); packet.addf(value); } } else { int32 index = msg.geti(); int32 n = msg.geti(); packet.addtag('i'); packet.addtag('i'); packet.addi(index); packet.addi(n); for (int i = 0; i < n; ++i) { float32 value = 0.f; Graph_GetControl(graph, index + i, value); packet.addtag('f'); packet.addf(value); } } } if (packet.size()) { CallSequencedCommand(SendReplyCmd, inWorld, packet.size(), packet.data(), inReply); } return kSCErr_None; } SCErr meth_s_noid(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_s_noid(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { sc_msg_iter msg(inSize, inData); while (msg.remain()) { Graph* graph = Msg_GetGraph(inWorld, msg); if (!graph) continue; Node_RemoveID(&graph->mNode); } return kSCErr_None; } SCErr meth_notify(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_notify(World* inWorld, int inSize, char* inData, ReplyAddress* inReply) { CallSequencedCommand(NotifyCmd, inWorld, inSize, inData, inReply); return kSCErr_None; } SCErr meth_error(World* inWorld, int inSize, char* inData, ReplyAddress* inReply); SCErr meth_error(World* inWorld, int inSize, char* inData, ReplyAddress* /*inReply*/) { sc_msg_iter msg(inSize, inData); int mode = msg.geti(); // inWorld->mLocalErrorNotification = mode; // // if non-zero, new state should be saved permanently // if(mode) { inWorld->mErrorNotification = mode; }; // -1 = bundle off, -2 = bundle on, 0 = permanent off, 1 = permanent on switch (mode) { case -1: inWorld->mLocalErrorNotification += 1; break; case -2: inWorld->mLocalErrorNotification -= 1; break; case 0: inWorld->mErrorNotification = 0; break; case 1: inWorld->mErrorNotification = 1; }; return kSCErr_None; } #define NEW_COMMAND(name) NewCommand(#name, cmd_##name, meth_##name) void initMiscCommands(); void initMiscCommands() { // nrt NEW_COMMAND(none); NEW_COMMAND(notify); NEW_COMMAND(status); NEW_COMMAND(quit); NEW_COMMAND(clearSched); NEW_COMMAND(version); NEW_COMMAND(rtMemoryStatus); NEW_COMMAND(d_recv); NEW_COMMAND(d_load); NEW_COMMAND(d_loadDir); NEW_COMMAND(d_freeAll); NEW_COMMAND(d_free); NEW_COMMAND(s_new); NEW_COMMAND(s_newargs); NEW_COMMAND(n_trace); NEW_COMMAND(n_free); NEW_COMMAND(n_run); NEW_COMMAND(u_cmd); NEW_COMMAND(cmd); // NEW_COMMAND(n_cmd); NEW_COMMAND(n_map); NEW_COMMAND(n_mapn); NEW_COMMAND(n_mapa); NEW_COMMAND(n_mapan); NEW_COMMAND(n_set); NEW_COMMAND(n_setn); NEW_COMMAND(n_fill); NEW_COMMAND(n_before); NEW_COMMAND(n_after); NEW_COMMAND(n_order); NEW_COMMAND(g_new); NEW_COMMAND(g_head); NEW_COMMAND(g_tail); NEW_COMMAND(g_freeAll); NEW_COMMAND(g_deepFree); NEW_COMMAND(p_new); NEW_COMMAND(b_alloc); NEW_COMMAND(b_allocRead); NEW_COMMAND(b_allocReadChannel); NEW_COMMAND(b_read); NEW_COMMAND(b_readChannel); NEW_COMMAND(b_write); NEW_COMMAND(b_free); NEW_COMMAND(b_close); NEW_COMMAND(b_zero); NEW_COMMAND(b_set); NEW_COMMAND(b_setn); NEW_COMMAND(b_fill); NEW_COMMAND(b_gen); NEW_COMMAND(c_set); NEW_COMMAND(c_setn); NEW_COMMAND(c_fill); NEW_COMMAND(dumpOSC); NEW_COMMAND(c_get); NEW_COMMAND(c_getn); NEW_COMMAND(b_get); NEW_COMMAND(b_getn); NEW_COMMAND(s_get); NEW_COMMAND(s_getn); NEW_COMMAND(n_query); NEW_COMMAND(b_query); NEW_COMMAND(s_noid); NEW_COMMAND(sync); NEW_COMMAND(g_dumpTree); NEW_COMMAND(g_queryTree); NEW_COMMAND(error); }
60,966
C++
.cpp
1,658
28.470446
104
0.580718
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
29,923
sc_ugen_factory.cpp
supercollider_supercollider/server/supernova/sc/sc_ugen_factory.cpp
// prototype of a supercollider-synthdef-based synth prototype // Copyright (C) 2009-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; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. /* \todo for now we use dlopen, later we want to become cross-platform */ #ifdef DLOPEN # include <dlfcn.h> #elif defined(_WIN32) # include "SC_Win32Utils.h" # include "SC_Codecvt.hpp" #endif #include <filesystem> #include "sc_ugen_factory.hpp" #include "SC_World.h" #include "SC_Wire.h" #include "ErrorMessage.hpp" #include "SC_Filesystem.hpp" // SC_PLUGIN_EXT namespace nova { std::unique_ptr<sc_ugen_factory> sc_factory; Unit* sc_ugen_def::construct(sc_synthdef::unit_spec_t const& unit_spec, sc_synth* parent, int parentIndex, World* world, linear_allocator& allocator) { const int buffer_length = world->mBufLength; const size_t output_count = unit_spec.output_specs.size(); /* size for wires and buffers */ uint8_t* chunk = allocator.alloc<uint8_t>(memory_requirement()); memset(chunk, 0, memory_requirement()); Unit* unit = (Unit*)(std::uintptr_t(chunk + 63) & (~63)); // align on 64 byte boundary unit->mInBuf = allocator.alloc<float*>(unit_spec.input_specs.size()); unit->mOutBuf = allocator.alloc<float*>(unit_spec.output_specs.size()); unit->mInput = allocator.alloc<Wire*>(unit_spec.input_specs.size()); unit->mOutput = allocator.alloc<Wire*>(unit_spec.output_specs.size()); unit->mNumInputs = unit_spec.input_specs.size(); unit->mNumOutputs = unit_spec.output_specs.size(); /* initialize members */ unit->mCalcRate = unit_spec.rate; unit->mSpecialIndex = unit_spec.special_index; unit->mDone = false; unit->mUnitDef = reinterpret_cast<struct UnitDef*>(this); /* we abuse this field to store our reference */ unit->mWorld = world; /* initialize members from synth */ unit->mParent = static_cast<Graph*>(parent); unit->mParentIndex = parentIndex; if (unit_spec.rate == 2) unit->mRate = &world->mFullRate; else unit->mRate = &world->mBufRate; unit->mBufLength = unit->mRate->mBufLength; float* buffer_base = parent->unit_buffers; /* allocate buffers */ for (size_t i = 0; i != output_count; ++i) { Wire* w = allocator.alloc<Wire>(); w->mFromUnit = unit; w->mCalcRate = unit->mCalcRate; w->mBuffer = nullptr; w->mScalarValue = 0; if (unit->mCalcRate == 2) { /* allocate a new buffer */ assert(unit_spec.buffer_mapping[i] >= 0); std::size_t buffer_id = unit_spec.buffer_mapping[i]; unit->mOutBuf[i] = buffer_base + buffer_length * buffer_id; w->mBuffer = unit->mOutBuf[i]; } else unit->mOutBuf[i] = &w->mScalarValue; unit->mOutput[i] = w; } /* prepare inputs */ for (size_t i = 0; i != unit_spec.input_specs.size(); ++i) { int source = unit_spec.input_specs[i].source; int index = unit_spec.input_specs[i].index; if (source == -1) unit->mInput[i] = &unit->mParent->mWire[index]; else { Unit* prev = parent->units[source]; unit->mInput[i] = prev->mOutput[index]; } if (unit->mInput[i]->mCalcRate == 2) unit->mInBuf[i] = unit->mInput[i]->mBuffer; else unit->mInBuf[i] = &unit->mInput[i]->mScalarValue; } return unit; } bool sc_ugen_def::add_command(const char* cmd_name, UnitCmdFunc func) { sc_unitcmd_def* def = new sc_unitcmd_def(cmd_name, func); unitcmd_set.insert(*def); return true; } void sc_ugen_def::run_unit_command(const char* cmd_name, Unit* unit, struct sc_msg_iter* args) { unitcmd_set_type::iterator it = unitcmd_set.find(cmd_name, named_hash_hash(), named_hash_equal()); if (it != unitcmd_set.end()) { it->run(unit, args); } else { std::cout << "can't find unit command: " << cmd_name << std::endl; } } sample* sc_bufgen_def::run(World* world, uint32_t buffer_index, struct sc_msg_iter* args) { SndBuf* buf = World_GetNRTBuf(world, buffer_index); sample* data = buf->data; (func)(world, buf, args); if (data == buf->data) return nullptr; else return data; } void sc_plugin_container::register_ugen(const char* inUnitClassName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags) { sc_ugen_def* def = new sc_ugen_def(inUnitClassName, inAllocSize, inCtor, inDtor, inFlags); ugen_set.insert(*def); } void sc_plugin_container::register_bufgen(const char* name, BufGenFunc func) { sc_bufgen_def* def = new sc_bufgen_def(name, func); bufgen_set.insert(*def); } sc_ugen_def* sc_plugin_container::find_ugen(symbol const& name) { ugen_set_type::iterator it = ugen_set.find(name, named_hash_hash(), named_hash_equal()); if (it == ugen_set.end()) return nullptr; return &*it; } bool sc_plugin_container::register_ugen_command_function(const char* ugen_name, const char* cmd_name, UnitCmdFunc func) { sc_ugen_def* def = find_ugen(symbol(ugen_name)); if (!def) { std::cout << "unable to register ugen command: ugen '" << ugen_name << "' doesn't exist" << std::endl; return false; } return def->add_command(cmd_name, func); } bool sc_plugin_container::register_cmd_plugin(const char* cmd_name, PlugInCmdFunc func, void* user_data) { cmdplugin_set_type::iterator it = cmdplugin_set.find(cmd_name, named_hash_hash(), named_hash_equal()); if (it != cmdplugin_set.end()) { std::cout << "cmd plugin already registered: " << cmd_name << std::endl; return false; } sc_cmdplugin_def* def = new sc_cmdplugin_def(cmd_name, func, user_data); cmdplugin_set.insert(*def); return true; } sample* sc_plugin_container::run_bufgen(World* world, const char* name, uint32_t buffer_index, struct sc_msg_iter* args) { bufgen_set_type::iterator it = bufgen_set.find(name, named_hash_hash(), named_hash_equal()); if (it == bufgen_set.end()) { std::cout << "unable to find buffer generator: " << name << std::endl; return nullptr; } return it->run(world, buffer_index, args); } bool sc_plugin_container::run_cmd_plugin(World* world, const char* name, struct sc_msg_iter* args, void* replyAddr) { cmdplugin_set_type::iterator it = cmdplugin_set.find(name, named_hash_hash(), named_hash_equal()); if (it == cmdplugin_set.end()) { std::cout << "unable to find cmd plugin: " << name << std::endl; return false; } it->run(world, args, replyAddr); return true; } void sc_ugen_factory::load_plugin_folder(std::filesystem::path const& path) { using namespace std::filesystem; directory_iterator end; if (!is_directory(path)) return; for (directory_iterator it(path); it != end; ++it) { if (is_regular_file(it->status())) load_plugin(it->path()); if (is_directory(it->status())) load_plugin_folder(it->path()); } } static bool check_api_version(int (*api_version)(), std::string const& filename) { using namespace std; using namespace scsynth; if (api_version) { int plugin_version = (*api_version)(); if (plugin_version == sc_api_version) return true; else cout << ErrorMessage::apiVersionMismatch(filename, sc_api_version, plugin_version) << endl; } else { cout << ErrorMessage::apiVersionNotFound(filename) << endl; } return false; } #ifdef DLOPEN void sc_ugen_factory::load_plugin(std::filesystem::path const& path) { using namespace std; // Ignore files that don't have the extension of an SC plugin if (path.extension() != SC_PLUGIN_EXT) { return; } void* handle = dlopen(path.string().c_str(), RTLD_NOW | RTLD_LOCAL); if (handle == nullptr) return; typedef int (*info_function)(); info_function api_version = reinterpret_cast<info_function>(dlsym(handle, "api_version")); if (!check_api_version(api_version, path.string())) { dlclose(handle); return; } info_function supernova_check = reinterpret_cast<info_function>(dlsym(handle, "server_type")); if (!supernova_check || (*supernova_check)() == sc_server_scsynth) { // silently ignore dlclose(handle); return; } void* load_symbol = dlsym(handle, "load"); if (!load_symbol) { cout << "Problem when loading plugin: \"load\" function undefined" << path << endl; dlclose(handle); return; } open_handles.push_back(handle); LoadPlugInFunc load_func = reinterpret_cast<LoadPlugInFunc>(load_symbol); (*load_func)(&sc_interface); /* don't close the handle */ return; } void sc_ugen_factory::close_handles(void) { for (void* handle : open_handles) { void* ptr = dlsym(handle, "unload"); if (ptr) { UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr; (*unloadFunc)(); } dlclose(handle); } } #elif defined(_WIN32) void sc_ugen_factory::load_plugin(std::filesystem::path const& path) { // Ignore files that don't have the extension of an SC plugin if (path.extension() != SC_PLUGIN_EXT) { return; } // std::cout << "try open plugin: " << path << std::endl; const char* filename = path.string().c_str(); HINSTANCE hinstance = LoadLibraryW(path.wstring().c_str()); if (!hinstance) { wchar_t* s; DWORD lastErr = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, lastErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*)&s, 0, NULL); std::cout << "Cannot open plugin: " << path << SC_Codecvt::utf16_wcstr_to_utf8_string(s).c_str() << std::endl; LocalFree(s); return; } typedef int (*info_function)(); info_function api_version = reinterpret_cast<info_function>(GetProcAddress(hinstance, "api_version")); if (!check_api_version(api_version, filename)) { FreeLibrary(hinstance); return; } typedef int (*info_function)(); info_function server_type = reinterpret_cast<info_function>(GetProcAddress(hinstance, "server_type")); if (!server_type) { FreeLibrary(hinstance); return; } if ((*server_type)() != sc_server_supernova) { FreeLibrary(hinstance); return; } void* ptr = (void*)GetProcAddress(hinstance, "load"); if (!ptr) { wchar_t* s; FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t*)&s, 0, NULL); std::cout << "*** ERROR: GetProcAddress err " << SC_Codecvt::utf16_wcstr_to_utf8_string(s).c_str() << std::endl; LocalFree(s); FreeLibrary(hinstance); return; } open_handles.push_back(hinstance); LoadPlugInFunc loadFunc = (LoadPlugInFunc)ptr; (*loadFunc)(&sc_interface); return; } void sc_ugen_factory::close_handles(void) { for (void* ptrhinstance : open_handles) { HINSTANCE hinstance = (HINSTANCE)ptrhinstance; void* ptr = (void*)GetProcAddress(hinstance, "unload"); if (ptr) { UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr; (*unloadFunc)(); } FreeLibrary(hinstance); } } #else #endif } /* namespace nova */
12,497
C++
.cpp
303
34.815182
120
0.636949
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
29,924
sc_osc_handler.cpp
supercollider_supercollider/server/supernova/sc/sc_osc_handler.cpp
// osc handler for supercollider-style communication, implementation // 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. #include "server/memory_pool.hpp" #include <iostream> // 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/placeholders.hpp> #include <boost/asio/read.hpp> #include <boost/bind/bind.hpp> #include "osc/OscOutboundPacketStream.h" #include "osc/OscPrintReceivedElements.h" #include "sc_msg_iter.h" #include "sc_osc_handler.hpp" #include "../server/server.hpp" #include "utilities/sized_array.hpp" #include "SC_OSC_Commands.h" #include "SC_Version.hpp" #include "SC_FifoMsg.h" #ifdef _WIN32 # include "malloc.h" // for alloca #endif namespace nova { using namespace std; using nova::detail::endpoint_ptr; using nova::detail::nova_endpoint; namespace { int32_t last_generated = 0; server_node* find_node(int32_t target_id) { if (target_id == -1) target_id = last_generated; server_node* node = instance->find_node(target_id); if (node == nullptr) log_printf("node not found: %d\n", target_id); return node; } abstract_group* find_group(int32_t target_id) { if (target_id == -1) target_id = last_generated; abstract_group* node = instance->find_group(target_id); if (node == nullptr) log("node not found or not a group\n"); return node; } bool check_node_id(int node_id) { if (!instance->node_id_available(node_id)) { log_printf("node id %d already in use\n", node_id); return false; } return true; } void fill_notification(const server_node* node, osc::OutboundPacketStream& p) { p << node->id(); /* parent */ const abstract_group* parent_node = node->get_parent(); assert(parent_node); p << parent_node->id(); /* previous/next */ if (parent_node->is_parallel()) p << -2 << -2; /* we are in a parallel group, so we have no notion of previous/next */ else { const server_node* prev_node = node->previous_node(); if (prev_node) p << prev_node->id(); else p << -1; const server_node* next_node = node->next_node(); if (next_node) p << next_node->id(); else p << -1; } /* is_synth, head, tail */ if (node->is_synth()) p << 0; else { const abstract_group* node_group = static_cast<const abstract_group*>(node); p << 1; if (node_group->is_parallel()) p << -2 << -2; else { const group* node_real_group = static_cast<const group*>(node_group); if (node_real_group->empty()) p << -1 << -1; else p << node_real_group->head_node()->id() << node_real_group->tail_node()->id(); } } p << osc::EndMessage; } spin_lock system_callback_allocator_lock; struct movable_string { /** allocate new string, only allowed to be called from the rt context */ explicit movable_string(const char* str) { size_t length = strlen(str) + 1; /* terminating \0 */ char* data = (char*)system_callback::allocate(length); strcpy(data, str); data_ = data; } movable_string(movable_string const& rhs) = delete; movable_string operator=(movable_string const& rhs) = delete; movable_string(movable_string&& rhs) { data_ = rhs.data_; const_cast<movable_string&>(rhs).data_ = nullptr; } ~movable_string(void) { if (data_) system_callback::deallocate((char*)data_); } const char* c_str(void) const { return data_; } private: const char* data_ = nullptr; }; template <typename T> struct movable_array { /** allocate new array, only allowed to be called from the rt context */ movable_array(size_t length, const T* data, bool locked = false): length_(length) { data_ = (T*)system_callback::allocate(length * sizeof(T)); for (size_t i = 0; i != length; ++i) data_[i] = data[i]; } movable_array& operator=(movable_array const& rhs) = delete; movable_array(movable_array const& rhs) = delete; movable_array(movable_array&& rhs): length_(rhs.length_), data_(rhs.data_) { rhs.data_ = nullptr; } movable_array& operator=(movable_array&& rhs) { if (data_) system_callback::deallocate(data_); length_ = rhs.length_; data_ = rhs.data_; rhs.data_ = nullptr; return *this; } ~movable_array(void) { if (!data_) return; system_callback::deallocate(data_); data_ = nullptr; } const T* data(void) const { return data_; } const T& operator[](size_t index) const { return data_[index]; } size_t size(void) const { return length_; } private: size_t length_ = 0; T* data_; }; template <typename T> static inline void consume(T&& object) { T sink(std::forward<T>(object)); // move object here (and destroy) } void send_done_message(endpoint_ptr const& endpoint, const char* cmd) { if (endpoint) { char buffer[1024]; osc::OutboundPacketStream p(buffer, 1024); p << osc::BeginMessage("/done") << cmd << osc::EndMessage; endpoint->send(p.Data(), p.Size()); } } void send_done_message(endpoint_ptr const& endpoint, const char* cmd, osc::int32 index) { if (endpoint) { char buffer[1024]; osc::OutboundPacketStream p(buffer, 1024); p << osc::BeginMessage("/done") << cmd << index << osc::EndMessage; endpoint->send(p.Data(), p.Size()); } } void send_fail_message(endpoint_ptr const& endpoint, const char* cmd, const char* content) { if (endpoint) { char buffer[8192]; osc::OutboundPacketStream p(buffer, 8192); p << osc::BeginMessage("/fail") << cmd << content << osc::EndMessage; endpoint->send(p.Data(), p.Size()); } } void send_fail_message(endpoint_ptr const& endpoint, const char* cmd, const char* content, int id) { if (endpoint) { char buffer[8192]; osc::OutboundPacketStream p(buffer, 8192); p << osc::BeginMessage("/fail") << cmd << content << (osc::int32)id << osc::EndMessage; endpoint->send(p.Data(), p.Size()); } } template <typename Functor> struct fn_system_callback : public system_callback { fn_system_callback(Functor const& fn): fn_(fn) {} fn_system_callback(Functor&& fn): fn_(std::forward<Functor>(fn)) {} void run(void) override { fn_(); } Functor fn_; }; template <typename Functor> struct fn_sync_callback : public audio_sync_callback { fn_sync_callback(Functor const& fn): fn_(fn) {} fn_sync_callback(Functor&& fn): fn_(std::forward<Functor>(fn)) {} void run(void) override { fn_(); } Functor fn_; }; /** helper class for dispatching real-time and non real-time osc command callbacks * * uses template specialization to avoid unnecessary callback rescheduling */ template <typename DerivedClass> struct cmd_dispatcher_base { template <typename A> static void free_in_rt_thread(A&& object) { DerivedClass::fire_rt_callback([object = std::move(object)]() mutable { consume(std::move(object)); }); } template <typename A, typename B> static void free_in_rt_thread(A&& object1, B&& object2) { DerivedClass::fire_rt_callback([object1 = std::move(object1), object2 = std::move(object2)]() mutable { consume(std::move(object1)); consume(std::move(object2)); }); } template <typename A, typename B, typename C> static void free_in_rt_thread(A&& object1, B&& object2, C&& object3) { DerivedClass::fire_rt_callback( [object1 = std::move(object1), object2 = std::move(object2), object3 = std::move(object3)]() mutable { consume(std::move(object1)); consume(std::move(object2)); consume(std::move(object3)); }); } template <typename A, typename B, typename C, typename D> static void free_in_rt_thread(A&& object1, B&& object2, C&& object3, D&& object4) { DerivedClass::fire_rt_callback([object1 = std::move(object1), object2 = std::move(object2), object3 = std::move(object3), object4 = std::move(object4)]() mutable { consume(std::move(object1)); consume(std::move(object2)); consume(std::move(object3)); consume(std::move(object4)); }); } static void fire_done_message(endpoint_ptr const& endpoint_ref, const char* cmd, osc::int32 index) { if (endpoint_ref) { DerivedClass::fire_io_callback( [=, endpoint = endpoint_ptr(endpoint_ref)]() { send_done_message(endpoint, cmd, index); }); } } static void fire_message(endpoint_ptr const& endpoint_ref, movable_array<char>&& message) { if (endpoint_ref) { DerivedClass::fire_io_callback( [=, message = std::move(message), endpoint = endpoint_ptr(endpoint_ref)]() mutable { endpoint->send(message.data(), message.size()); DerivedClass::fire_rt_callback( [=, message = std::move(message)]() mutable { consume(std::move(message)); }); }); } } }; template <bool realtime> struct cmd_dispatcher : public cmd_dispatcher_base<cmd_dispatcher<realtime>> { template <typename Functor> static void fire_system_callback(Functor const& f) { instance->add_system_callback(new fn_system_callback<Functor>(f)); } template <typename Functor> static void fire_system_callback(Functor&& f) { instance->add_system_callback(new fn_system_callback<Functor>(std::forward<Functor>(f))); } template <typename Functor> static void fire_io_callback(Functor const& f) { instance->add_io_callback(new fn_system_callback<Functor>(f)); } template <typename Functor> static void fire_io_callback(Functor&& f) { instance->add_io_callback(new fn_system_callback<Functor>(std::forward<Functor>(f))); } template <typename Functor> static void fire_rt_callback(Functor const& f) { instance->add_sync_callback(new fn_sync_callback<Functor>(f)); } template <typename Functor> static void fire_rt_callback(Functor&& f) { instance->add_sync_callback(new fn_sync_callback<Functor>(std::forward<Functor>(f))); } }; template <> struct cmd_dispatcher<false> : public cmd_dispatcher_base<cmd_dispatcher<false>> { template <typename Functor> static void fire_system_callback(Functor const& f) { f(); } template <typename Functor> static void fire_system_callback(Functor&& f) { Functor fn(std::forward<Functor>(f)); fn(); } template <typename Functor> static void fire_rt_callback(Functor const& f) { f(); } template <typename Functor> static void fire_rt_callback(Functor&& f) { Functor fn(std::forward<Functor>(f)); fn(); } template <typename Functor> static void fire_io_callback(Functor const& f) { f(); } template <typename Functor> static void fire_io_callback(Functor&& f) { Functor fn(std::forward<Functor>(f)); fn(); } }; void report_failure(endpoint_ptr const& endpoint, std::exception const& error, const char* command, int bufnum) { std::cout << error.what() << std::endl; send_fail_message(endpoint, command, error.what(), bufnum); } } /* namespace */ namespace detail { using nova::log; int sc_notify_observers::add_observer(endpoint_ptr const& ep) { auto it = find(ep); if (it != observers.end()) return already_registered; observers.push_back(ep); return observers.size() - 1; } int sc_notify_observers::remove_observer(endpoint_ptr const& ep) { auto it = find(ep); if (it == observers.end()) return not_registered; const int observerIndex = it - observers.begin(); observers.erase(it); return observerIndex; } const char* sc_notify_observers::error_string(error_code error) { switch (error) { case no_error: return ""; case already_registered: return "notify: already registered"; case not_registered: return "notify: not registered"; default: assert(false); return ""; } } sc_notify_observers::observer_vector::iterator sc_notify_observers::find(endpoint_ptr const& ep) { for (auto it = observers.begin(); it != observers.end(); ++it) { udp_endpoint* elemUDP = dynamic_cast<udp_endpoint*>(it->get()); udp_endpoint* testUDP = dynamic_cast<udp_endpoint*>(ep.get()); if (elemUDP && testUDP) { if (*elemUDP == *testUDP) return it; } typedef sc_osc_handler::tcp_connection tcp_connection; tcp_connection* elemTCP = dynamic_cast<tcp_connection*>(it->get()); tcp_connection* testTCP = dynamic_cast<tcp_connection*>(ep.get()); if (elemTCP && testTCP) { if (*elemTCP == *testTCP) return it; } } return observers.end(); } void sc_notify_observers::notify(const char* address_pattern, const server_node* node) const { char buffer[128]; // 128 byte should be enough osc::OutboundPacketStream p(buffer, 128); p << osc::BeginMessage(address_pattern); fill_notification(node, p); movable_array<char> message(p.Size(), p.Data()); cmd_dispatcher<true>::fire_io_callback([=, message = std::move(message)]() mutable { instance->send_notification(message.data(), message.size()); cmd_dispatcher<true>::fire_rt_callback( [=, message = std::move(message)]() mutable { consume(std::move(message)); }); }); } void fire_trigger(int32_t node_id, int32_t trigger_id, float value) { char buffer[128]; // 128 byte should be enough osc::OutboundPacketStream p(buffer, 128); p << osc::BeginMessage("/tr") << osc::int32(node_id) << osc::int32(trigger_id) << value << osc::EndMessage; instance->send_notification(p.Data(), p.Size()); } void sc_notify_observers::send_trigger(int32_t node_id, int32_t trigger_id, float value) { // called from rt helper threads, so we need to lock the memory pool (for system_callback allocation) spin_lock::scoped_lock lock(system_callback_allocator_lock); cmd_dispatcher<true>::fire_io_callback([=]() { fire_trigger(node_id, trigger_id, value); }); } void sc_notify_observers::send_node_reply(int32_t node_id, int reply_id, const char* command_name, int argument_count, const float* values) { // called from rt helper threads, so we need to lock the memory pool spin_lock::scoped_lock lock(system_callback_allocator_lock); movable_string cmd(command_name); movable_array<float> value_array(argument_count, values); cmd_dispatcher<true>::fire_io_callback([=, value_array = std::move(value_array), cmd = std::move(cmd)]() mutable { size_t buffer_size = 1024 + strlen(cmd.c_str()) + value_array.size() * sizeof(float); char* buffer = (buffer_size < 2048) ? (char*)alloca(buffer_size) : (char*)malloc(buffer_size); try { osc::OutboundPacketStream p(buffer, buffer_size); p << osc::BeginMessage(cmd.c_str()) << osc::int32(node_id) << osc::int32(reply_id); for (int i = 0; i != value_array.size(); ++i) p << value_array[i]; p << osc::EndMessage; instance->send_notification(p.Data(), p.Size()); } catch (...) {} cmd_dispatcher<true>::free_in_rt_thread(std::move(value_array), std::move(cmd)); if (buffer_size >= 2048) free(buffer); }); } void sc_notify_observers::send_notification(const char* data, size_t length) { for (auto& observer : observers) observer->send(data, length); } void udp_endpoint::send(const char* data, size_t length) { instance->sc_notify_observers::send_udp(data, length, endpoint_); } void sc_notify_observers::send_udp(const char* data, size_t size, udp::endpoint const& receiver) { std::lock_guard<std::mutex> lock(udp_mutex); sc_notify_observers::udp_socket.send_to(boost::asio::buffer(data, size), receiver); } void sc_scheduled_bundles::bundle_node::run(void) { typedef osc::ReceivedBundleElement bundle_element; typedef osc::ReceivedBundle received_bundle; typedef osc::ReceivedMessage ReceivedMessage; bundle_element element(data_); if (element.IsBundle()) { received_bundle bundle(element); if (instance->non_rt) instance->handle_bundle<false>(bundle, endpoint_); else instance->handle_bundle<true>(bundle, endpoint_); } else { ReceivedMessage message(element); if (instance->non_rt) instance->handle_message<false>(message, element.Size(), endpoint_); else instance->handle_message<true>(message, element.Size(), endpoint_); } } void sc_scheduled_bundles::insert_bundle(time_tag const& timeout, const char* data, size_t length, endpoint_ptr const& endpoint) { /* allocate chunk from realtime pool */ void* chunk = rt_pool.malloc(sizeof(bundle_node) + length + 4); bundle_node* node = (bundle_node*)chunk; char* cpy = (char*)chunk + sizeof(bundle_node); memcpy(cpy, data - 4, length + 4); new (node) bundle_node(timeout, cpy, endpoint); bundle_q.insert(*node); } void sc_scheduled_bundles::execute_bundles(time_tag const& last, time_tag const& now) { World* world = &sc_factory->world; while (!bundle_q.empty()) { bundle_node& front = *bundle_q.top(); time_tag const& next_timestamp = front.timeout_; if (now < next_timestamp) break; if (last < next_timestamp) { // between last and now time_tag time_since_last = next_timestamp - last; float samples_since_last = time_since_last.to_samples(world->mSampleRate); float sample_offset; float subsample_offset = std::modf(samples_since_last, &sample_offset); world->mSampleOffset = (int)sample_offset; world->mSubsampleOffset = subsample_offset; } else world->mSampleOffset = world->mSubsampleOffset = 0; front.run(); bundle_q.erase_and_dispose(bundle_q.top(), &dispose_bundle); } world->mSampleOffset = world->mSubsampleOffset = 0; } void sc_osc_handler::open_tcp_acceptor(ip::address address, unsigned int port) { if (address.is_v6()) tcp_acceptor_.open(tcp::v6()); else tcp_acceptor_.open(tcp::v4()); tcp_acceptor_.bind(tcp::endpoint(address, port)); tcp_acceptor_.listen(); start_tcp_accept(); } void sc_osc_handler::open_udp_socket(ip::address address, unsigned int port) { if (address.is_v6()) sc_notify_observers::udp_socket.open(udp::v6()); else sc_notify_observers::udp_socket.open(udp::v4()); sc_notify_observers::udp_socket.bind(udp::endpoint(address, port)); } bool sc_osc_handler::open_socket(int protocol, ip::address address, unsigned int port) { try { if (protocol == IPPROTO_TCP) { open_tcp_acceptor(address, port); return true; } else if (protocol == IPPROTO_UDP) { open_udp_socket(address, port); start_receive_udp(); return true; } } catch (const boost::system::system_error& exc) { // Special verbose message to help with common issue. Issue #3969 if (exc.code() == boost::system::errc::address_in_use) { std::cout << "\n*** ERROR: failed to open " << (protocol == IPPROTO_TCP ? "TCP" : "UDP") << " socket: address in use.\n" "This could be because another instance of supernova is already using it.\n" "You can use SuperCollider (sclang) to kill all running servers by running `Server.killAll`.\n" "You can also kill supernova using a terminal or your operating system's task manager." << std::endl; std::exit(1); } // Allow other exceptions to propagate upward so they can be caught and printed in main. throw; } return false; } void sc_osc_handler::start_receive_udp() { using namespace boost; sc_notify_observers::udp_socket.async_receive_from(buffer(recv_buffer_), udp_remote_endpoint_, bind(&sc_osc_handler::handle_receive_udp, this, asio::placeholders::error, asio::placeholders::bytes_transferred)); } void sc_osc_handler::handle_receive_udp(const boost::system::error_code& error, std::size_t bytes_transferred) { if (unlikely(error == error::operation_aborted)) return; /* we're done */ if (error) { std::cout << "(supernova) sc_osc_handler received error code " << error << std::endl; start_receive_udp(); return; } handle_packet_async(recv_buffer_.data(), bytes_transferred, make_shared<udp_endpoint>(udp_remote_endpoint_)); start_receive_udp(); return; } void sc_osc_handler::tcp_connection::start(sc_osc_handler* self) { using namespace boost; typedef boost::endian::big_int32_t big_int32_t; asio::ip::tcp::no_delay option(true); socket_.set_option(option); const bool check_password = self->tcp_password_; if (check_password) { std::array<char, 32> password; big_int32_t msglen; for (unsigned int i = 0; i != 4; ++i) { size_t size = socket_.receive(asio::buffer(&msglen, 4)); if (size != sizeof(big_int32_t)) return; if (msglen > password.size()) return; size = socket_.receive(asio::buffer(password.data(), msglen)); bool verified = true; if (size != msglen || strcmp(password.data(), self->tcp_password_) != 0) verified = false; if (!verified) throw std::runtime_error("cannot verify password"); } } osc_handler = self; async_read_msg_size(); } void sc_osc_handler::tcp_connection::send(const char* data, size_t length) { std::lock_guard<std::mutex> lock(socket_mutex_); try { boost::endian::big_int32_t len(length); socket_.send(boost::asio::buffer(&len, sizeof(len))); size_t written = socket_.send(boost::asio::buffer(data, length)); assert(length == written); } catch (std::exception const& err) { std::cout << "Exception when sending message over TCP: " << err.what(); } } void sc_osc_handler::tcp_connection::async_read_msg_size() { namespace asio = boost::asio; pointer ptr = std::static_pointer_cast<sc_osc_handler::tcp_connection>(shared_from_this()); asio::async_read(socket_, asio::buffer(&msg_size_, 4), [=](const boost::system::error_code& error, std::size_t bytes_transferred) { if (error == boost::asio::error::eof) return; // connection closed if (error) { cout << "tcp_connection received error: " << error.message() << endl; return; } ptr->handle_message_size(); }); } void sc_osc_handler::tcp_connection::handle_message_size() { msg_buffer_.resize(msg_size_); namespace asio = boost::asio; pointer ptr = std::static_pointer_cast<sc_osc_handler::tcp_connection>(shared_from_this()); asio::async_read(socket_, asio::buffer(msg_buffer_), [=](const boost::system::error_code& error, std::size_t bytes_transferred) { if (error == boost::asio::error::eof) return; // connection closed if (error) { cout << "tcp_connection received error: " << error.message() << endl; return; } assert(bytes_transferred == ptr->msg_size_); ptr->handle_message(); }); } void sc_osc_handler::tcp_connection::handle_message() { assert(msg_size_ == msg_buffer_.size()); osc_handler->handle_packet_async(msg_buffer_.data(), msg_buffer_.size(), shared_from_this()); async_read_msg_size(); } void sc_osc_handler::start_tcp_accept(void) { tcp_connection::pointer new_connection = tcp_connection::create(tcp_acceptor_.get_executor()); tcp_acceptor_.async_accept( new_connection->socket(), boost::bind(&sc_osc_handler::handle_tcp_accept, this, new_connection, boost::asio::placeholders::error)); } void sc_osc_handler::handle_tcp_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { if (!error) new_connection->start(this); start_tcp_accept(); } void sc_osc_handler::handle_packet_async(const char* data, size_t length, endpoint_ptr const& endpoint) { received_packet* p = received_packet::alloc_packet(data, length, endpoint); if (!p) return; if (dump_osc_packets == 1) { ReceivedPacket packet(data, length); if (packet.IsMessage()) { ReceivedMessage message(packet); const char* address = message.AddressPattern(); if (strcmp(address, "/status") != 0) // we ignore /status messages cout << "received osc message " << message << endl; } else cout << "received osc bundle " << packet << endl; } instance->add_sync_callback(p); } time_tag sc_osc_handler::handle_bundle_nrt(const char* data, size_t length) { ReceivedPacket packet(data, length); if (!packet.IsBundle()) throw std::runtime_error("packet needs to be an osc bundle"); ReceivedBundle bundle(packet); handle_bundle<false>(bundle, nullptr); return bundle.TimeTag(); } sc_osc_handler::received_packet* sc_osc_handler::received_packet::alloc_packet(const char* data, size_t length, endpoint_ptr const& remote_endpoint) { /* received_packet struct and data array are located in one memory chunk */ void* chunk = received_packet::allocate(sizeof(received_packet) + length); if (!chunk) { std::cerr << "Memory allocation failure: OSC message not handled\n"; return nullptr; } received_packet* p = (received_packet*)chunk; char* cpy = (char*)(chunk) + sizeof(received_packet); memcpy(cpy, data, length); new (p) received_packet(cpy, length, remote_endpoint); return p; } void sc_osc_handler::received_packet::run(void) { instance->handle_packet(data, length, endpoint_); } void sc_osc_handler::handle_packet(const char* data, std::size_t length, endpoint_ptr const& endpoint) { ReceivedPacket packet(data, length); if (packet.IsBundle()) { ReceivedBundle bundle(packet); handle_bundle<true>(bundle, endpoint); } else { ReceivedMessage message(packet); handle_message<true>(message, packet.Size(), endpoint); } } template <bool realtime> void sc_osc_handler::handle_bundle(ReceivedBundle const& bundle, endpoint_ptr const& endpoint) { time_tag bundle_time = bundle.TimeTag(); typedef osc::ReceivedBundleElementIterator bundle_iterator; typedef osc::ReceivedBundleElement bundle_element; if (bundle_time < now) { if (!bundle_time.is_immediate()) { time_tag late = now - bundle_time; log_printf("late: %f\n", late.to_seconds()); }; for (bundle_iterator it = bundle.ElementsBegin(); it != bundle.ElementsEnd(); ++it) { bundle_element const& element = *it; if (element.IsBundle()) { ReceivedBundle inner_bundle(element); handle_bundle<realtime>(inner_bundle, endpoint); } else { ReceivedMessage message(element); handle_message<realtime>(message, element.Size(), endpoint); } } } else { for (bundle_iterator it = bundle.ElementsBegin(); it != bundle.ElementsEnd(); ++it) { bundle_element const& element = *it; scheduled_bundles.insert_bundle(bundle_time, element.Contents(), element.Size(), endpoint); } } } template <bool realtime> void sc_osc_handler::handle_message(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint) { try { if (message.AddressPatternIsUInt32()) handle_message_int_address<realtime>(message, msg_size, endpoint); else handle_message_sym_address<realtime>(message, msg_size, endpoint); } catch (std::exception const& e) { log_printf("exception in handle_message: %s\n", e.what()); } } namespace { typedef osc::ReceivedMessage ReceivedMessage; int addr_pattern_size(ReceivedMessage const& msg) { return msg.TypeTags() - 1 - msg.AddressPattern(); } int first_arg_as_int(ReceivedMessage const& message) { osc::ReceivedMessageArgumentStream args = message.ArgumentStream(); osc::int32 val; args >> val; return val; } template <bool realtime> void handle_quit(endpoint_ptr endpoint) { instance->quit_received = true; cmd_dispatcher<realtime>::fire_io_callback([=]() { instance->prepare_to_terminate(); if (endpoint) send_done_message(endpoint, "/quit"); instance->terminate(); }); } template <bool realtime> void handle_notify(ReceivedMessage const& message, endpoint_ptr const& endpoint) { int enable = first_arg_as_int(message); cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = endpoint_ptr(endpoint)]() { int observer = 0; if (enable) { observer = instance->add_observer(endpoint); if (observer < 0) send_fail_message(endpoint, "/notify", sc_notify_observers::error_string((sc_notify_observers::error_code)observer)); } else { observer = instance->remove_observer(endpoint); if (observer < 0) send_fail_message(endpoint, "/notify", sc_notify_observers::error_string((sc_notify_observers::error_code)observer)); } if (observer >= 0) send_done_message(endpoint, "/notify", observer); }); } template <> void handle_notify<false>(ReceivedMessage const& message, endpoint_ptr const& endpoint) {} template <bool realtime> void handle_status(endpoint_ptr const& endpoint_ref) { cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = endpoint_ptr(endpoint_ref)]() { if (unlikely(instance->quit_received)) // we don't reply once we are about to quit return; char buffer[1024]; typedef osc::int32 i32; float peak_load, average_load; instance->cpu_load(peak_load, average_load); osc::OutboundPacketStream p(buffer, 1024); p << osc::BeginMessage("/status.reply") << (i32)1 /* unused */ << (i32)sc_factory->ugen_count() /* ugens */ << (i32)instance->synth_count() /* synths */ << (i32)instance->group_count() /* groups */ << (i32)instance->definition_count() /* synthdefs */ << average_load /* average cpu % */ << peak_load /* peak cpu % */ << instance->get_samplerate() /* nominal samplerate */ << instance->smooth_samplerate /* actual samplerate */ << osc::EndMessage; endpoint->send(p.Data(), p.Size()); }); } template <> void handle_status<false>(endpoint_ptr const& endpoint_ref) {} void handle_dumpOSC(ReceivedMessage const& message) { int val = first_arg_as_int(message); val = min(1, val); /* we just support one way of dumping osc messages */ instance->dumpOSC(val); /* thread-safe */ } template <bool realtime> void handle_sync(ReceivedMessage const& message, endpoint_ptr const& endpoint) { int id = first_arg_as_int(message); // ping pong: we go through the nrt->rt channel to ensure that earlier messages have been completely dispatched cmd_dispatcher<realtime>::fire_system_callback([=, endpoint = endpoint_ptr(endpoint)]() { cmd_dispatcher<realtime>::fire_rt_callback([=, endpoint = endpoint_ptr(endpoint)]() { cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = endpoint_ptr(endpoint)]() { char buffer[128]; osc::OutboundPacketStream p(buffer, 128); p << osc::BeginMessage("/synced") << id << osc::EndMessage; endpoint->send(p.Data(), p.Size()); }); }); }); } template <> void handle_sync<false>(ReceivedMessage const& message, endpoint_ptr const& endpoint) {} void handle_clearSched(void) { instance->clear_scheduled_bundles(); } void handle_error(ReceivedMessage const& message) { int val = first_arg_as_int(message); instance->set_error_posting(val); /* thread-safe */ } template <bool realtime> void handle_version(endpoint_ptr const& endpoint_ref) { cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = endpoint_ptr(endpoint_ref)]() { if (unlikely(instance->quit_received)) return; char buffer[4096]; typedef osc::int32 i32; osc::OutboundPacketStream p(buffer, 4096); p << osc::BeginMessage("/version.reply") << "supernova" << (i32)SC_VersionMajor << (i32)SC_VersionMinor << SC_VersionPostfix << SC_BranchOrTag << SC_CommitHash << osc::EndMessage; endpoint->send(p.Data(), p.Size()); }); } template <> void handle_version<false>(endpoint_ptr const& endpoint_ref) {} template <bool realtime> void handle_rtMemoryStatus(endpoint_ptr const& endpoint_ref) { cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = endpoint_ptr(endpoint_ref)]() { if (unlikely(instance->quit_received)) return; char buffer[4096]; typedef osc::int32 i32; osc::OutboundPacketStream p(buffer, 4096); p << osc::BeginMessage("/rtMemoryStatus.reply") << (i32)(rt_pool.get_pool_size() - rt_pool.get_used_size()) << (i32)rt_pool.get_max_size() << osc::EndMessage; endpoint->send(p.Data(), p.Size()); }); } template <> void handle_rtMemoryStatus<false>(endpoint_ptr const& endpoint_ref) {} void handle_unhandled_message(ReceivedMessage const& msg) { log_printf("unhandled message: %s\n", msg.AddressPattern()); } static bool node_position_sanity_check(node_position_constraint const& constraint) { switch (constraint.second) { case head: case tail: case insert: { server_node* target = constraint.first; if (!target->is_group()) { log_printf("Invalid position constraint (target: %d, addAction: %d)\n", target->id(), constraint.second); return false; } break; } case before: case after: case replace: break; } return true; } sc_synth* add_synth(const char* name, int node_id, int action, int target_id) { if (!check_node_id(node_id)) return nullptr; server_node* target = find_node(target_id); if (target == nullptr) return nullptr; node_position_constraint pos = make_pair(target, node_position(action)); if (!node_position_sanity_check(pos)) return nullptr; abstract_synth* synth = instance->add_synth(name, node_id, pos); if (!synth) log_printf("Cannot create synth (synthdef: %s, node id: %d)\n", name, node_id); last_generated = node_id; return static_cast<sc_synth*>(synth); } /* extract float or int32 as float from argument iterator */ inline float extract_float_argument(osc::ReceivedMessageArgumentIterator const& it) { if (it->IsFloat()) return it->AsFloatUnchecked(); if (it->IsInt32()) return float(it->AsInt32Unchecked()); if (it->IsInt64()) return float(it->AsInt64Unchecked()); throw std::runtime_error("type cannot be converted to float"); } inline void verify_argument(osc::ReceivedMessageArgumentIterator const& it, osc::ReceivedMessageArgumentIterator const& end) { if (it == end) throw std::runtime_error("unexpected end of argument list"); } template <bool IsAudio, typename slot_type> void apply_control_bus_mapping(server_node& node, slot_type slot, size_t index, int bus) { if (node.is_synth()) static_cast<sc_synth&>(node).map_control_bus<IsAudio>(slot, index, bus); else { static_cast<abstract_group&>(node).apply_on_children( [&](server_node& node) { apply_control_bus_mapping<IsAudio, slot_type>(node, slot, index, bus); }); } } template <typename control_id_type> void set_control_array(server_node* node, control_id_type control, osc::ReceivedMessageArgumentIterator& it) { size_t array_size = it->ComputeArrayItemCount(); ++it; if (it->IsArrayBegin()) { // nested arrays are basically user errors, but we handle them like normal arrays log("Warning in /s_new handler: nested array argument detected"); set_control_array<control_id_type>(node, control, it); return; } else { for (size_t i = 0; i != array_size; ++i) { if (it->IsString() || it->IsSymbol()) { char const* name = it->AsStringUnchecked(); ++it; int bus_id; switch (name[0]) { case 'c': bus_id = atoi(name + 1); apply_control_bus_mapping<false>(*node, control, i, bus_id); break; case 'a': bus_id = atoi(name + 1); apply_control_bus_mapping<true>(*node, control, i, bus_id); break; default: throw runtime_error("invalid name for control mapping"); } } else { float value = extract_float_argument(it++); node->set_control_array_element(control, i, value); } } } if (!it->IsArrayEnd()) throw runtime_error("missing array end tag"); ++it; // skip array end } template <bool IsAudio, typename slot_type> void apply_control_bus_mapping(server_node& node, slot_type slot, int bus); template <typename ControlSpecifier> void set_control(server_node* node, ControlSpecifier const& control, osc::ReceivedMessageArgumentIterator& it) { if (it->IsArrayBegin()) set_control_array(node, control, it); else if (it->IsString() || it->IsSymbol()) { char const* name = it->AsStringUnchecked(); ++it; int bus_id; switch (name[0]) { case 'c': bus_id = atoi(name + 1); apply_control_bus_mapping<false>(*node, control, bus_id); break; case 'a': bus_id = atoi(name + 1); apply_control_bus_mapping<true>(*node, control, bus_id); break; default: throw runtime_error("invalid name for control mapping"); } } else { float value = extract_float_argument(it++); node->set(control, value); } } /* set control values of node from string/float or int/float pair */ void set_control(server_node* node, osc::ReceivedMessageArgumentIterator& it, osc::ReceivedMessageArgumentIterator end) { if (it->IsInt32()) { osc::int32 index = it->AsInt32Unchecked(); ++it; if (it == end) return; // sclang sometimes uses an integer instead of an empty argument list set_control(node, index, it); } else if (it->IsString()) { const char* str = it->AsStringUnchecked(); ++it; set_control(node, str, it); } else throw runtime_error("invalid argument"); } void handle_s_new(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator args = msg.ArgumentsBegin(), end = msg.ArgumentsEnd(); const char* def_name = args->AsString(); ++args; int32_t id = args->AsInt32(); ++args; if (id == -1) id = instance->generate_node_id(); int32_t action, target; if (args != end) { action = args->AsInt32(); ++args; } else action = 0; if (args != end) { target = args->AsInt32(); ++args; } else target = 0; sc_synth* synth = add_synth(def_name, id, action, target); if (synth == nullptr) return; try { while (args != end) set_control(synth, args, end); } catch (std::exception& e) { log_printf("exception in /s_new: %s\n", e.what()); } } void handle_g_new(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id, action, target_id; args >> node_id >> action >> target_id; if (node_id == -1) node_id = instance->generate_node_id(); else if (!check_node_id(node_id)) continue; server_node* target = find_node(target_id); if (!target) continue; node_position_constraint pos = make_pair(target, node_position(action)); if (!node_position_sanity_check(pos)) continue; instance->add_group(node_id, pos); last_generated = node_id; } } void handle_g_freeall(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 id; args >> id; abstract_group* group = find_group(id); if (!group) continue; instance->group_free_all(group); } } void handle_g_deepFree(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 id; args >> id; abstract_group* group = find_group(id); if (!group) continue; instance->group_free_deep(group); } } void g_query_tree_fill_node(osc::OutboundPacketStream& p, bool flag, server_node const& node) { p << osc::int32(node.id()); if (node.is_synth()) p << -1; else p << osc::int32(static_cast<abstract_group const&>(node).child_count()); if (node.is_synth()) { sc_synth const& scsynth = static_cast<sc_synth const&>(node); p << scsynth.definition_name(); if (flag) { osc::int32 controls = scsynth.mNumControls; p << controls; for (int i = 0; i != controls; ++i) { const char* name_of_slot = scsynth.name_of_slot(i); if (name_of_slot) p << name_of_slot; else p << osc::int32(i); char str[10]; if (scsynth.getMappedSymbol(i, str)) p << str; else p << scsynth.mControls[i]; } } } else { abstract_group const& group = static_cast<abstract_group const&>(node); group.apply_on_children([&](server_node const& node) { g_query_tree_fill_node(p, flag, node); }); } } template <bool realtime> void g_query_tree(int node_id, bool flag, endpoint_ptr endpoint) { server_node* node = find_node(node_id); if (!node || node->is_synth()) return; abstract_group* group = static_cast<abstract_group*>(node); size_t max_msg_size = 1 << 16; for (;;) { try { if (max_msg_size > 1 << 22) return; sized_array<char, rt_pool_allocator<char>> data(max_msg_size); osc::OutboundPacketStream p(data.c_array(), max_msg_size); p << osc::BeginMessage("/g_queryTree.reply") << (flag ? 1 : 0) << node_id << osc::int32(group->child_count()); group->apply_on_children([&](server_node const& node) { g_query_tree_fill_node(p, flag, node); }); p << osc::EndMessage; movable_array<char> message(p.Size(), data.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); return; } catch (...) { max_msg_size *= 2; /* if we run out of memory, retry with doubled memory resources */ } } } template <bool realtime> void handle_g_queryTree(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { try { osc::int32 id, flag; args >> id >> flag; g_query_tree<realtime>(id, flag, endpoint); } catch (std::exception& e) { log_printf("exception in handle_g_queryTree: %s\n", e.what()); } } } typedef std::basic_stringstream <char, std::char_traits <char>/*, rt_pool_allocator<char>*/ > rt_string_stream; void fill_spaces(rt_string_stream& stream, int level) { for (int i = 0; i != level * 3; ++i) stream << ' '; } void dump_controls(rt_string_stream& stream, abstract_synth const& synth, int indentation_level) { const size_t number_of_slots = synth.number_of_slots(); bool eol_pending = false; for (size_t control_index = 0; control_index != number_of_slots; ++control_index) { const char* name_of_slot = synth.name_of_slot(control_index); if (name_of_slot) { if (eol_pending) { stream << endl; eol_pending = false; } fill_spaces(stream, indentation_level); stream << synth.name_of_slot(control_index) << ": "; eol_pending = true; } else stream << ", "; char str[10]; if (synth.getMappedSymbol(control_index, str)) stream << str; else stream << synth.get(control_index); } if (eol_pending) stream << endl; } void g_dump_node(rt_string_stream& stream, server_node& node, bool flag, int level) { using namespace std; fill_spaces(stream, level); if (node.is_synth()) { abstract_synth const& synth = static_cast<abstract_synth const&>(node); stream << synth.id() << " " << synth.definition_name() << endl; if (flag) dump_controls(stream, synth, level + 1); } else { abstract_group& group = static_cast<abstract_group&>(node); stream << group.id(); if (group.is_parallel()) stream << " parallel group"; else stream << " group"; stream << endl; group.apply_on_children([&](server_node& node) { g_dump_node(stream, node, flag, level + 1); }); } } void g_dump_tree(int id, bool flag) { server_node* node = find_node(id); if (!node) return; // FIXME: can we completely avoid all internal allocations? rt_string_stream stream; stream << "NODE TREE Group " << id << std::endl; g_dump_node(stream, *node, flag, 1); log(stream.str().c_str(), stream.str().size()); } void handle_g_dumpTree(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { try { osc::int32 id, flag; args >> id >> flag; g_dump_tree(id, flag); } catch (std::exception& e) { log_printf("exception in /g_dumpTree: %s\n", e.what()); } } } void handle_n_free(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { try { osc::int32 id; args >> id; server_node* node = find_node(id); if (!node) continue; instance->free_node(node); } catch (std::exception& e) { log_printf("exception in /n_free: %s\n", e.what()); } } } /** macro to define an os command handler with a starting node id * * it is mainly intended as decorator to avoid duplicate error handling code */ #define HANDLE_N_DECORATOR(cmd, function) \ void handle_n_##cmd(ReceivedMessage const& msg) { \ osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); \ osc::int32 id = it->AsInt32(); \ ++it; \ \ server_node* node = find_node(id); \ if (!node) \ return; \ \ try { \ while (it != msg.ArgumentsEnd()) \ function(node, it); \ } catch (std::exception & e) { log_printf("Exception during /n_" #cmd "handler: %s\n", e.what()); } \ } void set_control(server_node* node, osc::ReceivedMessageArgumentIterator& it) { if (it->IsInt32()) { osc::int32 index = it->AsInt32Unchecked(); ++it; set_control(node, index, it); } else if (it->IsString()) { const char* str = it->AsStringUnchecked(); ++it; set_control(node, str, it); } else throw runtime_error("invalid argument"); } HANDLE_N_DECORATOR(set, set_control) void set_control_n(server_node* node, osc::ReceivedMessageArgumentIterator& it) { if (it->IsInt32()) { osc::int32 index = it->AsInt32Unchecked(); ++it; osc::int32 count = it->AsInt32(); ++it; for (int i = 0; i != count; ++i) node->set(index + i, extract_float_argument(it++)); } else if (it->IsString()) { const char* str = it->AsStringUnchecked(); ++it; osc::int32 count = it->AsInt32(); ++it; sized_array<float> values(count); for (int i = 0; i != count; ++i) values[i] = extract_float_argument(it++); node->set_control_array(str, count, values.c_array()); } else throw runtime_error("invalid argument"); } HANDLE_N_DECORATOR(setn, set_control_n) void fill_control(server_node* node, osc::ReceivedMessageArgumentIterator& it) { if (it->IsInt32()) { osc::int32 index = it->AsInt32Unchecked(); ++it; osc::int32 count = it->AsInt32(); ++it; float value = extract_float_argument(it++); for (int i = 0; i != count; ++i) node->set(index + i, value); } else if (it->IsString()) { const char* str = it->AsStringUnchecked(); ++it; osc::int32 count = it->AsInt32(); ++it; float value = extract_float_argument(it++); sized_array<float> values(count); for (int i = 0; i != count; ++i) values[i] = value; node->set_control_array(str, count, values.c_array()); } else throw runtime_error("invalid argument"); } HANDLE_N_DECORATOR(fill, fill_control) template <bool IsAudio, typename slot_type> void apply_control_bus_mapping(server_node& node, slot_type slot, int bus_index) { if (node.is_synth()) static_cast<sc_synth&>(node).map_control_bus<IsAudio>(slot, bus_index); else { static_cast<abstract_group&>(node).apply_on_children( [&](server_node& node) { apply_control_bus_mapping<IsAudio, slot_type>(node, slot, bus_index); }); } } template <bool IsAudio, typename slot_type> void apply_control_busn_mapping(server_node& node, slot_type slot, int bus_index, int count) { if (node.is_synth()) static_cast<sc_synth&>(node).map_control_buses<IsAudio>(slot, bus_index, count); else { static_cast<abstract_group&>(node).apply_on_children( [&](server_node& node) { apply_control_busn_mapping<IsAudio, slot_type>(node, slot, bus_index, count); }); } } template <bool IsAudio> void map_control(server_node* node, osc::ReceivedMessageArgumentIterator& it) { if (it->IsInt32()) { osc::int32 control_index = it->AsInt32Unchecked(); ++it; osc::int32 control_bus_index = it->AsInt32(); ++it; apply_control_bus_mapping<IsAudio>(*node, control_index, control_bus_index); } else if (it->IsString()) { const char* control_name = it->AsStringUnchecked(); ++it; osc::int32 control_bus_index = it->AsInt32(); ++it; apply_control_bus_mapping<IsAudio>(*node, control_name, control_bus_index); } else throw runtime_error("invalid argument"); } template <bool IsAudio> void mapn_control(server_node* node, osc::ReceivedMessageArgumentIterator& it) { if (it->IsInt32()) { osc::int32 control_index = it->AsInt32Unchecked(); ++it; osc::int32 bus_index = it->AsInt32(); ++it; osc::int32 count = it->AsInt32(); ++it; apply_control_busn_mapping<IsAudio>(*node, control_index, bus_index, count); } else if (it->IsString()) { const char* control_name = it->AsStringUnchecked(); ++it; osc::int32 bus_index = it->AsInt32(); ++it; osc::int32 count = it->AsInt32(); ++it; apply_control_busn_mapping<IsAudio>(*node, control_name, bus_index, count); } else throw runtime_error("invalid argument"); } HANDLE_N_DECORATOR(map, map_control<false>) HANDLE_N_DECORATOR(mapa, map_control<true>) HANDLE_N_DECORATOR(mapn, mapn_control<false>) HANDLE_N_DECORATOR(mapan, mapn_control<true>) template <nova::node_position Relation> void handle_n_before_or_after(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_a, node_b; args >> node_a >> node_b; server_node* node = find_node(node_a); if (!node) continue; server_node* target_node = find_node(node_b); if (!target_node) continue; abstract_group::move_before_or_after<Relation>(node, target_node); instance->notification_node_moved(node); } instance->request_dsp_queue_update(); } template <nova::node_position Position> void handle_g_head_or_tail(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id, target_id; args >> target_id >> node_id; server_node* node = find_node(node_id); if (!node) continue; abstract_group* target_group = find_group(target_id); if (!target_group) continue; abstract_group::move_to_head_or_tail<Position>(node, target_group); instance->notification_node_moved(node); } instance->request_dsp_queue_update(); } template <bool realtime> void handle_n_query(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id; args >> node_id; server_node* node = find_node(node_id); if (!node) continue; char buffer[128]; // 128 byte should be enough osc::OutboundPacketStream p(buffer, 128); p << osc::BeginMessage("/n_info"); fill_notification(node, p); movable_array<char> message(p.Size(), p.Data()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } } void handle_n_order(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 action, target_id; args >> action >> target_id; server_node* target = find_node(target_id); if (target == nullptr) return; abstract_group* target_parent; if (action == before || action == after) target_parent = target->get_parent(); else { if (target->is_synth()) throw std::runtime_error("invalid argument for n_order: argument is no synth"); target_parent = static_cast<abstract_group*>(target); } while (!args.Eos()) { osc::int32 node_id; args >> node_id; server_node* node = find_node(node_id); if (node == nullptr) continue; abstract_group* node_parent = node->get_parent(); /** TODO: this can be optimized if node_parent == target_parent */ node_parent->remove_child(node); if (action == before || action == after) target_parent->add_child(node, make_pair(target, node_position(action))); else target_parent->add_child(node, node_position(action)); instance->notification_node_moved(node); } instance->request_dsp_queue_update(); } void handle_n_run(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id, run_flag; args >> node_id >> run_flag; server_node* node = find_node(node_id); if (!node) continue; if (run_flag) instance->node_resume(node); else instance->node_pause(node); } } void enable_tracing(server_node& node) { if (node.is_synth()) { sc_synth& synth = static_cast<sc_synth&>(node); synth.enable_tracing(); } else { abstract_group& group = static_cast<abstract_group&>(node); group.apply_on_children(enable_tracing); } } void handle_n_trace(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id; args >> node_id; server_node* node = find_node(node_id); if (!node) continue; enable_tracing(*node); } } void handle_s_noid(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 node_id; args >> node_id; instance->synth_reassign_id(node_id); } } int32_t get_control_index(sc_synth* s, osc::ReceivedMessageArgumentIterator& it, osc::OutboundPacketStream& p) { int32_t control; if (it->IsInt32()) { control = it->AsInt32Unchecked(); ++it; p << control; } else if (it->IsString()) { const char* control_str = it->AsStringUnchecked(); ++it; control = s->resolve_slot(control_str); p << control_str; } else if (it->IsSymbol()) { const char* control_str = it->AsSymbolUnchecked(); ++it; control = s->resolve_slot(control_str); p << osc::Symbol(control_str); } else throw std::runtime_error("wrong argument type"); return control; } template <bool realtime> void handle_s_get(ReceivedMessage const& msg, size_t msg_size, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); if (!it->IsInt32()) throw std::runtime_error("wrong argument type"); int32_t node_id = it->AsInt32Unchecked(); ++it; server_node* node = find_node(node_id); if (!node || !node->is_synth()) throw std::runtime_error("node is not a synth"); sc_synth* s = static_cast<sc_synth*>(node); size_t alloc_size = msg_size + sizeof(float) * (msg.ArgumentCount() - 1) + 128; sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/n_set") << node_id; while (it != msg.ArgumentsEnd()) { int32_t control = get_control_index(s, it, p); p << s->get(control); } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } template <bool realtime> void handle_s_getn(ReceivedMessage const& msg, size_t msg_size, endpoint_ptr const& endpoint) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); if (!it->IsInt32()) throw std::runtime_error("wrong argument type"); int32_t node_id = it->AsInt32Unchecked(); ++it; server_node* node = find_node(node_id); if (!node || !node->is_synth()) throw std::runtime_error("node is not a synth"); sc_synth* s = static_cast<sc_synth*>(node); /* count argument values */ size_t argument_count = 0; for (osc::ReceivedMessageArgumentIterator local = it; local != msg.ArgumentsEnd(); ++local) { ++local; /* skip control */ if (local == msg.ArgumentsEnd()) break; if (!local->IsInt32()) throw std::runtime_error("invalid count"); argument_count += local->AsInt32Unchecked(); } size_t alloc_size = msg_size + sizeof(float) * (argument_count) + 128; sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/n_setn") << node_id; while (it != msg.ArgumentsEnd()) { int32_t control = get_control_index(s, it, p); if (!it->IsInt32()) throw std::runtime_error("integer argument expected"); int32_t control_count = it->AsInt32Unchecked(); ++it; if (control_count < 0) break; p << control_count; for (int i = 0; i != control_count; ++i) p << s->get(control + i); } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } /** wrapper class for osc completion message */ struct completion_message { /** constructor should only be used from the real-time thread */ completion_message(size_t size, const void* data): size_(size) { if (size) { data_ = system_callback::allocate(size); memcpy(data_, data, size); } } /** default constructor creates uninitialized object */ completion_message(void): size_(0) {} completion_message(completion_message const& rhs) = delete; completion_message operator=(completion_message const& rhs) = delete; completion_message(completion_message&& rhs) { operator=(std::forward<completion_message>(rhs)); } completion_message& operator=(completion_message&& rhs) { size_ = rhs.size_; data_ = rhs.data_; rhs.size_ = 0; return *this; } ~completion_message(void) { if (size_) system_callback::deallocate(data_); } /** handle package in the rt thread * not to be called from the rt thread */ void trigger_async(endpoint_ptr const& endpoint) { if (size_) { sc_osc_handler::received_packet* p = sc_osc_handler::received_packet::alloc_packet((char*)data_, size_, endpoint); if (p) instance->add_sync_callback(p); } } /** handle package directly * only to be called from the rt thread */ void handle(endpoint_ptr const& endpoint) const { if (size_) instance->handle_packet((char*)data_, size_, endpoint); } size_t size_; void* data_; }; completion_message extract_completion_message(osc::ReceivedMessageArgumentStream& args) { osc::Blob blob(nullptr, 0); if (!args.Eos()) { try { args >> blob; } catch (osc::WrongArgumentTypeException& e) {} } return completion_message(blob.size, blob.data); } completion_message extract_completion_message(osc::ReceivedMessageArgumentIterator& it) { const void* data = nullptr; osc::osc_bundle_element_size_t length = 0; if (it->IsBlob()) it->AsBlobUnchecked(data, length); ++it; return completion_message(length, data); } // must be called from rt thread void handle_completion_message(completion_message&& message, endpoint_ptr endpoint) { completion_message msg(std::forward<completion_message>(message)); msg.handle(endpoint); } template <bool realtime> void handle_b_alloc(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 bufferIndex, frames, channels; args >> bufferIndex >> frames; if (!args.Eos()) args >> channels; else channels = 1; completion_message message = extract_completion_message(args); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(bufferIndex)); try { sample* free_buf = sc_factory->get_nrt_mirror_buffer(bufferIndex); sc_factory->allocate_buffer(bufferIndex, frames, channels); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { sc_factory->buffer_sync(bufferIndex); handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_io_callback([=] { free_aligned(free_buf); send_done_message(endpoint, "/b_alloc", bufferIndex); }); }); } catch (std::exception const& error) { report_failure(endpoint, error, "/b_alloc", bufferIndex); cmd_dispatcher<realtime>::free_in_rt_thread(std::move(message)); } }); } template <bool realtime> void handle_b_free(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 index; args >> index; completion_message message = extract_completion_message(args); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(index)); sample* free_buf = sc_factory->get_nrt_mirror_buffer(index); sc_factory->free_buffer(index); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { sc_factory->buffer_sync(index); handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_io_callback([=] { free_aligned(free_buf); send_done_message(endpoint, "/b_free", index); }); }); }); } template <bool realtime> void handle_b_allocRead(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 bufferIndex; const char* filenameString; osc::int32 start = 0; osc::int32 frames = 0; args >> bufferIndex >> filenameString; if (!args.Eos()) args >> start; if (!args.Eos()) args >> frames; completion_message message = extract_completion_message(args); movable_string filename(filenameString); cmd_dispatcher<realtime>::fire_system_callback( [=, filename = std::move(filename), message = std::move(message)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(bufferIndex)); sample* free_buf = sc_factory->get_nrt_mirror_buffer(bufferIndex); try { sc_factory->buffer_read_alloc(bufferIndex, filename.c_str(), start, frames); cmd_dispatcher<realtime>::fire_rt_callback( [=, filename = std::move(filename), message = std::move(message)]() mutable { sc_factory->buffer_sync(bufferIndex); handle_completion_message(std::move(message), endpoint); consume(std::move(filename)); cmd_dispatcher<realtime>::fire_io_callback([=] { free_aligned(free_buf); send_done_message(endpoint, "/b_allocRead", bufferIndex); }); }); } catch (std::exception const& error) { cmd_dispatcher<realtime>::free_in_rt_thread(std::move(message), std::move(filename)); report_failure(endpoint, error, "/b_allocRead", bufferIndex); } }); } template <bool realtime> void handle_b_allocReadChannel(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator arg = msg.ArgumentsBegin(); osc::int32 bufnum = arg->AsInt32(); arg++; const char* filenameString = arg->AsString(); arg++; osc::int32 start = arg->AsInt32(); arg++; size_t frames = arg->AsInt32(); arg++; size_t channel_args = msg.ArgumentCount() - 4; /* we already consumed 4 elements */ size_t channel_count = 0; sized_array<uint, rt_pool_allocator<uint>> channels(channel_args); // Any remaining Int arguments are channels, followed by an optional // completion message. for (uint i = 0; i < channel_args; ++i) { if (arg->IsInt32()) { channels[i] = arg->AsInt32Unchecked(); arg++; ++channel_count; } } /* we reached the message blob */ completion_message message = extract_completion_message(arg); movable_array<uint32_t> channel_mapping(channel_count, channels.c_array()); movable_string filename(filenameString); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message), channel_mapping = std::move(channel_mapping), filename = std::move(filename)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(bufnum)); sample* free_buf = sc_factory->get_nrt_mirror_buffer(bufnum); try { sc_factory->buffer_alloc_read_channels(bufnum, filename.c_str(), start, frames, channel_mapping.size(), channel_mapping.data()); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message), channel_mapping = std::move(channel_mapping), filename = std::move(filename)]() mutable { sc_factory->buffer_sync(bufnum); consume(std::move(channel_mapping)); consume(std::move(filename)); handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_io_callback([=] { free_aligned(free_buf); send_done_message(endpoint, "/b_allocReadChannel", bufnum); }); }); } catch (std::exception const& error) { cmd_dispatcher<realtime>::free_in_rt_thread(std::move(message), std::move(channel_mapping), std::move(filename)); report_failure(endpoint, error, "/b_allocReadChannel", bufnum); } }); } const char* b_write = "/b_write"; void fire_b_write_exception(void) { throw std::runtime_error("wrong arguments for /b_write"); } template <bool realtime> void handle_b_write(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator arg = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); /* required args */ osc::int32 bufnum = arg->AsInt32(); arg++; const char* filename = arg->AsString(); arg++; const char* header_format = arg->AsString(); arg++; const char* sample_format = arg->AsString(); arg++; /* optional args */ osc::int32 frames = -1; osc::int32 start = 0; osc::int32 leave_open = 0; completion_message message; if (arg != end) { if (!arg->IsInt32()) fire_b_write_exception(); frames = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_write_exception(); start = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_write_exception(); leave_open = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) message = extract_completion_message(arg); fire_callback: movable_string filenameString(filename); movable_string headerString(header_format); movable_string sampleString(sample_format); cmd_dispatcher<realtime>::fire_system_callback( [=, message = std::move(message), filenameString = std::move(filenameString), headerString = std::move(headerString), sampleString = std::move(sampleString)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(bufnum)); try { sc_factory->buffer_write(bufnum, filenameString.c_str(), headerString.c_str(), sampleString.c_str(), start, frames, leave_open); cmd_dispatcher<realtime>::fire_rt_callback( [=, message = std::move(message), filenameString = std::move(filenameString), headerString = std::move(headerString), sampleString = std::move(sampleString)]() mutable { handle_completion_message(std::move(message), endpoint); consume(std::move(filenameString)); consume(std::move(headerString)); consume(std::move(sampleString)); cmd_dispatcher<realtime>::fire_done_message(endpoint, b_write, bufnum); }); } catch (std::exception const& error) { report_failure(endpoint, error, b_write, bufnum); cmd_dispatcher<realtime>::free_in_rt_thread(std::move(message), std::move(filenameString), std::move(headerString), std::move(sampleString)); } }); } const char* b_read = "/b_read"; void fire_b_read_exception(void) { throw std::runtime_error("wrong arguments for /b_read"); } template <bool realtime> void handle_b_read(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator arg = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); /* required args */ osc::int32 bufnum = arg->AsInt32(); arg++; const char* filename = arg->AsString(); arg++; /* optional args */ osc::int32 start_file = 0; osc::int32 frames = -1; osc::int32 start_buffer = 0; osc::int32 leave_open = 0; completion_message message; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); start_file = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); frames = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); start_buffer = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); leave_open = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) message = extract_completion_message(arg); fire_callback: movable_string fname(filename); cmd_dispatcher<realtime>::fire_system_callback( [=, filename = std::move(fname), message = std::move(message)]() mutable { sc_ugen_factory::buffer_lock_t buffer_lock(sc_factory->buffer_guard(bufnum)); try { sc_factory->buffer_read(bufnum, filename.c_str(), start_file, frames, start_buffer, leave_open); cmd_dispatcher<realtime>::fire_rt_callback( [=, filename = std::move(filename), message = std::move(message)]() mutable { sc_factory->buffer_sync(bufnum); handle_completion_message(std::move(message), endpoint); consume(std::move(filename)); cmd_dispatcher<realtime>::fire_done_message(endpoint, b_read, bufnum); }); } catch (std::exception const& error) { report_failure(endpoint, error, b_read, bufnum); cmd_dispatcher<realtime>::free_in_rt_thread(std::move(message), std::move(filename)); } }); } const char* b_readChannel = "/b_readChannel"; void fire_b_readChannel_exception(void) { throw std::runtime_error("wrong arguments for /b_readChannel"); } template <bool realtime> void handle_b_readChannel(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator arg = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); /* required args */ osc::int32 bufnum = arg->AsInt32(); arg++; const char* filename = arg->AsString(); arg++; /* optional args */ osc::int32 start_file = 0; osc::int32 frames = -1; osc::int32 start_buffer = 0; osc::int32 leave_open = 0; sized_array<uint32_t, rt_pool_allocator<uint32_t>> channel_mapping( int32_t(msg.ArgumentCount())); /* larger than required */ uint32_t channel_count = 0; completion_message message; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); start_file = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_read_exception(); frames = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_write_exception(); start_buffer = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; if (arg != end) { if (!arg->IsInt32()) fire_b_write_exception(); leave_open = arg->AsInt32Unchecked(); arg++; } else goto fire_callback; while (arg != end) { if (arg->IsBlob()) { message = extract_completion_message(arg); goto fire_callback; } else if (arg->IsInt32()) { channel_mapping[channel_count] = arg->AsInt32Unchecked(); ++arg; } else fire_b_readChannel_exception(); } fire_callback: movable_string fname(filename); movable_array<uint32_t> channel_map(channel_count, channel_mapping.c_array()); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message), filename = std::move(fname), channel_map = std::move(channel_map)]() mutable { try { sc_factory->buffer_read_channel(bufnum, filename.c_str(), start_file, frames, start_buffer, leave_open, channel_map.size(), channel_map.data()); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message), filename = std::move(filename), channel_map = std::move(channel_map)]() mutable { sc_factory->buffer_sync(bufnum); handle_completion_message(std::move(message), endpoint); consume(std::move(filename)); consume(std::move(channel_map)); cmd_dispatcher<realtime>::fire_done_message(endpoint, b_readChannel, bufnum); }); } catch (std::exception const& error) { report_failure(endpoint, error, b_readChannel, bufnum); cmd_dispatcher<realtime>::free_in_rt_thread(std::move(filename), std::move(channel_map), std::move(message)); } }); } const char* b_zero = "/b_zero"; template <bool realtime> void handle_b_zero(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 index; args >> index; completion_message message = extract_completion_message(args); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message)]() mutable { sc_factory->buffer_zero(index); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { sc_factory->increment_write_updates(index); handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_done_message(endpoint, b_zero, index); }); }); } void handle_b_set(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); verify_argument(it, end); osc::int32 buffer_index = it->AsInt32(); ++it; buffer_wrapper::sample_t* data = sc_factory->get_buffer(buffer_index); if (!data) { log_printf("/b_set called on unallocated buffer\n"); return; } while (it != end) { osc::int32 index = it->AsInt32(); ++it; float value = extract_float_argument(it++); data[index] = value; } } void handle_b_setn(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); verify_argument(it, end); osc::int32 buffer_index = it->AsInt32(); ++it; buffer_wrapper::sample_t* data = sc_factory->get_buffer(buffer_index); if (!data) { log_printf("/b_setn called on unallocated buffer\n"); return; } while (it != end) { osc::int32 index = it->AsInt32(); ++it; verify_argument(it, end); osc::int32 samples = it->AsInt32(); ++it; for (int i = 0; i != samples; ++i) { verify_argument(it, end); float value = extract_float_argument(it++); data[index + i] = value; } } } void handle_b_fill(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); osc::ReceivedMessageArgumentIterator end = msg.ArgumentsEnd(); verify_argument(it, end); osc::int32 buffer_index = it->AsInt32(); ++it; buffer_wrapper::sample_t* data = sc_factory->get_buffer(buffer_index); if (!data) { log_printf("/b_fill called on unallocated buffer\n"); return; } int bufSamples = sc_factory->get_buffer_struct(buffer_index)->samples; while (it != end) { osc::int32 index = it->AsInt32(); ++it; verify_argument(it, end); osc::int32 samples = it->AsInt32(); ++it; verify_argument(it, end); float value = extract_float_argument(it++); for (int i = 0; i != samples; ++i) { data[index] = value; ++index; if (index >= bufSamples) { break; } } } } template <bool realtime> void handle_b_query(ReceivedMessage const& msg, endpoint_ptr endpoint) { const size_t elem_size = 3 * sizeof(int) * sizeof(float); osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); size_t arg_count = msg.ArgumentCount(); size_t size = elem_size * arg_count + 128; /* should be more than required */ sized_array<char, rt_pool_allocator<char>> data(size); osc::OutboundPacketStream p(data.c_array(), size); p << osc::BeginMessage("/b_info"); while (!args.Eos()) { osc::int32 buffer_index; args >> buffer_index; SndBuf* buf = sc_factory->get_buffer_struct(buffer_index); p << buffer_index << osc::int32(buf->frames) << osc::int32(buf->channels) << float(buf->samplerate); } p << osc::EndMessage; movable_array<char> message(p.Size(), data.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } template <bool realtime> void handle_b_close(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); osc::int32 index; args >> index; completion_message message = extract_completion_message(args); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(message)]() mutable { sc_factory->buffer_close(index); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_done_message(endpoint, "/b_close", index); }); }); } template <bool realtime> void handle_b_get(ReceivedMessage const& msg, endpoint_ptr endpoint) { const size_t elem_size = sizeof(int) * sizeof(float); osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); const size_t index_count = msg.ArgumentCount() - 1; const size_t alloc_size = index_count * elem_size + 128; /* hopefully enough */ sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::int32 buffer_index; args >> buffer_index; const SndBuf* buf = sc_factory->get_buffer_struct(buffer_index); const sample* data = buf->data; if (!data) { log_printf("/b_get called on unallocated buffer\n"); return; } const int max_sample = buf->frames * buf->channels; osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/b_set") << buffer_index; while (!args.Eos()) { osc::int32 index; args >> index; p << index; if (index < max_sample) p << data[index]; else p << 0.f; } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } template <typename Alloc> struct getn_data { getn_data(int start, int count, const float* data): start_index_(start), data_(count) { data_.reserve(count); for (int i = 0; i != count; ++i) data_[i] = data[i]; } int start_index_; std::vector<float, Alloc> data_; }; template <bool realtime> void handle_b_getn(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); typedef getn_data<rt_pool_allocator<float>> getn_data; std::vector<getn_data, rt_pool_allocator<getn_data>> return_data; osc::int32 buffer_index; args >> buffer_index; const SndBuf* buf = sc_factory->get_buffer_struct(buffer_index); const sample* data = buf->data; if (!data) { log_printf("/b_getn called on unallocated buffer\n"); return; } const int max_sample = buf->frames * buf->channels; while (!args.Eos()) { osc::int32 index, sample_count; args >> index >> sample_count; if (index + sample_count <= max_sample) return_data.push_back(getn_data(index, sample_count, data + index)); } size_t alloc_size = 128; for (size_t i = 0; i != return_data.size(); ++i) alloc_size += return_data[i].data_.size() * (sizeof(float) + sizeof(int)) + 2 * sizeof(int); sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/b_setn") << buffer_index; for (size_t i = 0; i != return_data.size(); ++i) { p << osc::int32(return_data[i].start_index_) << osc::int32(return_data[i].data_.size()); for (size_t j = 0; j != return_data[i].data_.size(); ++j) p << return_data[i].data_[j]; } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } template <bool realtime> void handle_b_gen(ReceivedMessage const& msg, size_t msg_size, endpoint_ptr endpoint) { int skip_bytes = addr_pattern_size(msg); // skip address pattern movable_array<char> cmd(msg_size - skip_bytes, msg.AddressPattern() + skip_bytes); cmd_dispatcher<realtime>::fire_system_callback([=, message = std::move(cmd)]() mutable { sc_msg_iter msg(message.size(), message.data()); char nextTag = msg.nextTag(); if (nextTag != 'i') { printf("/b_gen handler: invalid buffer index type %c\n", nextTag); return; } int index = msg.geti(); const char* generator = (const char*)msg.gets4(); if (!generator) { if (nextTag += 'i') { printf("/b_gen handler: invalid bufgen name\n"); return; } } sample* free_buf = sc_factory->buffer_generate(index, generator, msg); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { consume(std::move(message)); sc_factory->buffer_sync(index); cmd_dispatcher<realtime>::fire_io_callback([=] { free_aligned(free_buf); send_done_message(endpoint, "/b_gen", index); }); }); }); } void handle_c_set(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); while (it != msg.ArgumentsEnd()) { osc::int32 bus_index = it->AsInt32(); ++it; if (it == msg.ArgumentsEnd()) return; float value = extract_float_argument(it++); sc_factory->controlbus_set(bus_index, value); } } void handle_c_setn(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); while (it != msg.ArgumentsEnd()) { osc::int32 bus_index, bus_count; bus_index = it->AsInt32(); ++it; bus_count = it->AsInt32(); ++it; for (int i = 0; i != bus_count; ++i) { float value = extract_float_argument(it++); sc_factory->controlbus_set(bus_index + i, value); } } } void handle_c_fill(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentIterator it = msg.ArgumentsBegin(); while (it != msg.ArgumentsEnd()) { osc::int32 bus_index, bus_count; bus_index = it->AsInt32(); ++it; bus_count = it->AsInt32(); ++it; float value = extract_float_argument(it++); sc_factory->controlbus_fill(bus_index, bus_count, value); } } template <bool realtime> void handle_c_get(ReceivedMessage const& msg, endpoint_ptr endpoint) { const size_t elem_size = sizeof(int) + sizeof(float); osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); const size_t index_count = msg.ArgumentCount(); const size_t alloc_size = index_count * elem_size + 128; /* hopefully enough */ sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/c_set"); while (!args.Eos()) { osc::int32 index; args >> index; p << index << sc_factory->controlbus_get(index); } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } template <bool realtime> void handle_c_getn(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); /* we pessimize, but better to allocate too much than too little */ const size_t alloc_size = 128 + (2 * sizeof(int) + 128 * sizeof(float)) * msg.ArgumentCount(); sized_array<char, rt_pool_allocator<char>> return_message(alloc_size); osc::OutboundPacketStream p(return_message.c_array(), alloc_size); p << osc::BeginMessage("/c_setn"); while (!args.Eos()) { osc::int32 bus_index, bus_count; args >> bus_index >> bus_count; p << bus_index << bus_count; for (int i = 0; i != bus_count; ++i) { float value = sc_factory->controlbus_get(bus_index + i); p << value; } } p << osc::EndMessage; movable_array<char> message(p.Size(), return_message.c_array()); cmd_dispatcher<realtime>::fire_message(endpoint, std::move(message)); } static std::vector<sc_synth_definition_ptr> wrapSynthdefs(std::vector<sc_synthdef>&& synthdefs) { std::vector<sc_synth_definition_ptr> wrappedSynthdefs; wrappedSynthdefs.reserve(synthdefs.size()); for (sc_synthdef& synthdef : synthdefs) { sc_synth_definition_ptr ptr(new sc_synth_definition(std::move(synthdef))); wrappedSynthdefs.emplace_back(std::move(ptr)); } return wrappedSynthdefs; } template <bool realtime> void handle_d_recv(ReceivedMessage const& msg, endpoint_ptr endpoint) { const void* synthdef_data; osc::osc_bundle_element_size_t synthdef_size; osc::ReceivedMessageArgumentIterator args = msg.ArgumentsBegin(); args->AsBlob(synthdef_data, synthdef_size); ++args; movable_array<char> def(synthdef_size, (const char*)synthdef_data); completion_message message = extract_completion_message(args); cmd_dispatcher<realtime>::fire_system_callback([=, def = std::move(def), message = std::move(message)]() mutable { std::vector<sc_synth_definition_ptr> wrappedSynthdefs = wrapSynthdefs(read_synthdefs(def.data(), def.data() + def.size())); cmd_dispatcher<realtime>::fire_rt_callback([=, def = std::move(def), message = std::move(message), wrappedSynthdefs = std::move(wrappedSynthdefs)]() mutable { for (sc_synth_definition_ptr& definition : wrappedSynthdefs) instance->register_definition(std::move(definition)); handle_completion_message(std::move(message), endpoint); consume(std::move(def)); cmd_dispatcher<realtime>::fire_io_callback([=, wrappedSynthdefs = std::move(wrappedSynthdefs)] { consume(std::move(wrappedSynthdefs)); send_done_message(endpoint, "/d_recv"); }); }); }); } template <bool realtime> void handle_d_load(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentIterator args = msg.ArgumentsBegin(); const char* path = args->AsString(); args++; completion_message message = extract_completion_message(args); movable_string path_string(path); cmd_dispatcher<realtime>::fire_system_callback( [=, message = std::move(message), path_string = std::move(path_string)]() mutable { /* TODO: we need to implement some file name pattern matching */ std::vector<sc_synth_definition_ptr> wrappedSynthdefs = wrapSynthdefs(sc_read_synthdefs_file(path_string.c_str())); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message), path_string = std::move(path_string), wrappedSynthdefs = std::move(wrappedSynthdefs)]() mutable { for (sc_synth_definition_ptr& definition : wrappedSynthdefs) instance->register_definition(std::move(definition)); handle_completion_message(std::move(message), endpoint); consume(std::move(path_string)); cmd_dispatcher<realtime>::fire_io_callback([=, wrappedSynthdefs = std::move(wrappedSynthdefs)] { consume(std::move(wrappedSynthdefs)); send_done_message(endpoint, "/d_load"); }); }); }); } template <bool realtime> void handle_d_loadDir(ReceivedMessage const& msg, endpoint_ptr endpoint) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); const char* path; args >> path; completion_message message = extract_completion_message(args); movable_string path_string(path); cmd_dispatcher<realtime>::fire_system_callback( [=, message = std::move(message), path_string = std::move(path_string)]() mutable { std::vector<sc_synth_definition_ptr> wrappedSynthdefs = wrapSynthdefs(sc_read_synthdefs_dir(path_string.c_str())); cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message), path_string = std::move(path_string), wrappedSynthdefs = std::move(wrappedSynthdefs)]() mutable { for (sc_synth_definition_ptr& definition : wrappedSynthdefs) instance->register_definition(std::move(definition)); handle_completion_message(std::move(message), endpoint); consume(std::move(path_string)); cmd_dispatcher<realtime>::fire_io_callback([=, wrappedSynthdefs = std::move(wrappedSynthdefs)] { consume(std::move(wrappedSynthdefs)); send_done_message(endpoint, "/d_loadDir"); }); }); }); } void handle_d_free(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { const char* defname; args >> defname; instance->remove_definition(defname); } } void insert_parallel_group(int node_id, int action, int target_id) { if (node_id == -1) node_id = instance->generate_node_id(); else if (!check_node_id(node_id)) return; server_node* target = find_node(target_id); if (!target) return; node_position_constraint pos = make_pair(target, node_position(action)); if (!node_position_sanity_check(pos)) return; instance->add_parallel_group(node_id, pos); last_generated = node_id; } void handle_p_new(ReceivedMessage const& msg) { osc::ReceivedMessageArgumentStream args = msg.ArgumentStream(); while (!args.Eos()) { osc::int32 id, action, target; args >> id >> action >> target; insert_parallel_group(id, action, target); } } void handle_u_cmd(ReceivedMessage const& msg, int size) { int skip_bytes = addr_pattern_size(msg); // skip address pattern sc_msg_iter args(size - skip_bytes, msg.AddressPattern() + skip_bytes); int node_id = args.geti(); server_node* target_synth = find_node(node_id); if (target_synth == nullptr || target_synth->is_group()) return; sc_synth* synth = static_cast<sc_synth*>(target_synth); int ugen_index = args.geti(); const char* cmd_name = args.gets(); synth->apply_unit_cmd(cmd_name, ugen_index, &args); } void handle_cmd(ReceivedMessage const& msg, int size, endpoint_ptr endpoint) { int skip_bytes = addr_pattern_size(msg); // skip address pattern sc_msg_iter args(size - skip_bytes, msg.AddressPattern() + skip_bytes); const char* cmd = args.gets(); sc_factory->run_cmd_plugin(&sc_factory->world, cmd, &args, endpoint.get()); } } /* namespace */ template <bool realtime> void sc_osc_handler::handle_message_int_address(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint) { uint32_t address = message.AddressPatternAsUInt32(); switch (address) { case cmd_none: break; case cmd_quit: handle_quit<realtime>(endpoint); break; case cmd_s_new: handle_s_new(message); break; case cmd_s_noid: handle_s_noid(message); break; case cmd_s_get: handle_s_get<realtime>(message, msg_size, endpoint); break; case cmd_s_getn: handle_s_getn<realtime>(message, msg_size, endpoint); break; case cmd_notify: handle_notify<realtime>(message, endpoint); break; case cmd_status: handle_status<realtime>(endpoint); break; case cmd_dumpOSC: handle_dumpOSC(message); break; case cmd_sync: handle_sync<realtime>(message, endpoint); break; case cmd_clearSched: handle_clearSched(); break; case cmd_error: handle_error(message); break; case cmd_g_new: handle_g_new(message); break; case cmd_g_head: handle_g_head_or_tail<head>(message); break; case cmd_g_tail: handle_g_head_or_tail<tail>(message); break; case cmd_g_freeAll: handle_g_freeall(message); break; case cmd_g_deepFree: handle_g_deepFree(message); break; case cmd_g_queryTree: handle_g_queryTree<realtime>(message, endpoint); break; case cmd_g_dumpTree: handle_g_dumpTree(message); break; case cmd_n_free: handle_n_free(message); break; case cmd_n_set: handle_n_set(message); break; case cmd_n_setn: handle_n_setn(message); break; case cmd_n_fill: handle_n_fill(message); break; case cmd_n_map: handle_n_map(message); break; case cmd_n_mapn: handle_n_mapn(message); break; case cmd_n_mapa: handle_n_mapa(message); break; case cmd_n_mapan: handle_n_mapan(message); break; case cmd_n_query: handle_n_query<realtime>(message, endpoint); break; case cmd_n_order: handle_n_order(message); break; case cmd_n_run: handle_n_run(message); break; case cmd_n_before: handle_n_before_or_after<before>(message); break; case cmd_n_after: handle_n_before_or_after<after>(message); break; case cmd_n_trace: handle_n_trace(message); break; case cmd_b_alloc: handle_b_alloc<realtime>(message, endpoint); break; case cmd_u_cmd: handle_u_cmd(message, msg_size); break; case cmd_b_free: handle_b_free<realtime>(message, endpoint); break; case cmd_b_allocRead: handle_b_allocRead<realtime>(message, endpoint); break; case cmd_b_allocReadChannel: handle_b_allocReadChannel<realtime>(message, endpoint); break; case cmd_b_read: handle_b_read<realtime>(message, endpoint); break; case cmd_b_readChannel: handle_b_readChannel<realtime>(message, endpoint); break; case cmd_b_write: handle_b_write<realtime>(message, endpoint); break; case cmd_b_zero: handle_b_zero<realtime>(message, endpoint); break; case cmd_b_set: handle_b_set(message); break; case cmd_b_setn: handle_b_setn(message); break; case cmd_b_fill: handle_b_fill(message); break; case cmd_b_query: handle_b_query<realtime>(message, endpoint); break; case cmd_b_get: handle_b_get<realtime>(message, endpoint); break; case cmd_b_getn: handle_b_getn<realtime>(message, endpoint); break; case cmd_b_gen: handle_b_gen<realtime>(message, msg_size, endpoint); break; case cmd_b_close: handle_b_close<realtime>(message, endpoint); break; case cmd_c_set: handle_c_set(message); break; case cmd_c_setn: handle_c_setn(message); break; case cmd_c_fill: handle_c_fill(message); break; case cmd_c_get: handle_c_get<realtime>(message, endpoint); break; case cmd_c_getn: handle_c_getn<realtime>(message, endpoint); break; case cmd_d_recv: handle_d_recv<realtime>(message, endpoint); break; case cmd_d_load: handle_d_load<realtime>(message, endpoint); break; case cmd_d_loadDir: handle_d_loadDir<realtime>(message, endpoint); break; case cmd_d_free: handle_d_free(message); break; case cmd_p_new: handle_p_new(message); break; case cmd_cmd: handle_cmd(message, msg_size, endpoint); break; case cmd_version: handle_version<realtime>(endpoint); break; case cmd_rtMemoryStatus: handle_rtMemoryStatus<realtime>(endpoint); break; default: handle_unhandled_message(message); } } namespace { template <bool realtime> void dispatch_group_commands(const char* address, ReceivedMessage const& message, endpoint_ptr const& endpoint) { assert(address[1] == 'g'); assert(address[2] == '_'); if (strcmp(address + 3, "new") == 0) { handle_g_new(message); return; } if (strcmp(address + 3, "head") == 0) { handle_g_head_or_tail<head>(message); return; } if (strcmp(address + 3, "tail") == 0) { handle_g_head_or_tail<tail>(message); return; } if (strcmp(address + 3, "freeAll") == 0) { handle_g_freeall(message); return; } if (strcmp(address + 3, "deepFree") == 0) { handle_g_deepFree(message); return; } if (strcmp(address + 3, "queryTree") == 0) { handle_g_queryTree<realtime>(message, endpoint); return; } if (strcmp(address + 3, "dumpTree") == 0) { handle_g_dumpTree(message); return; } } template <bool realtime> void dispatch_node_commands(const char* address, ReceivedMessage const& message, endpoint_ptr const& endpoint) { assert(address[1] == 'n'); assert(address[2] == '_'); if (strcmp(address + 3, "free") == 0) { handle_n_free(message); return; } if (strcmp(address + 3, "set") == 0) { handle_n_set(message); return; } if (strcmp(address + 3, "setn") == 0) { handle_n_setn(message); return; } if (strcmp(address + 3, "fill") == 0) { handle_n_fill(message); return; } if (strcmp(address + 3, "map") == 0) { handle_n_map(message); return; } if (strcmp(address + 3, "mapn") == 0) { handle_n_mapn(message); return; } if (strcmp(address + 3, "mapa") == 0) { handle_n_mapa(message); return; } if (strcmp(address + 3, "mapan") == 0) { handle_n_mapan(message); return; } if (strcmp(address + 3, "run") == 0) { handle_n_run(message); return; } if (strcmp(address + 3, "before") == 0) { handle_n_before_or_after<before>(message); return; } if (strcmp(address + 3, "after") == 0) { handle_n_before_or_after<after>(message); return; } if (strcmp(address + 3, "order") == 0) { handle_n_order(message); return; } if (strcmp(address + 3, "query") == 0) { handle_n_query<realtime>(message, endpoint); return; } if (strcmp(address + 3, "trace") == 0) { handle_n_trace(message); return; } } template <bool realtime> void dispatch_buffer_commands(const char* address, ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint) { assert(address[1] == 'b'); assert(address[2] == '_'); if (strcmp(address + 3, "alloc") == 0) { handle_b_alloc<realtime>(message, endpoint); return; } if (strcmp(address + 3, "free") == 0) { handle_b_free<realtime>(message, endpoint); return; } if (strcmp(address + 3, "allocRead") == 0) { handle_b_allocRead<realtime>(message, endpoint); return; } if (strcmp(address + 3, "allocReadChannel") == 0) { handle_b_allocReadChannel<realtime>(message, endpoint); return; } if (strcmp(address + 3, "read") == 0) { handle_b_read<realtime>(message, endpoint); return; } if (strcmp(address + 3, "readChannel") == 0) { handle_b_readChannel<realtime>(message, endpoint); return; } if (strcmp(address + 3, "write") == 0) { handle_b_write<realtime>(message, endpoint); return; } if (strcmp(address + 3, "zero") == 0) { handle_b_zero<realtime>(message, endpoint); return; } if (strcmp(address + 3, "set") == 0) { handle_b_set(message); return; } if (strcmp(address + 3, "setn") == 0) { handle_b_setn(message); return; } if (strcmp(address + 3, "fill") == 0) { handle_b_fill(message); return; } if (strcmp(address + 3, "query") == 0) { handle_b_query<realtime>(message, endpoint); return; } if (strcmp(address + 3, "get") == 0) { handle_b_get<realtime>(message, endpoint); return; } if (strcmp(address + 3, "getn") == 0) { handle_b_getn<realtime>(message, endpoint); return; } if (strcmp(address + 3, "gen") == 0) { handle_b_gen<realtime>(message, msg_size, endpoint); return; } if (strcmp(address + 3, "close") == 0) { handle_b_close<realtime>(message, endpoint); return; } } template <bool realtime> void dispatch_control_bus_commands(const char* address, ReceivedMessage const& message, endpoint_ptr const& endpoint) { assert(address[1] == 'c'); assert(address[2] == '_'); if (strcmp(address + 3, "set") == 0) { handle_c_set(message); return; } if (strcmp(address + 3, "setn") == 0) { handle_c_setn(message); return; } if (strcmp(address + 3, "fill") == 0) { handle_c_fill(message); return; } if (strcmp(address + 3, "get") == 0) { handle_c_get<realtime>(message, endpoint); return; } if (strcmp(address + 3, "getn") == 0) { handle_c_getn<realtime>(message, endpoint); return; } } template <bool realtime> void dispatch_synthdef_commands(const char* address, ReceivedMessage const& message, endpoint_ptr const& endpoint) { assert(address[1] == 'd'); assert(address[2] == '_'); if (strcmp(address + 3, "recv") == 0) { handle_d_recv<realtime>(message, endpoint); return; } if (strcmp(address + 3, "load") == 0) { handle_d_load<realtime>(message, endpoint); return; } if (strcmp(address + 3, "loadDir") == 0) { handle_d_loadDir<realtime>(message, endpoint); return; } if (strcmp(address + 3, "free") == 0) { handle_d_free(message); return; } } template <bool realtime> void dispatch_synth_commands(const char* address, ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint) { assert(address[1] == 's'); assert(address[2] == '_'); if (strcmp(address + 3, "new") == 0) { handle_s_new(message); return; } if (strcmp(address + 3, "noid") == 0) { handle_s_noid(message); return; } if (strcmp(address + 3, "get") == 0) { handle_s_get<realtime>(message, msg_size, endpoint); return; } if (strcmp(address + 3, "getn") == 0) { handle_s_getn<realtime>(message, msg_size, endpoint); return; } } } /* namespace */ template <bool realtime> void sc_osc_handler::handle_message_sym_address(ReceivedMessage const& message, size_t msg_size, endpoint_ptr const& endpoint) { const char* address = message.AddressPattern(); /* scsynth doesn't require the leading / */ if (address[0] != '/') address -= 1; if (address[2] == '_') { if (address[1] == 'g') { dispatch_group_commands<realtime>(address, message, endpoint); return; } if (address[1] == 'n') { dispatch_node_commands<realtime>(address, message, endpoint); return; } if (address[1] == 'b') { dispatch_buffer_commands<realtime>(address, message, msg_size, endpoint); return; } if (address[1] == 'c') { dispatch_control_bus_commands<realtime>(address, message, endpoint); return; } if (address[1] == 'd') { dispatch_synthdef_commands<realtime>(address, message, endpoint); return; } if (address[1] == 's') { dispatch_synth_commands<realtime>(address, message, msg_size, endpoint); return; } } if (strcmp(address + 1, "p_new") == 0) { handle_p_new(message); return; } if (strcmp(address + 1, "u_cmd") == 0) { handle_u_cmd(message, msg_size); return; } if (strcmp(address + 1, "status") == 0) { handle_status<realtime>(endpoint); return; } if (strcmp(address + 1, "sync") == 0) { handle_sync<realtime>(message, endpoint); return; } if (strcmp(address + 1, "quit") == 0) { handle_quit<realtime>(endpoint); return; } if (strcmp(address + 1, "notify") == 0) { handle_notify<realtime>(message, endpoint); return; } if (strcmp(address + 1, "dumpOSC") == 0) { handle_dumpOSC(message); return; } if (strcmp(address + 1, "clearSched") == 0) { handle_clearSched(); return; } if (strcmp(address + 1, "error") == 0) { handle_error(message); return; } if (strcmp(address + 1, "cmd") == 0) { handle_cmd(message, msg_size, endpoint); return; } if (strcmp(address + 1, "version") == 0) { handle_version<realtime>(endpoint); return; } if (strcmp(address + 1, "rtMemoryStatus") == 0) { handle_rtMemoryStatus<realtime>(endpoint); return; } if (strcmp(address + 1, "none") == 0) return; handle_unhandled_message(message); } template <bool realtime> void handle_asynchronous_command(World* world, const char* cmdName, void* cmdData, AsyncStageFn stage2, AsyncStageFn stage3, AsyncStageFn stage4, AsyncFreeFn cleanup, completion_message&& message, endpoint_ptr endpoint) { // Usually, this API function is called in response to plugin/unit commands (handled *before* DSP computation). // We lock the memory pool nevertheless, just in case it's called from RT helper threads. // Actually, it's not a good idea to call it from within the perform routine because fire_system_callback() // is not thread-safe (the system_interpreter is a SPSC FIFO). On the other hand, calling it in the constructor // seems to be safe because constructors are protected by a global lock and therefore never run in parallel. spin_lock::scoped_lock lock(system_callback_allocator_lock); cmd_dispatcher<realtime>::fire_system_callback( [=, message = std::move(message), endpoint = std::move(endpoint)]() mutable { // stage 2 (NRT thread) bool result2 = !stage2 || (stage2)(world, cmdData); if (result2) { cmd_dispatcher<realtime>::fire_rt_callback( [=, message = std::move(message), endpoint = std::move(endpoint)]() mutable { // stage 3 (RT thread) bool result3 = !stage3 || (stage3)(world, cmdData); if (result3) { handle_completion_message(std::move(message), endpoint); cmd_dispatcher<realtime>::fire_io_callback([=, endpoint = std::move(endpoint)] { // stage 4 (NRT thread) bool result4 = !stage4 || (stage4)(world, cmdData); if (result4 && cmdName) send_done_message(endpoint, cmdName); // free in RT thread! cmd_dispatcher<realtime>::fire_rt_callback([=] { if (cleanup) (cleanup)(world, cmdData); }); }); } else { if (cleanup) (cleanup)(world, cmdData); consume(std::move(message)); } }); } else { // free in RT thread! cmd_dispatcher<realtime>::fire_rt_callback([=, message = std::move(message)]() mutable { if (cleanup) (cleanup)(world, cmdData); consume(std::move(message)); }); } }); } void sc_osc_handler::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 { completion_message msg(completionMsgSize, completionMsgData); endpoint_ptr shared_endpoint; nova_endpoint* endpoint = replyAddr ? static_cast<nova_endpoint*>(replyAddr) : nullptr; if (endpoint) shared_endpoint = endpoint->shared_from_this(); if (world->mRealTime) handle_asynchronous_command<true>(world, cmdName, cmdData, stage2, stage3, stage4, cleanup, std::move(msg), shared_endpoint); else handle_asynchronous_command<false>(world, cmdName, cmdData, stage2, stage3, stage4, cleanup, std::move(msg), shared_endpoint); } // called from RT thread, perform in NRT thread, free in RT thread template <bool realtime> void handle_message_from_RT(FifoMsg& msg) { // see handle_asynchronous_command() spin_lock::scoped_lock lock(system_callback_allocator_lock); cmd_dispatcher<realtime>::fire_system_callback([msg]() mutable { msg.Perform(); cmd_dispatcher<realtime>::fire_rt_callback([msg]() mutable { msg.Free(); }); }); } void sc_osc_handler::send_message_from_RT(const World* world, FifoMsg& msg) const { if (world->mRealTime) handle_message_from_RT<true>(msg); else handle_message_from_RT<false>(msg); } // called from NRT thread, perform in RT thread, free in NRT thread template <bool realtime> void handle_message_to_RT(FifoMsg& msg) { cmd_dispatcher<realtime>::fire_rt_callback([msg]() mutable { msg.Perform(); cmd_dispatcher<realtime>::fire_system_callback([msg]() mutable { msg.Free(); }); }); } void sc_osc_handler::send_message_to_RT(const World* world, FifoMsg& msg) const { if (world->mRealTime) handle_message_to_RT<true>(msg); else handle_message_to_RT<false>(msg); } } /* namespace detail */ } /* namespace nova */
122,237
C++
.cpp
2,939
33.060225
120
0.597244
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
29,925
sc_synth_definition.cpp
supercollider_supercollider/server/supernova/sc/sc_synth_definition.cpp
// prototype of a supercollider-synthdef-based synth prototype, implementation // 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. #include <iostream> #include <future> #include <filesystem> #include <boost/range/iterator_range.hpp> #include "sc_synth.hpp" #include "sc_ugen_factory.hpp" #include "sc_synth_definition.hpp" #include "server/synth_factory.hpp" namespace nova { using namespace std; void register_synthdefs(synth_factory& factory, std::vector<sc_synthdef>&& defs) { for (sc_synthdef& def : defs) { sc_synth_definition_ptr sp = new sc_synth_definition(std::move(def)); factory.register_definition(std::move(sp)); } } std::vector<sc_synthdef> sc_read_synthdefs_file(path const& file) { try { return read_synthdef_file(file.string()); } catch (std::exception const& e) { cout << "Exception when parsing synthdef file " << file.string() << ": " << e.what() << endl; return std::vector<sc_synthdef>(); } } std::vector<sc_synthdef> sc_read_synthdefs_dir(path const& dir) { using namespace std::filesystem; using namespace std; typedef vector<sc_synthdef> def_vector; def_vector ret; if (!exists(dir)) return ret; // FIXME: some kind of threadpool would be nice! auto launch_policy = thread::hardware_concurrency() > 1 ? launch::async : launch::deferred; vector<future<def_vector>> futures; for (auto const& entry : boost::make_iterator_range(recursive_directory_iterator(dir), recursive_directory_iterator())) { if (!is_directory(entry.status())) { auto path_name = entry.path(); if (path_name.extension() == ".scsyndef") futures.emplace_back(async(launch_policy, [=]() { return sc_read_synthdefs_file(path_name); })); } } for (future<def_vector>& synthdef_future : futures) { for (sc_synthdef& definition : synthdef_future.get()) ret.emplace_back(std::move(definition)); } return ret; } sc_synth_definition::sc_synth_definition(sc_synthdef&& sd): synth_definition(sd.name()), sc_synthdef(std::forward<sc_synthdef>(sd)) { std::map<int, symbol> reversed_parameter_map; for (auto const& elem : parameter_map) reversed_parameter_map.insert(std::make_pair(elem.second, elem.first)); for (auto const& entry : parameter_map) { const symbol name = entry.first; const int32_t current_index = entry.second; int controls_per_parameter = 1; for (int32_t next_index = current_index + 1; next_index != parameter_count(); ++next_index) { if (reversed_parameter_map.find(next_index) != reversed_parameter_map.end()) break; controls_per_parameter += 1; } slot_resolver::register_slot(name, current_index, controls_per_parameter); } } abstract_synth* sc_synth_definition::create_instance(int node_id) { sc_synth* synth = new sc_synth(node_id, this); return synth; } } /* namespace nova */
3,785
C++
.cpp
88
37.943182
112
0.680556
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
29,926
sc_plugin_interface.cpp
supercollider_supercollider/server/supernova/sc/sc_plugin_interface.cpp
// interface for supercollider plugins // 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. #include <cstdarg> #include <random> #include "SC_Win32Utils.h" #include "SC_SndFileHelpers.hpp" #include "sc_plugin_interface.hpp" #include "sc_ugen_factory.hpp" #include "sc_synth.hpp" #include "nova-simd/simd_memory.hpp" #include "../server/server_args.hpp" #include "../server/memory_pool.hpp" #include "../server/server.hpp" #include "malloc_aligned.hpp" #include "../utilities/sized_array.hpp" #include "SC_Prototypes.h" #include "SC_Unit.h" #include "SC_Lock.h" #include "clz.h" #include "SC_fftlib.h" #include "SC_Lock.h" #include "../../common/Samp.hpp" #include "../../common/SC_SndFileHelpers.hpp" #include <boost/math/constants/constants.hpp> // undefine the shadowed scfft functions #undef scfft_create #undef scfft_dofft #undef scfft_doifft #undef scfft_destroy namespace nova { spin_lock log_guard; // needs to be acquired for logging from the helper threads! namespace { spin_lock rt_pool_guard; inline Node* as_Node(server_node* node) { if (node == nullptr) return nullptr; // hack!!! we only assume that the 32bit integer mID member can be accessed via Node if (node->is_synth()) { sc_synth* s = static_cast<sc_synth*>(node); return &s->mNode; } else { void* nodePointer = &node->node_id; return (Node*)nodePointer; } } void pause_node(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_pause_node(node); } void free_node(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); } void free_node_and_preceding(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of preceding nodes\n"); return; } server_node* preceding = node->previous_node(); if (preceding) sc_factory->add_done_node(preceding); } void free_node_and_pause_preceding(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of preceding nodes\n"); return; } server_node* preceding = node->previous_node(); if (preceding) sc_factory->add_pause_node(preceding); } void free_node_and_preceding_children(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of preceding nodes"); return; } server_node* preceding = node->previous_node(); if (!preceding) return; if (preceding->is_synth()) sc_factory->add_done_node(preceding); else { abstract_group* preceding_group = static_cast<abstract_group*>(preceding); sc_factory->add_freeAll_node(preceding_group); } } void free_node_and_preceding_deep(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { log("parallel groups have no notion of preceding nodes\n"); return; } server_node* preceding = node->previous_node(); if (!preceding) return; if (preceding->is_synth()) sc_factory->add_done_node(preceding); else { abstract_group* preceding_group = static_cast<abstract_group*>(preceding); sc_factory->add_freeDeep_node(preceding_group); } } void free_node_and_all_preceding(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of preceding nodes\n"); return; } for (;;) { node = node->previous_node(); if (node) sc_factory->add_done_node(node); else return; } } void free_node_and_following(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } server_node* next = node->next_node(); if (next) sc_factory->add_done_node(next); } void free_node_and_pause_following(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } server_node* next = node->next_node(); if (next) sc_factory->add_pause_node(next); } void free_node_and_resume_following(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } server_node* next = node->next_node(); if (next) sc_factory->add_resume_node(next); } void free_node_and_following_children(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } server_node* following = node->previous_node(); if (!following) return; if (following->is_synth()) sc_factory->add_done_node(following); else { abstract_group* following_group = static_cast<abstract_group*>(following); sc_factory->add_freeAll_node(following_group); } } void free_node_and_following_deep(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } server_node* following = node->previous_node(); if (!following) return; if (following->is_synth()) sc_factory->add_done_node(following); else { abstract_group* following_group = static_cast<abstract_group*>(following); sc_factory->add_freeDeep_node(following_group); } } void free_node_and_all_following(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); sc_factory->add_done_node(node); if (node->get_parent()->is_parallel()) { spin_lock::scoped_lock lock(log_guard); log("parallel groups have no notion of following nodes\n"); return; } for (;;) { node = node->previous_node(); if (node) sc_factory->add_done_node(node); else return; } } void free_group_members(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); abstract_group* group = const_cast<abstract_group*>(node->get_parent()); sc_factory->add_freeAll_node(group); } void free_parent_group(Unit* unit) { server_node* node = static_cast<sc_synth*>(unit->mParent); abstract_group* group = const_cast<abstract_group*>(node->get_parent()); sc_factory->add_done_node(group); } bool get_scope_buffer(World* inWorld, int index, int channels, int maxFrames, ScopeBufferHnd& hnd) { scope_buffer_writer writer = instance->get_scope_buffer_writer(index, channels, maxFrames); if (writer.valid()) { hnd.internalData = writer.buffer; hnd.data = writer.data(); hnd.channels = channels; hnd.maxFrames = maxFrames; return true; } else { hnd.internalData = nullptr; return false; } } void push_scope_buffer(World* inWorld, ScopeBufferHnd& hnd, int frames) { scope_buffer_writer writer(reinterpret_cast<scope_buffer*>(hnd.internalData)); writer.push(frames); hnd.data = writer.data(); } void release_scope_buffer(World* inWorld, ScopeBufferHnd& hnd) { scope_buffer_writer writer(reinterpret_cast<scope_buffer*>(hnd.internalData)); instance->release_scope_buffer_writer(writer); } } /* namespace */ } /* namespace nova */ extern "C" { bool define_unit(const char* inUnitClassName, size_t inAllocSize, UnitCtorFunc inCtor, UnitDtorFunc inDtor, uint32 inFlags) { try { nova::sc_factory->register_ugen(inUnitClassName, inAllocSize, inCtor, inDtor, inFlags); return true; } catch (...) { return false; } } bool define_bufgen(const char* name, BufGenFunc func) { try { nova::sc_factory->register_bufgen(name, func); return true; } catch (...) { return false; } } bool define_unitcmd(const char* unitClassName, const char* cmdName, UnitCmdFunc inFunc) { return nova::sc_factory->register_ugen_command_function(unitClassName, cmdName, inFunc); } bool define_plugincmd(const char* name, PlugInCmdFunc func, void* user_data) { return nova::sc_factory->register_cmd_plugin(name, func, user_data); } void* rt_alloc(World* dummy, size_t size) { nova::spin_lock::scoped_lock lock(nova::rt_pool_guard); if (size) return nova::rt_pool.malloc(size); else return nullptr; } void* rt_realloc(World* dummy, void* ptr, size_t size) { nova::spin_lock::scoped_lock lock(nova::rt_pool_guard); return nova::rt_pool.realloc(ptr, size); } void rt_free(World* dummy, void* ptr) { nova::spin_lock::scoped_lock lock(nova::rt_pool_guard); if (ptr) nova::rt_pool.free(ptr); } void* nrt_alloc(size_t size) { return malloc(size); } void* nrt_realloc(void* ptr, size_t size) { return realloc(ptr, size); } void nrt_free(void* ptr) { free(ptr); } void* nrt_alloc_2(World* dummy, size_t size) { return malloc(size); } void* nrt_realloc_2(World* dummy, void* ptr, size_t size) { return realloc(ptr, size); } void nrt_free_2(World* dummy, void* ptr) { free(ptr); } void clear_outputs(Unit* unit, int samples) { const uint32_t outputs = unit->mNumOutputs; if ((samples & 63) == 0) { const uint32_t loops = samples / 64; for (int i = 0; i != outputs; ++i) { float* buffer = unit->mOutBuf[i]; for (int loop = 0; loop != loops; ++loop) { nova::zerovec_simd<64>(buffer + loop * 64); } } return; } if ((samples & 15) == 0) { for (int i = 0; i != outputs; ++i) nova::zerovec_simd(unit->mOutBuf[i], samples); return; } for (int i = 0; i != outputs; ++i) nova::zerovec(unit->mOutBuf[i], samples); } void node_end(struct Node* node) { nova::server_node* s = nova::instance->find_node(node->mID); nova::sc_factory->add_done_node(s); } void node_set_run(struct Node* node, int run) { using namespace nova; server_node* s = instance->find_node(node->mID); if (run == 0) sc_factory->add_pause_node(s); else sc_factory->add_resume_node(s); } int print(const char* fmt, ...) { va_list vargs; va_start(vargs, fmt); nova::log_guard.lock(); bool status = nova::log_printf(fmt, vargs); nova::log_guard.unlock(); va_end(vargs); return (status == true) ? 0 : -1; } /* todo: we need to implement most of the done actions */ void done_action(int done_action, struct Unit* unit) { using namespace nova; switch (done_action) { case 0: // do nothing when the UGen is finished return; case 1: // pause the enclosing synth, but do not free it nova::pause_node(unit); return; case 2: // free the enclosing synth nova::free_node(unit); return; case 3: // free both this synth and the preceding node nova::free_node_and_preceding(unit); return; case 4: // free both this synth and the following node nova::free_node_and_following(unit); return; case 5: // free this synth; if the preceding node is a group then do g_freeAll on it, else free it nova::free_node_and_preceding_children(unit); return; case 6: nova::free_node_and_following_children(unit); // free this synth; if the following node is a group then do g_freeAll on it, else free it return; case 7: // free this synth and all preceding nodes in this group nova::free_node_and_all_preceding(unit); return; case 8: // free this synth and all following nodes in this group nova::free_node_and_all_following(unit); return; case 9: // free this synth and pause the preceding node nova::free_node_and_pause_preceding(unit); return; case 10: // free this synth and pause the following node nova::free_node_and_pause_following(unit); return; case 11: // free this synth and if the preceding node is a group then do g_deepFree on it, else free it nova::free_node_and_preceding_deep(unit); return; case 12: // free this synth and if the following node is a group then do g_deepFree on it, else free it nova::free_node_and_following_deep(unit); return; case 13: // free this synth and all other nodes in this group (before and after) nova::free_group_members(unit); return; case 14: // free the enclosing group and all nodes within it (including this synth) nova::free_parent_group(unit); return; case 15: // free this synth and resume the following node nova::free_node_and_resume_following(unit); return; default: return; } } int buf_alloc(SndBuf* buf, int channels, int frames, double samplerate) { try { nova::sc_factory->allocate_buffer(buf, channels, frames, samplerate); return kSCErr_None; } catch (std::exception const& e) { std::cout << e.what() << std::endl; return kSCErr_Failed; } } void send_trigger(Node* unit, int trigger_id, float value) { nova::instance->send_trigger(unit->mID, trigger_id, value); } void world_lock(World* world) { reinterpret_cast<SC_Lock*>(world->mNRTLock)->lock(); } void world_unlock(World* world) { reinterpret_cast<SC_Lock*>(world->mNRTLock)->unlock(); } Node* get_node(World* world, int id) { nova::server_node* node = nova::instance->find_node(id); return nova::as_Node(node); } void send_node_reply(Node* node, int reply_id, const char* command_name, int argument_count, const float* values) { if (!nova::sc_factory->world.mRealTime) return; nova::instance->send_node_reply(node->mID, reply_id, command_name, argument_count, values); } int do_asynchronous_command( 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) { nova::instance->do_asynchronous_command(inWorld, replyAddr, cmdName, cmdData, stage2, stage3, stage4, cleanup, completionMsgSize, completionMsgData); return 0; } bool send_message_from_RT(World* world, struct FifoMsg& msg) { nova::instance->send_message_from_RT(world, msg); return true; } bool send_message_to_RT(World* world, struct FifoMsg& msg) { nova::instance->send_message_to_RT(world, msg); return true; } } /* extern "C" */ namespace nova { inline void initialize_rate(Rate& rate, double sample_rate, int blocksize) { rate.mSampleRate = sample_rate; rate.mSampleDur = 1. / sample_rate; rate.mRadiansPerSample = 2 * boost::math::constants::pi<double>() / sample_rate; rate.mBufLength = blocksize; rate.mBufDuration = blocksize / sample_rate; rate.mBufRate = sample_rate / blocksize; rate.mSlopeFactor = 1. / blocksize; div_t div_result = std::div(blocksize, 3); rate.mFilterLoops = div_result.quot; rate.mFilterRemain = div_result.rem; if (rate.mFilterLoops == 0.) rate.mFilterSlope = 0.; else rate.mFilterSlope = 1. / rate.mFilterLoops; } void sc_plugin_interface::initialize(server_arguments const& args, float* control_busses) { const bool nrt_mode = args.non_rt; done_nodes.reserve(64); pause_nodes.reserve(16); resume_nodes.reserve(16); freeAll_nodes.reserve(16); freeDeep_nodes.reserve(16); /* define functions */ sc_interface.fDefineUnit = &define_unit; sc_interface.fDefineBufGen = &define_bufgen; sc_interface.fDefinePlugInCmd = &define_plugincmd; sc_interface.fDefineUnitCmd = &define_unitcmd; /* interface functions */ sc_interface.fNodeEnd = &node_end; sc_interface.fGetNode = &get_node; sc_interface.fNodeRun = &node_set_run; sc_interface.fPrint = &print; sc_interface.fDoneAction = &done_action; sc_interface.fSendMsgFromRT = &send_message_from_RT; sc_interface.fSendMsgToRT = &send_message_to_RT; /* sndfile functions */ #ifdef NO_LIBSNDFILE sc_interface.fSndFileFormatInfoFromStrings = nullptr; #else sc_interface.fSndFileFormatInfoFromStrings = &sndfileFormatInfoFromStrings; #endif /* wave tables */ sc_interface.mSine = gSine; sc_interface.mCosecant = gInvSine; sc_interface.mSineSize = kSineSize; sc_interface.mSineWavetable = gSineWavetable; /* memory allocation */ if (!nrt_mode) { sc_interface.fRTAlloc = &rt_alloc; sc_interface.fRTRealloc = &rt_realloc; sc_interface.fRTFree = &rt_free; } else { sc_interface.fRTAlloc = &nrt_alloc_2; sc_interface.fRTRealloc = &nrt_realloc_2; sc_interface.fRTFree = &nrt_free_2; } sc_interface.fNRTAlloc = &nrt_alloc; sc_interface.fNRTRealloc = &nrt_realloc; sc_interface.fNRTFree = &nrt_free; /* ugen functions */ sc_interface.fClearUnitOutputs = clear_outputs; /* buffer functions */ sc_interface.fBufAlloc = &buf_alloc; /* trigger functions */ sc_interface.fSendTrigger = &send_trigger; sc_interface.fSendNodeReply = &send_node_reply; /* world locks */ sc_interface.fNRTLock = &world_lock; sc_interface.fNRTUnlock = &world_unlock; world.mNRTLock = new SC_Lock(); /* fft library */ sc_interface.fSCfftCreate = &scfft_create; sc_interface.fSCfftDestroy = &scfft_destroy; sc_interface.fSCfftDoFFT = &scfft_dofft; sc_interface.fSCfftDoIFFT = &scfft_doifft; /* scope API */ sc_interface.fGetScopeBuffer = &get_scope_buffer; sc_interface.fPushScopeBuffer = &push_scope_buffer; sc_interface.fReleaseScopeBuffer = &release_scope_buffer; /* osc plugins */ sc_interface.fDoAsynchronousCommand = &do_asynchronous_command; /* initialize world */ /* control busses */ world.mControlBus = control_busses; world.mNumControlBusChannels = args.control_busses; world.mControlBusTouched = new int32[args.control_busses]; std::fill(world.mControlBusTouched, world.mControlBusTouched + args.control_busses, -1); /* audio busses */ audio_busses.initialize(args.audio_busses, args.blocksize); world.mAudioBus = audio_busses.buffers; world.mNumAudioBusChannels = args.audio_busses; world.mAudioBusTouched = new int32[args.audio_busses]; world.mAudioBusLocks = audio_busses.locks; world.mControlBusLock = new spin_lock(); std::fill(world.mAudioBusTouched, world.mAudioBusTouched + args.audio_busses, -1); /* audio buffers */ world.mNumSndBufs = args.buffers; world.mSndBufs = new SndBuf[world.mNumSndBufs]; world.mSndBufsNonRealTimeMirror = new SndBuf[world.mNumSndBufs]; world.mSndBufUpdates = new SndBufUpdates[world.mNumSndBufs]; memset(world.mSndBufs, 0, world.mNumSndBufs * sizeof(SndBuf)); memset(world.mSndBufsNonRealTimeMirror, 0, world.mNumSndBufs * sizeof(SndBuf)); memset(world.mSndBufUpdates, 0, world.mNumSndBufs * sizeof(SndBufUpdates)); world.mBufCounter = 0; async_buffer_guards.reset(new std::mutex[world.mNumSndBufs]); /* audio settings */ world.mBufLength = args.blocksize; world.mSampleRate = args.samplerate; initialize_rate(world.mFullRate, args.samplerate, args.blocksize); initialize_rate(world.mBufRate, double(args.samplerate) / args.blocksize, 1); world.mNumInputs = args.input_channels; world.mNumOutputs = args.output_channels; world.mRealTime = !args.non_rt; world.mVerbosity = args.verbosity; /* rngs */ world.mNumRGens = args.rng_count; world.mRGen = new RGen[world.mNumRGens]; std::vector<std::uint32_t> seeds(world.mNumRGens); try { std::random_device rd; std::seed_seq seq({ rd(), rd(), rd() }); seq.generate(seeds.begin(), seeds.end()); } catch (...) { auto now = std::chrono::high_resolution_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); std::seed_seq seq({ seconds.count() }); seq.generate(seeds.begin(), seeds.end()); } for (int i = 0; i < world.mNumRGens; ++i) world.mRGen[i].init(seeds[i]); } void sc_plugin_interface::reset_sampling_rate(int sr) { world.mSampleRate = sr; initialize_rate(world.mFullRate, sr, world.mBufLength); initialize_rate(world.mBufRate, double(sr) / world.mBufLength, 1); } void sc_done_action_handler::apply_done_actions(void) { for (server_node* node : done_nodes) instance->free_node(node); done_nodes.clear(); for (server_node* node : resume_nodes) instance->node_resume(node); resume_nodes.clear(); for (server_node* node : pause_nodes) instance->node_pause(node); pause_nodes.clear(); for (abstract_group* group : freeDeep_nodes) instance->group_free_deep(group); freeDeep_nodes.clear(); for (abstract_group* group : freeAll_nodes) instance->group_free_all(group); freeAll_nodes.clear(); } sc_plugin_interface::~sc_plugin_interface(void) { delete[] world.mAudioBusTouched; delete[] world.mControlBusTouched; delete[] world.mSndBufs; delete[] world.mSndBufsNonRealTimeMirror; delete[] world.mSndBufUpdates; delete[] world.mRGen; delete reinterpret_cast<SC_Lock*>(world.mNRTLock); } namespace { sample* allocate_buffer(size_t samples) { const size_t alloc_size = samples * sizeof(sample); sample* ret = (sample*)calloc_aligned(alloc_size); if (ret) mlock(ret, alloc_size); return ret; } inline int32 bufmask(int32 x) { return (1 << (31 - CLZ(x))) - 1; } inline void sndbuf_init(SndBuf* buf) { buf->samplerate = 0; buf->sampledur = 0; buf->data = nullptr; buf->channels = 0; buf->samples = 0; buf->frames = 0; buf->mask = 0; buf->mask1 = 0; buf->coord = 0; buf->sndfile = nullptr; buf->isLocal = false; } inline void sndbuf_copy(SndBuf* dest, const SndBuf* src) { dest->samplerate = src->samplerate; dest->sampledur = src->sampledur; dest->data = src->data; dest->channels = src->channels; dest->samples = src->samples; dest->frames = src->frames; dest->mask = src->mask; dest->mask1 = src->mask1; dest->coord = src->coord; dest->sndfile = src->sndfile; dest->isLocal = src->isLocal; } static inline size_t compute_remaining_samples(size_t frames_per_read, size_t already_read, size_t total_frames) { int remain = frames_per_read; if (already_read + frames_per_read > total_frames) remain = total_frames - already_read; return remain; } void read_channel(SndfileHandle& sf, uint32_t channel_count, const uint32_t* channel_data, uint32 total_frames, sample* data) { const unsigned int frames_per_read = 1024; sized_array<sample> read_frame(sf.channels() * frames_per_read); if (channel_count == 1) { // fast-path for single-channel read for (size_t i = 0; i < total_frames; i += frames_per_read) { int remaining_samples = compute_remaining_samples(frames_per_read, i, total_frames); size_t read = sf.readf(read_frame.c_array(), remaining_samples); size_t channel_mapping = channel_data[0]; for (size_t frame = 0; frame != read; ++frame) { data[0] = read_frame[frame * sf.channels() + channel_mapping]; data += channel_count; } } } else { for (size_t i = 0; i < total_frames; i += frames_per_read) { int remaining_samples = compute_remaining_samples(frames_per_read, i, total_frames); size_t read = sf.readf(read_frame.c_array(), remaining_samples); for (size_t frame = 0; frame != read; ++frame) { for (size_t c = 0; c != channel_count; ++c) { size_t channel_mapping = channel_data[c]; data[c] = read_frame[frame * sf.channels() + channel_mapping]; } data += channel_count; } } } } } /* namespace */ void sc_plugin_interface::allocate_buffer(SndBuf* buf, uint32_t frames, uint32_t channels, double samplerate) { const uint32_t samples = frames * channels; if (samples == 0) throw std::runtime_error("invalid buffer size"); sample* data = nova::allocate_buffer(samples); if (data == nullptr) throw std::runtime_error("could not allocate memory"); buf->data = data; buf->channels = channels; buf->frames = frames; buf->samples = samples; buf->mask = bufmask(samples); /* for delay lines */ buf->mask1 = buf->mask - 1; /* for oscillators */ buf->samplerate = samplerate; buf->sampledur = 1.0 / samplerate; buf->isLocal = false; } SndBuf* sc_plugin_interface::allocate_buffer(uint32_t index, uint32_t frames, uint32_t channels) { SndBuf* buf = World_GetNRTBuf(&world, index); allocate_buffer(buf, frames, channels, world.mFullRate.mSampleRate); return buf; } void sc_plugin_interface::buffer_read_alloc(uint32_t index, const char* filename, uint32_t start, uint32_t frames) { auto f = makeSndfileHandle(filename); if (f.rawHandle() == nullptr) throw std::runtime_error(f.strError()); const size_t sf_frames = f.frames(); if (start > sf_frames) start = sf_frames; if (frames == 0 || frames > sf_frames - start) frames = sf_frames - start; SndBuf* buf = World_GetNRTBuf(&world, index); allocate_buffer(buf, frames, f.channels(), f.samplerate()); f.seek(start, SEEK_SET); f.readf(buf->data, frames); } void sc_plugin_interface::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) { // If no channel argument provided we read all channels. if (channel_count == 0) { buffer_read_alloc(index, filename, start, frames); return; } auto f = makeSndfileHandle(filename); if (f.rawHandle() == nullptr) throw std::runtime_error(f.strError()); uint32_t sf_channels = uint32_t(f.channels()); const uint32_t* max_chan = std::max_element(channel_data, channel_data + channel_count); if (*max_chan >= sf_channels) throw std::runtime_error("Channel out of range"); const size_t sf_frames = f.frames(); if (start > sf_frames) start = sf_frames; if (frames == 0 || frames > sf_frames - start) frames = sf_frames - start; SndBuf* buf = World_GetNRTBuf(&world, index); allocate_buffer(buf, frames, channel_count, f.samplerate()); f.seek(start, SEEK_SET); read_channel(f, channel_count, channel_data, frames, buf->data); } void sc_plugin_interface::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) { SndBuf* buf = World_GetNRTBuf(&world, index); int format = headerFormatFromString(header_format) | sampleFormatFromString(sample_format); auto sf = makeSndfileHandle(filename, SFM_WRITE, format, buf->channels, buf->samplerate); if (sf.rawHandle() == nullptr) throw std::runtime_error(sf.strError()); if (frames == 0xffffffff) frames = buf->frames; const uint32_t remain = uint32_t(buf->frames) > start ? buf->frames - start : 0; const uint32_t frames_to_write = std::min(remain, frames); if (frames_to_write) sf.writef(buf->data + start * buf->channels, frames_to_write); if (leave_open && !buf->sndfile) buf->sndfile = sf.takeOwnership(); } static void buffer_read_verify(SndfileHandle& sf, size_t min_length, size_t samplerate, bool check_samplerate) { if (sf.rawHandle() == nullptr) throw std::runtime_error(sf.strError()); if (sf.frames() < min_length) throw std::runtime_error("no more frames to read"); if (check_samplerate && (sf.samplerate() != samplerate)) throw std::runtime_error("sample rate mismatch"); } void sc_plugin_interface::buffer_read(uint32_t index, const char* filename, uint32_t start_file, uint32_t frames, uint32_t start_buffer, bool leave_open) { SndBuf* buf = World_GetNRTBuf(&world, index); if (uint32_t(buf->frames) < start_buffer) throw std::runtime_error("buffer already full"); auto sf = makeSndfileHandle(filename, SFM_READ); buffer_read_verify(sf, start_file, buf->samplerate, !leave_open); if (sf.channels() != buf->channels) throw std::runtime_error("channel count mismatch"); const uint32_t buffer_remain = buf->frames - start_buffer; const uint32_t file_remain = sf.frames() - start_file; const uint32_t frames_to_read = std::min(frames, std::min(buffer_remain, file_remain)); sf.seek(start_file, SEEK_SET); sf.readf(buf->data + start_buffer * buf->channels, frames_to_read); if (leave_open) buf->sndfile = sf.takeOwnership(); } void sc_plugin_interface::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) { SndBuf* buf = World_GetNRTBuf(&world, index); if (channel_count != uint32_t(buf->channels)) throw std::runtime_error("channel count mismatch"); if (uint32_t(buf->frames) >= start_buffer) throw std::runtime_error("buffer already full"); auto sf = makeSndfileHandle(filename, SFM_READ); buffer_read_verify(sf, start_file, buf->samplerate, !leave_open); uint32_t sf_channels = uint32_t(sf.channels()); const uint32_t* max_chan = std::max_element(channel_data, channel_data + channel_count); if (*max_chan >= sf_channels) throw std::runtime_error("channel count mismatch"); const uint32_t buffer_remain = buf->frames - start_buffer; const uint32_t file_remain = sf.frames() - start_file; const uint32_t frames_to_read = std::min(frames, std::min(buffer_remain, file_remain)); sf.seek(start_file, SEEK_SET); read_channel(sf, channel_count, channel_data, frames_to_read, buf->data); if (leave_open) buf->sndfile = sf.takeOwnership(); } void sc_plugin_interface::buffer_close(uint32_t index) { SndBuf* buf = World_GetNRTBuf(&world, index); if (buf->sndfile == nullptr) return; sf_close(GETSNDFILE(buf)); buf->sndfile = nullptr; } void sc_plugin_interface::buffer_zero(uint32_t index) { SndBuf* buf = World_GetNRTBuf(&world, index); uint32_t length = buf->frames * buf->channels; uint32_t unrolled = length & ~63; uint32_t remain = length & 63; zerovec_simd(buf->data, unrolled); zerovec(buf->data + unrolled, remain); } sample* sc_plugin_interface::buffer_generate(uint32_t buffer_index, const char* cmd_name, struct sc_msg_iter& msg) { return sc_factory->run_bufgen(&world, cmd_name, buffer_index, &msg); } void sc_plugin_interface::buffer_sync(uint32_t index) noexcept { sndbuf_copy(world.mSndBufs + index, world.mSndBufsNonRealTimeMirror + index); increment_write_updates(index); } void sc_plugin_interface::free_buffer(uint32_t index) { SndBuf* buf = world.mSndBufsNonRealTimeMirror + index; if (buf->sndfile) sf_close(GETSNDFILE(buf)); sndbuf_init(buf); } } /* namespace nova */
34,211
C++
.cpp
849
34.354535
117
0.659293
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
29,927
sc_synth.cpp
supercollider_supercollider/server/supernova/sc/sc_synth.cpp
// 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. #include <cstdio> #include "SC_Win32Utils.h" #include <boost/align/align_up.hpp> #include "sc_msg_iter.h" #include "sc_synth.hpp" #include "sc_ugen_factory.hpp" #include "../server/server.hpp" namespace nova { sc_synth::sc_synth(int node_id, sc_synth_definition_ptr const& prototype): abstract_synth(node_id, prototype) { World const& world = sc_factory->world; const bool rt_synthesis = world.mRealTime; mNode.mWorld = &sc_factory->world; rgen.init((uint32_t)(uint64_t)this); /* initialize sc wrapper class */ mRGen = &rgen; mSubsampleOffset = world.mSubsampleOffset; mSampleOffset = world.mSampleOffset; mLocalAudioBusUnit = nullptr; mLocalControlBusUnit = nullptr; localBufNum = 0; localMaxBufNum = 0; // so far mPrivate is only used for queued unit commands, // i.e. it just points to the head of the list. mPrivate = nullptr; mNode.mID = node_id; sc_synthdef const& synthdef = *prototype; const size_t parameter_count = synthdef.parameter_count(); const size_t constants_count = synthdef.constants.size(); /* we allocate one memory chunk */ const size_t wire_buffer_alignment = 64 * 8; // align to cache line boundaries const size_t alloc_size = prototype->memory_requirement(); const size_t sample_alloc_size = world.mBufLength * synthdef.buffer_count + wire_buffer_alignment /* for alignment */; const size_t total_alloc_size = alloc_size + sample_alloc_size * sizeof(sample); char* raw_chunk = rt_synthesis ? (char*)rt_pool.malloc(total_alloc_size) : (char*)malloc(total_alloc_size); if (raw_chunk == nullptr) throw std::bad_alloc(); linear_allocator allocator(raw_chunk); /* prepare controls */ mNumControls = parameter_count; mControls = allocator.alloc<float>(parameter_count); mControlRates = allocator.alloc<int>(parameter_count); mAudioBusOffsets = allocator.alloc<int>(parameter_count); mMapControls = allocator.alloc<float*>(parameter_count); /* initialize controls */ for (size_t i = 0; i != parameter_count; ++i) { mControls[i] = synthdef.parameters[i]; /* initial parameters */ mMapControls[i] = &mControls[i]; /* map to control values */ mControlRates[i] = 0; /* init to 0*/ mAudioBusOffsets[i] = -1; /* init to -1: not mapped to an audio bus yet */ } /* allocate constant wires */ mWire = allocator.alloc<Wire>(constants_count); for (size_t i = 0; i != synthdef.constants.size(); ++i) { Wire* wire = mWire + i; wire->mFromUnit = nullptr; wire->mCalcRate = 0; wire->mBuffer = nullptr; wire->mScalarValue = get_constant(i); } unit_count = prototype->unit_count(); calc_unit_count = prototype->calc_unit_count(); units = allocator.alloc<Unit*>(unit_count); calc_units = allocator.alloc<Unit*>(calc_unit_count + 1); // over-allocate to allow prefetching unit_buffers = allocator.alloc<sample>(sample_alloc_size); unit_buffers = static_cast<sample*>(boost::alignment::align_up(unit_buffers, wire_buffer_alignment)); /* allocate unit generators */ sc_factory->allocate_ugens(synthdef.graph.size()); for (size_t i = 0; i != synthdef.graph.size(); ++i) { sc_synthdef::unit_spec_t const& spec = synthdef.graph[i]; units[i] = spec.prototype->construct(spec, this, i, &sc_factory->world, allocator); } for (size_t i = 0; i != synthdef.calc_unit_indices.size(); ++i) { int32_t index = synthdef.calc_unit_indices[i]; calc_units[i] = units[index]; } assert((char*)mControls + alloc_size <= allocator.alloc<char>()); // ensure the memory boundaries } sc_synth::~sc_synth(void) { assert(!initialized); } extern "C" { void* rt_alloc(World* dummy, size_t size); void* rt_free(World* dummy, void* ptr); } // FIXME: for some reason, we cannot initialize multiple synths in parallel static spin_lock scsynth_preparation_lock; void sc_synth::prepare(void) { assert(!initialized); scsynth_preparation_lock.lock(); std::for_each(units, units + unit_count, [](Unit* unit) { sc_ugen_def* def = reinterpret_cast<sc_ugen_def*>(unit->mUnitDef); def->initialize(unit); }); scsynth_preparation_lock.unlock(); initialized = true; // *finally* dispatch queued unit commands auto cmd = (sc_unit_cmd*)mPrivate; while (cmd) { auto next = cmd->next; sc_msg_iter args(cmd->size, cmd->data); // error checking has already be done in Unit_DoCmd() int node_id = args.geti(); assert(node_id == mNode.mID); int ugen_index = args.geti(); const char* cmd_name = args.gets(); apply_unit_cmd(cmd_name, ugen_index, &args); // NOTE: we can't just do rt_pool.free() because other synths might be // calling rt_alloc()/rt_free() concurrently in their calc function! rt_free(nullptr, cmd); cmd = next; } mPrivate = nullptr; } void sc_synth::finalize() { if (initialized) { std::for_each(units, units + unit_count, [](Unit* unit) { sc_ugen_def* def = reinterpret_cast<sc_ugen_def*>(unit->mUnitDef); def->destruct(unit); }); } sc_factory->free_ugens(unit_count); if (sc_factory->is_realtime_synthesis()) rt_pool.free(mControls); else free(mControls); initialized = false; // free queued unit commands // AFAICT this can only happen if a Graph is created, Unit commands are sent and the Graph // is deleted all at the same time stamp. auto* cmd = (sc_unit_cmd*)mPrivate; while (cmd) { auto next = cmd->next; rt_pool.free(cmd); cmd = next; } } void sc_synth::set(slot_index_t slot_index, sample val) { if (slot_index >= mNumControls) { log("argument number out of range\n"); return; } mControlRates[slot_index] = 0; mMapControls[slot_index] = &mControls[slot_index]; mControls[slot_index] = val; } void sc_synth::set_control_array(slot_index_t slot_index, size_t count, sample* val) { if (slot_index + count >= mNumControls) return; for (size_t i = 0; i != count; ++i) set(slot_index + i, val[i]); } float sc_synth::get(slot_index_t slot_index) const { return mControls[slot_index]; } bool sc_synth::getMappedSymbol(slot_index_t slot_index, char* str) const { // analogous place in scsynth: SC_Group.cpp: void Group_QueryTreeAndControls(Group* inGroup, big_scpacket *packet) bool isMapped = mMapControls[slot_index] != mControls + slot_index; if (isMapped) { if (mControlRates[slot_index] == 2) { int bus = mMapControls[slot_index] - mNode.mWorld->mAudioBus; bus = bus / mNode.mWorld->mBufLength; sprintf(str, "a%d", bus); } else { int bus = mMapControls[slot_index] - mNode.mWorld->mControlBus; sprintf(str, "c%d", bus); } } return isMapped; } void sc_synth::map_control_bus_control(unsigned int slot_index, int control_bus_index) { if (slot_index >= mNumControls) return; World* world = mNode.mWorld; if (control_bus_index < 0) { mControlRates[slot_index] = 0; mMapControls[slot_index] = mControls + slot_index; } else if (uint32(control_bus_index) < world->mNumControlBusChannels) { mControlRates[slot_index] = 1; mMapControls[slot_index] = world->mControlBus + control_bus_index; } } void sc_synth::map_control_buses_control(unsigned int slot_index, int control_bus_index, int count) { if (slot_index >= mNumControls) return; int slots_to_set = std::min(count, int(mNumControls - slot_index)); for (int i = 0; i != slots_to_set; ++i) map_control_bus_control(slot_index + i, control_bus_index + i); } void sc_synth::map_control_bus_audio(unsigned int slot_index, int audio_bus_index) { if (slot_index >= mNumControls) return; World* world = mNode.mWorld; if (audio_bus_index < 0) { mControlRates[slot_index] = 0; mMapControls[slot_index] = mControls + slot_index; } else if (uint(audio_bus_index) < world->mNumAudioBusChannels) { mControlRates[slot_index] = 2; // lets AudioControl know that we've been mapped into an audio bus, so we can // zero the output when it's freed later. mAudioBusOffsets[slot_index] = audio_bus_index; mMapControls[slot_index] = world->mAudioBus + (audio_bus_index * world->mBufLength); } } void sc_synth::map_control_buses_audio(unsigned int slot_index, int audio_bus_index, int count) { if (slot_index >= mNumControls) return; int slots_to_set = std::min(count, int(mNumControls - slot_index)); for (int i = 0; i != slots_to_set; ++i) map_control_bus_audio(slot_index + i, audio_bus_index + i); } void sc_synth::apply_unit_cmd(const char* unit_cmd, unsigned int unit_index, struct sc_msg_iter* args) { if (unit_index >= 0 && unit_index < unit_count) { if (!initialized) { // don't run the unit command if the unit constructor hasn't been called yet! // instead we put it on a queue and run it after the graph has been prepared. // NOTE: we can't just use rt_pool.malloc() because other synths might be // calling rt_alloc()/rt_free() concurrently in their calc function! // log_printf("queue unit command\n"); auto cmd = (sc_unit_cmd*)rt_alloc(nullptr, sizeof(sc_unit_cmd) + args->size); cmd->next = nullptr; cmd->size = args->size; memcpy(cmd->data, args->data, args->size); if (mPrivate) { // add to tail auto ptr = (sc_unit_cmd*)mPrivate; while (ptr->next) ptr = ptr->next; ptr->next = cmd; } else { mPrivate = cmd; } return; } Unit* unit = units[unit_index]; sc_ugen_def* def = reinterpret_cast<sc_ugen_def*>(unit->mUnitDef); def->run_unit_command(unit_cmd, unit, args); } else { log_printf("unit index %d out of range!\n", unit_index); } } void sc_synth::run(void) { perform(); } extern spin_lock log_guard; #if defined(__GNUC__) && !defined(__APPLE__) # define thread_local __thread #endif #ifdef thread_local static thread_local std::array<char, 262144> trace_scratchpad; #else static std::array<char, 262144> trace_scratchpad; #endif struct scratchpad_printer { scratchpad_printer(char* str): string(str), position(0) { clear(); } void printf(const char* fmt, ...) { va_list vargs; va_start(vargs, fmt); printf(fmt, vargs); va_end(vargs); } const char* data(void) const { return string; } bool shouldFlush(void) const { return position + 1024 > 32768; } void clear(void) { position = 0; string[0] = '\0'; // zero-terminated } private: void printf(const char* fmt, va_list vargs) { position += vsprintf(string + position, fmt, vargs); } char* string; int position; }; void sc_synth::run_traced(void) { trace = 0; #ifndef thread_local spin_lock::scoped_lock lock(log_guard); #endif scratchpad_printer printer(trace_scratchpad.data()); printer.printf("\nTRACE %d %s #units: %d\n", id(), this->definition_name(), calc_unit_count); for (size_t calc_unit_index = 0; calc_unit_index != calc_unit_count; ++calc_unit_index) { Unit* unit = calc_units[calc_unit_index]; sc_ugen_def* def = reinterpret_cast<sc_ugen_def*>(unit->mUnitDef); printer.printf(" unit %zd %s\n in ", calc_unit_index, def->name()); for (uint16_t j = 0; j != unit->mNumInputs; ++j) { printer.printf(" %g", unit->mInBuf[j][0]); if (printer.shouldFlush()) { #ifdef thread_local spin_lock::scoped_lock lock(log_guard); #endif log(printer.data()); printer.clear(); } } printer.printf("\n"); (unit->mCalcFunc)(unit, unit->mBufLength); printer.printf(" out"); for (int j = 0; j < unit->mNumOutputs; ++j) { printer.printf(" %g", unit->mOutBuf[j][0]); if (printer.shouldFlush()) { #ifdef thread_local spin_lock::scoped_lock lock(log_guard); #endif log(printer.data()); printer.clear(); } } printer.printf("\n"); } printer.printf("\n"); #ifdef thread_local spin_lock::scoped_lock lock(log_guard); #endif log(printer.data()); } } /* namespace nova */
13,625
C++
.cpp
326
35.40184
118
0.637361
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
29,928
sc_synthdef.cpp
supercollider_supercollider/server/supernova/sc/sc_synthdef.cpp
// supercollider-style synthdef // Copyright (C) 2008, 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. #include <iostream> #include <iterator> #include <fstream> #include <sstream> #include <boost/format.hpp> #include <boost/endian/arithmetic.hpp> #include "sc_synthdef.hpp" #include "sc_ugen_factory.hpp" #include "utilities/sized_array.hpp" #include "utilities/exists.hpp" namespace nova { typedef std::int16_t int16; typedef std::int32_t int32; typedef std::int8_t int8; using boost::endian::big_int16_t; using boost::endian::big_int32_t; using boost::endian::big_int8_t; using std::size_t; namespace { void verify_synthdef_buffer(const char* buffer, const char* buffer_end) { if (buffer >= buffer_end) throw std::runtime_error("corrupted synthdef"); } std::string read_pstring(const char*& buffer, const char* buffer_end) { verify_synthdef_buffer(buffer, buffer_end); char str[256 + 1]; char name_size = *buffer++; verify_synthdef_buffer(buffer + name_size, buffer_end); memcpy(str, buffer, name_size); str[int(name_size)] = 0; buffer += name_size; return std::string(str); } float read_float(const char*& buffer, const char* buffer_end) { verify_synthdef_buffer(buffer, buffer_end); big_int32_t data = *(big_int32_t*)buffer; buffer += 4; union { int32_t i; float f; } cast; cast.i = data; return cast.f; } int8_t read_int8(const char*& buffer, const char* buffer_end) { verify_synthdef_buffer(buffer, buffer_end); big_int8_t data = *(big_int8_t*)buffer; buffer += 1; return data; } int16_t read_int16(const char*& buffer, const char* buffer_end) { verify_synthdef_buffer(buffer, buffer_end); big_int16_t data = *(big_int16_t*)buffer; buffer += 2; return data; } int32_t read_int32(const char*& buffer, const char* buffer_end) { verify_synthdef_buffer(buffer, buffer_end); big_int32_t data = *(big_int32_t*)buffer; buffer += 4; return data; } int32_t read_int(const char*& buffer, const char* buffer_end, int size) { if (size == 32) return read_int32(buffer, buffer_end); if (size == 16) return read_int16(buffer, buffer_end); assert(false); return 0; } } /* namespace */ std::vector<sc_synthdef> read_synthdefs(const char* buffer, const char* buffer_end) { /* int32 header = */ read_int32(buffer, buffer_end); int32 version = read_int32(buffer, buffer_end); int16 definition_count = read_int16(buffer, buffer_end); std::vector<sc_synthdef> ret; for (int i = 0; i != definition_count; ++i) { try { #ifdef __clang__ // clang does not like to emplace_back sc_synthdef def(buffer, buffer_end, version); ret.push_back(def); #else ret.emplace_back(buffer, buffer_end, version); #endif } catch (std::exception const& e) { std::cout << "Exception when reading synthdef: " << e.what() << std::endl; } } return ret; } std::vector<sc_synthdef> read_synthdef_file(std::filesystem::path const& filename) { using namespace std; ifstream stream; stream.open(filename.string().c_str()); if (!stream.is_open()) { cout << "cannot open file " << filename << endl; return std::vector<sc_synthdef>(); } /* get length of file */ stream.seekg(0, ios::end); size_t length = stream.tellg(); stream.seekg(0, ios::beg); sized_array<char> buffer(length); stream.read(buffer.c_array(), length); stream.close(); return read_synthdefs(buffer.begin(), buffer.end()); } sc_synthdef::unit_spec_t::unit_spec_t(const char*& buffer, const char* buffer_end, int version) { const int short_int_size = (version == 1) ? 16 : 32; name = symbol(read_pstring(buffer, buffer_end)); rate = read_int8(buffer, buffer_end); int32_t input_count = read_int(buffer, buffer_end, short_int_size); int32_t output_count = read_int(buffer, buffer_end, short_int_size); special_index = read_int16(buffer, buffer_end); for (int i = 0; i != input_count; ++i) { int32_t source = read_int(buffer, buffer_end, short_int_size); int32_t index = read_int(buffer, buffer_end, short_int_size); input_spec spec(source, index); input_specs.push_back(spec); } for (int i = 0; i != output_count; ++i) { char rate = read_int8(buffer, buffer_end); output_specs.push_back(rate); } } sc_synthdef::sc_synthdef(const char*& buffer, const char* buffer_end, int version) { read_synthdef(buffer, buffer_end, version); } void sc_synthdef::read_synthdef(const char*& buffer, const char* buffer_end, int version) { using namespace std; const int short_int_size = (version == 1) ? 16 : 32; /* read name */ name_ = symbol(read_pstring(buffer, buffer_end)); /* read constants */ int32_t constant_count = read_int(buffer, buffer_end, short_int_size); constants.reserve(constant_count); for (int i = 0; i != constant_count; ++i) { float data = read_float(buffer, buffer_end); constants.push_back(data); } /* read parameters */ int32_t par_count = read_int(buffer, buffer_end, short_int_size); parameters.reserve(par_count); for (int i = 0; i != par_count; ++i) { float data = read_float(buffer, buffer_end); parameters.push_back(data); } /* read parameter names */ int32_t parameter_names_count = read_int(buffer, buffer_end, short_int_size); for (int i = 0; i != parameter_names_count; ++i) { symbol data = symbol(read_pstring(buffer, buffer_end)); int32_t index = read_int(buffer, buffer_end, short_int_size); parameter_map[data] = index; } int32_t ugen_count = read_int(buffer, buffer_end, short_int_size); graph.reserve(ugen_count); for (int i = 0; i != ugen_count; ++i) { unit_spec_t data(buffer, buffer_end, version); graph.push_back(data); } prepare(); } namespace { template <typename Alloc = std::allocator<size_t>> class buffer_allocator { std::vector<size_t, Alloc> buffers; /* index: buffer id, value: last reference */ public: buffer_allocator(size_t size_hint) { buffers.reserve(size_hint); } /** allocate buffer for current ugen * * reuse buffers, which are not used after the current ugen */ int32_t allocate_buffer(size_t current_ugen) { for (size_t i = 0; i != buffers.size(); ++i) { if (buffers[i] <= current_ugen) return i; } buffers.push_back(current_ugen); return buffers.size() - 1; } /** allocate buffer for current ugen * * reuse the buffers, which have been used before the current ugen */ int32_t allocate_buffer_noalias(size_t current_ugen) { for (size_t i = 0; i != buffers.size(); ++i) { if (buffers[i] < current_ugen) return i; } buffers.push_back(current_ugen); return buffers.size() - 1; } size_t buffer_count(void) const { return buffers.size(); } void set_last_reference(int32_t buffer_id, size_t ugen_index) { buffers[buffer_id] = ugen_index; } }; } /* namespace */ void sc_synthdef::prepare(void) { // FIXME: this currently has quadratic complexity, as buffer_allocator::allocate has linear complexity memory_requirement_ = 0; const size_t number_of_ugens = graph.size(); calc_unit_indices.reserve(number_of_ugens); // store the last references to each output buffer inside a std::map for faster lookup std::map<input_spec, size_t> last_buffer_references; for (auto it = graph.rbegin(); it != graph.rend(); ++it) { for (size_t i = 0; i != it->input_specs.size(); ++i) { input_spec const& in_spec = it->input_specs[i]; if (it->rate == calc_DemandRate) { size_t ugen_index = number_of_ugens; // audio-inputs to demand-rate ugens will never be reused! last_buffer_references[in_spec] = ugen_index; } else { if (!exists(last_buffer_references, in_spec)) { size_t ugen_index = std::distance(it, graph.rend()) - 1; last_buffer_references.insert(std::make_pair(in_spec, ugen_index)); } } } } buffer_allocator<> allocator(number_of_ugens / 8); for (size_t ugen_index = 0; ugen_index != number_of_ugens; ++ugen_index) { unit_spec_t& current_ugen_spec = graph[ugen_index]; /* calc units are stored in an additional vector */ switch (current_ugen_spec.rate) { case calc_BufRate: case calc_FullRate: calc_unit_indices.push_back(ugen_index); } memory_requirement_ += current_ugen_spec.memory_requirement(); current_ugen_spec.buffer_mapping.resize(current_ugen_spec.output_specs.size()); sc_ugen_def* ugen = sc_factory->find_ugen(current_ugen_spec.name); if (unlikely(ugen == nullptr)) { /* we cannot prepare the synthdef, if the ugens are not installed */ boost::format frmt("Cannot load synth %1%: Unit generator %2% not installed"); frmt % name_.c_str() % current_ugen_spec.name.c_str(); throw std::runtime_error(frmt.str()); } current_ugen_spec.prototype = ugen; const bool can_alias = !ugen->cant_alias(); memory_requirement_ += ugen->memory_requirement(); for (size_t output_index = 0; output_index != current_ugen_spec.output_specs.size(); ++output_index) { int32_t buffer_id; if (current_ugen_spec.output_specs[output_index] == 2) { /* find last reference to this buffer */ size_t last_ref = ugen_index; input_spec this_input_spec(ugen_index, output_index); if (exists(last_buffer_references, this_input_spec)) last_ref = last_buffer_references[this_input_spec]; buffer_id = can_alias ? allocator.allocate_buffer(ugen_index) : allocator.allocate_buffer_noalias(ugen_index); allocator.set_last_reference(buffer_id, last_ref); } else buffer_id = -1; current_ugen_spec.buffer_mapping[output_index] = buffer_id; } } memory_requirement_ += (graph.size() + calc_unit_indices.size() + 1) * sizeof(Unit*); // reserves space for units (one more to allor prefetching) // memory that is required to fill the sc_synth data structure // see SC_Graph.h for corresponding data structure // mControls, mControlRates, mAudioBusOffset, mMapControls const size_t param_alloc_size = parameter_count() * (sizeof(float) + sizeof(int) + sizeof(int32) + sizeof(float*)); // mWire const size_t constant_alloc_size = constants.size() * sizeof(Wire); const size_t ctor_alloc_size = param_alloc_size + constant_alloc_size; memory_requirement_ += ctor_alloc_size; buffer_count = uint32_t(allocator.buffer_count()); calc_unit_indices.shrink_to_fit(); } std::string sc_synthdef::dump(void) const { using namespace std; stringstream stream; stream << "name " << name().c_str() << endl; stream << "constant: " << endl; for (uint i = 0; i != constants.size(); ++i) stream << "\t" << constants[i] << endl; stream << "parameters: " << endl; for (uint i = 0; i != parameters.size(); ++i) stream << "\t" << parameters[i] << endl; stream << "parameter names: " << endl; for (const auto& elem : parameter_map) stream << "\t" << elem.first.c_str() << " " << elem.second << endl; stream << "ugens: " << endl; for (uint i = 0; i != graph.size(); ++i) { stream << "\t" << graph[i].name.c_str() << ": rate " << graph[i].rate << endl; stream << "\tinputs:" << endl; for (uint j = 0; j != graph[i].input_specs.size(); ++j) { stream << "\t\t" << graph[i].input_specs[j].source << " " << graph[i].input_specs[j].index << endl; } } return stream.str(); } } /* namespace nova */
12,953
C++
.cpp
306
35.960784
120
0.631633
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
29,929
hardware_topology.cpp
supercollider_supercollider/server/supernova/utilities/hardware_topology.cpp
// parse hardware topology // Copyright (C) 2022 Christof Ressi // // 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. #if defined(_WIN32) # include <windows.h> # include <malloc.h> #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) # include <sys/sysctl.h> # include <errno.h> #else /* Linux */ # include <unistd.h> # include <sys/sysinfo.h> #endif #include <boost/thread.hpp> #include <thread> #include <vector> #include <string> #include <iostream> #include <fstream> #ifndef DEBUG_HARDWARE_TOPOLOGY # define DEBUG_HARDWARE_TOPOLOGY 0 #endif namespace { struct cpu_info { int physical_id; int core_id; int sibling_id; int id; bool operator<(const cpu_info& other) const { return to_int() < other.to_int(); } bool operator>(const cpu_info& other) const { return to_int() > other.to_int(); } private: /* convert members to a single uint64_t to simplify comparison. * We try to keep siblings as far apart as possible, followed by physical * packages, so that cores of the same package are close to each other. */ uint64_t to_int() const { return ((uint64_t)sibling_id << 24) | ((uint64_t)physical_id << 16) | ((uint64_t)core_id); } }; std::vector<cpu_info> cpu_info_vec; int core_count = 0; int package_count = 0; void print_cpu_info(void) { std::cout << "hardware topology:\n" << "\tlogical processors: " << cpu_info_vec.size() << "\n" << "\tCPU cores: " << core_count << "\n" << "\tphysical packages: " << package_count << "\n" << "\t---\n"; for (auto& info : cpu_info_vec) { std::cout << "\t#" << info.id << " package: " << info.physical_id << ", core: " << info.core_id << ", sibling: " << info.sibling_id << "\n"; } } } /* namespace */ namespace nova { void parse_hardware_topology(void) { #if defined(_WIN32) /* Windows */ typedef BOOL(WINAPI * func_type)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); /* available since Windows XP SP3 */ auto fn = (func_type)GetProcAddress(GetModuleHandleA("kernel32"), "GetLogicalProcessorInformation"); if (!fn) { std::cout << "GetLogicalProcessorInformation() not supported" << std::endl; return; } /* call with size 0 to retrieve the actual size; * ERROR_INSUFFICIENT_BUFFER is expected. */ DWORD err, size = 0; fn(NULL, &size); if ((err = GetLastError()) != ERROR_INSUFFICIENT_BUFFER) { std::cout << "GetLogicalProcessorInformation() failed (" << err << ")" << std::endl; return; } auto info = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)alloca(size); if (fn(info, &size) == FALSE) { std::cout << "GetLogicalProcessorInformation() failed (" << GetLastError() << ")" << std::endl; return; } size_t n = (size_t)size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); /* loop over CPU cores */ for (size_t i = 0; i < n; ++i) { if (info[i].Relationship == RelationProcessorCore) { /* add all siblings to CPU list */ int siblings = 0; ULONG_PTR mask = info[i].ProcessorMask; for (int j = 0; mask; j++, mask >>= 1) { if (mask & 1) { cpu_info_vec.push_back({ 0, core_count, siblings, j }); siblings++; } } core_count++; } } /* loop again for physical packages */ for (size_t i = 0; i < n; ++i) { if (info[i].Relationship == RelationProcessorPackage) { ULONG_PTR mask = info[i].ProcessorMask; /* loop over all processors and find corresponding t_cpuinfo */ for (size_t j = 0; mask != 0; ++j, mask >>= 1) { if (mask & 1) { for (auto& cpu : cpu_info_vec) { if (cpu.id == j) cpu.physical_id = package_count; } } } package_count++; } } #elif defined(__linux__) /* Linux */ /* The file /proc/cpuinfo contains all logical CPUs where * each entry has a property "physical id" and "core id". */ std::ifstream fs("/proc/cpuinfo"); if (!fs) { std::cout << "could not open /proc/cpuinfo" << std::endl; return; } auto parse_line = [](const std::string& line, const char* key, int& value) { if (line.find(key) != std::string::npos) { auto pos = line.find(":"); if (pos != std::string::npos) { value = std::stoi(line.substr(pos + 1)); return true; } else { throw std::runtime_error("missing colon after key"); } } else { return false; } }; int physical_id = -1; int core_id = -1; try { for (std::string line; std::getline(fs, line);) { if (line.empty()) continue; /* search for "physical id" and "core id" */ if (!parse_line(line, "physical id", physical_id) && !parse_line(line, "core id", core_id)) { continue; } if (physical_id >= 0 && core_id >= 0) { int id = (int)cpu_info_vec.size(); /* get sibling number */ int sibling_id = 0; for (auto& cpu : cpu_info_vec) { if ((cpu.physical_id == physical_id) && (cpu.core_id == core_id)) { sibling_id++; } } if (sibling_id == 0) core_count++; /* check for new physical package */ if (std::find_if(cpu_info_vec.begin(), cpu_info_vec.end(), [&](auto& cpu) { return cpu.physical_id == physical_id; }) == cpu_info_vec.end()) { package_count++; } cpu_info_vec.push_back({ physical_id, core_id, sibling_id, id }); physical_id = core_id = -1; } } } catch (const std::exception& e) { std::cout << "could not parse /proc/cpuinfo: " << e.what() << std::endl; cpu_info_vec.clear(); core_count = 0; package_count = 0; return; } #else /* Apple, BSDs, etc. */ // std::cout << "parse_hardware_topology() not implemented" << std::endl; return; #endif /* parsing done */ #if DEBUG_HARDWARE_TOPOLOGY print_cpu_info(); /* print original list */ #endif /* sort the list so that we can simply pick * consecutive CPUs for effective thread pinning. */ std::sort(cpu_info_vec.begin(), cpu_info_vec.end()); #if DEBUG_HARDWARE_TOPOLOGY /* print the sorted list */ std::cout << "sorted CPU list:" << std::endl; for (auto& info : cpu_info_vec) { std::cout << "\t#" << info.id << " package: " << info.physical_id << ", core: " << info.core_id << ", sibling: " << info.sibling_id << "\n"; } std::cout << std::endl; #endif } int get_cpu_for_thread_index(int thread_index) { if (!cpu_info_vec.empty()) { return cpu_info_vec[thread_index % cpu_info_vec.size()].id; } else { return thread_index; } } } /* namespace nova */
8,065
C++
.cpp
210
30.452381
105
0.55486
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
29,930
node_graph.cpp
supercollider_supercollider/server/supernova/server/node_graph.cpp
// node graph, implementation // Copyright (C) 2008, 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. #include <fstream> #include "dependency_graph_generator.hpp" #include "dsp_thread_queue_node.hpp" #include "node_graph.hpp" #include "synth.hpp" #include "utilities/exists.hpp" #include "dsp_thread_queue/dsp_thread_queue.hpp" namespace nova { void node_graph::add_node(server_node* n) { node_position_constraint to_root = std::make_pair(&root_group_, head); add_node(n, to_root, [](server_node& node) {}); } void node_graph::add_node(server_node* n, node_position_constraint const& constraint) { add_node(n, constraint, [](server_node& node) {}); } node_graph::dsp_thread_queue_ptr node_graph::generate_dsp_queue(void) { dependency_graph_generator gen; node_graph::dsp_thread_queue* ret = gen(this); return dsp_thread_queue_ptr(ret); } void node_graph::synth_reassign_id(int32_t node_id) { node_set_type::iterator it = node_set.find(node_id, hash_node(), equal_node()); if (it == node_set.end()) throw std::runtime_error("node id not found"); server_node* node = &(*it); if (!node->is_synth()) return; boost::hash<int32_t> hasher; int32_t hidden_id = -std::abs(node_id); while (!node_id_available(hidden_id)) hidden_id = -std::abs(static_cast<int32_t>(hasher(node_id))); assert(hidden_id < 0); node_set.erase(*node); node->reset_id(hidden_id); node_set.insert(*node); } int32_t node_graph::generate_node_id(void) { int32_t new_id; do { for (;;) { new_id = -std::abs(static_cast<int32_t>(server_node::hash(generated_id))); if (likely(new_id != generated_id)) break; generated_id -= 1; } } while (!node_id_available(new_id)); generated_id = new_id; return generated_id; } abstract_group::~abstract_group(void) { while (!child_nodes.empty()) { server_node& node = child_nodes.front(); remove_child(&node); } } void abstract_group::pause(void) { for (server_node& child_node : child_nodes) child_node.pause(); } void abstract_group::resume(void) { for (server_node& child_node : child_nodes) child_node.resume(); } void abstract_group::add_child(server_node* node) { assert(!has_child(node)); child_nodes.push_front(*node); node->set_parent(this); } void abstract_group::replace_child(server_node* node, server_node* node_to_replace) { assert(!has_child(node)); assert(has_child(node_to_replace)); server_node_list::iterator position_of_old_element = server_node_list::s_iterator_to(*node_to_replace); child_nodes.insert(position_of_old_element, *node); node->set_parent(this); remove_child(node_to_replace); } bool abstract_group::has_child(const server_node* node) const { if (!node->server_node::parent_hook::is_linked()) return false; /* find node in container */ for (const auto& elem : child_nodes) { if (&elem == node) return true; } return false; } void abstract_group::remove_child(server_node* node) { assert(has_child(node)); node->server_node::parent_hook::unlink(); node->clear_parent(); } void abstract_group::set(slot_index_t slot_id, float val) { for (auto& elem : child_nodes) elem.set(slot_id, val); } void abstract_group::set(const char* slot_str, float val) { size_t hashed_str = string_hash(slot_str); for (auto& elem : child_nodes) elem.set(slot_str, hashed_str, val); } void abstract_group::set(const char* slot_str, std::size_t hashed_str, float val) { for (auto& elem : child_nodes) elem.set(slot_str, hashed_str, val); } void abstract_group::set_control_array(const char* slot_str, size_t count, float* val) { size_t hashed_str = string_hash(slot_str); set_control_array(slot_str, hashed_str, count, val); } void abstract_group::set_control_array(const char* slot_str, std::size_t hashed_str, size_t count, float* val) { for (auto& elem : child_nodes) elem.set_control_array(slot_str, hashed_str, count, val); } void abstract_group::set_control_array(slot_index_t slot_id, size_t count, float* val) { for (auto& elem : child_nodes) elem.set_control_array(slot_id, count, val); } void abstract_group::set_control_array_element(const char* slot_str, size_t index, float val) { size_t hashed_str = string_hash(slot_str); set_control_array_element(slot_str, hashed_str, index, val); } void abstract_group::set_control_array_element(const char* slot_str, std::size_t hashed_str, size_t index, float val) { for (auto& elem : child_nodes) elem.set_control_array_element(slot_str, hashed_str, index, val); } void abstract_group::set_control_array_element(slot_index_t slot_id, size_t index, float val) { for (auto& elem : child_nodes) elem.set_control_array_element(slot_id, index, val); } int parallel_group::tail_nodes(void) const { int ret = child_synth_count; for (const auto& elem : child_groups) ret += elem.tail_nodes(); return ret; } void group::add_child(server_node* node, node_position_constraint const& constraint) { assert(!has_child(node)); server_node* ref = constraint.first; node_position position = constraint.second; assert((position == after) || (position == before) || (position == insert)); server_node_list::const_iterator it = child_nodes.iterator_to(*ref); if (position == after) ++it; child_nodes.insert(it, *node); node->set_parent(this); } void parallel_group::add_child(server_node* node, node_position_constraint const& constraint) { abstract_group::add_child(node); /* later warn about this! */ } void group::add_child(server_node* node, node_position position) { assert(!has_child(node)); assert((position == head) || (position == tail)); if (position == head) child_nodes.push_front(*node); else child_nodes.push_back(*node); node->set_parent(this); } void parallel_group::add_child(server_node* node, node_position position) { abstract_group::add_child(node); /* later warn about this! */ } } /* namespace nova */
6,992
C++
.cpp
180
34.538889
119
0.677816
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
29,931
memory_pool.cpp
supercollider_supercollider/server/supernova/server/memory_pool.cpp
// real-time memory pool, implementation // 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. #include "memory_pool.hpp" namespace nova { simple_pool<false> rt_pool; } /* namespace nova */
931
C++
.cpp
21
43.238095
72
0.748899
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
29,932
main.cpp
supercollider_supercollider/server/supernova/server/main.cpp
// nova server // Copyright (C) 2008, 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. #include <csignal> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include "SC_Win32Utils.h" #include "SC_ServerBootDelayWarning.h" #include <filesystem> #include <boost/algorithm/string.hpp> #include "server.hpp" #include "server_args.hpp" #include "SC_Version.hpp" #include "SC_EventLoop.hpp" #include "../sc/sc_ugen_factory.hpp" #include "../sc/sc_synth_definition.hpp" #include "../utilities/utils.hpp" #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) # include <wordexp.h> # include <sys/resource.h> #endif #ifdef __APPLE__ # include <ApplicationServices/ApplicationServices.h> # include <SC_Apple.hpp> #endif #ifndef _WIN32 # include <unistd.h> // for _POSIX_MEMLOCK #endif #if (_POSIX_MEMLOCK - 0) >= 200112L # include <sys/resource.h> # include <sys/mman.h> #endif #include "SC_Filesystem.hpp" #ifndef _WIN32 const char pathSeparator[] = ":"; #else const char pathSeparator[] = ";"; #endif using namespace nova; using namespace std; using DirName = SC_Filesystem::DirName; namespace nova { void parse_hardware_topology(void); } namespace { /* signal handler */ void terminate(int i) { instance->terminate(); } void register_signal_handler(void) { void (*prev_fn)(int); prev_fn = ::signal(SIGINT, terminate); } #ifdef JACK_BACKEND void connect_jack_ports(void) { using namespace boost; using namespace boost::algorithm; const char* input_string = getenv("SC_JACK_DEFAULT_INPUTS"); if (input_string) { string input_port(input_string); if (input_port.find(",") == string::npos) instance->connect_all_inputs(input_port.c_str()); else { vector<string> portnames; boost::split(portnames, input_port, is_any_of(",")); for (size_t i = 0; i != portnames.size(); ++i) instance->connect_input(i, portnames[i].c_str()); } } const char* output_string = getenv("SC_JACK_DEFAULT_OUTPUTS"); if (output_string) { string output_port(output_string); if (output_port.find(",") == string::npos) instance->connect_all_outputs(output_port.c_str()); else { vector<string> portnames; boost::split(portnames, output_port, is_any_of(",")); for (size_t i = 0; i != portnames.size(); ++i) instance->connect_output(i, portnames[i].c_str()); } } } void get_jack_names(server_arguments const& args, string& server_name, string& client_name) { client_name = "supernova"; if (!args.hw_name.empty() && !args.hw_name[0].empty()) { vector<string> names; boost::split(names, args.hw_name[0], boost::algorithm::is_any_of(":")); if (names.size() == 1) { server_name = names[0]; } else if (names.size() == 2) { server_name = names[0]; client_name = names[1]; } else { cout << "Error: cannot parse hardware device name. Using defaults." << endl; } } } void start_audio_backend(server_arguments const& args) { string server_name, client_name; get_jack_names(args, server_name, client_name); instance->open_client(server_name, client_name, args.input_channels, args.output_channels, args.blocksize); instance->prepare_backend(); instance->activate_audio(); unsigned int real_sampling_rate = instance->get_samplerate(); if (args.samplerate != real_sampling_rate) { if (args.samplerate) { cout << "Samplerate mismatch between command line argument and jack" << endl; cout << "Forcing samplerate of " << real_sampling_rate << "Hz" << endl; } server_arguments::set_samplerate((uint32_t)real_sampling_rate); sc_factory->reset_sampling_rate(real_sampling_rate); } connect_jack_ports(); } #elif defined(PORTAUDIO_BACKEND) void start_audio_backend(server_arguments const& args) { int input_channels = args.input_channels; int output_channels = args.output_channels; std::string input_device, output_device; // if input_device/output_device are empty, default audio device will be chosen if (!args.hw_name.empty()) { if (args.hw_name.size() == 1) { input_device = output_device = args.hw_name[0]; } else { input_device = args.hw_name[0]; output_device = args.hw_name[1]; } } if (input_channels == 0) input_device.clear(); if (output_channels == 0) output_device.clear(); std::cout << "Requested audio devices:" << std::endl; if (input_channels) std::cout << " In: " << (input_device.empty() ? "(default)" : input_device) << std::endl; if (output_channels) std::cout << " Out: " << (output_device.empty() ? "(default)" : output_device) << std::endl; # ifdef __APPLE__ bool success = instance->open_stream(input_device, input_channels, output_device, output_channels, args.samplerate, args.blocksize, args.hardware_buffer_size, args.safety_clip_threshold); # else bool success = instance->open_stream(input_device, input_channels, output_device, output_channels, args.samplerate, args.blocksize, args.hardware_buffer_size, 0); # endif if (!success) { std::cout << "*** ERROR: could not open audio devices." << std::endl; exit(1); } unsigned int real_sampling_rate = instance->get_samplerate(); if (args.samplerate != real_sampling_rate) { server_arguments::set_samplerate((uint32_t)real_sampling_rate); sc_factory->reset_sampling_rate(real_sampling_rate); } instance->report_latency(); instance->prepare_backend(); instance->activate_audio(); std::cout << "Audio devices opened successfully" << std::endl; } #else void start_audio_backend(server_arguments const& args) {} #endif void set_plugin_paths(server_arguments const& args, nova::sc_ugen_factory* factory) { if (!args.ugen_paths.empty()) { for (path const& path1 : args.ugen_paths) { vector<std::string> directories; boost::split(directories, path1.string(), boost::is_any_of(pathSeparator)); for (string const& path : directories) { factory->load_plugin_folder(path); } } } else { #ifdef SC_PLUGIN_DIR factory->load_plugin_folder(SC_PLUGIN_DIR); #endif factory->load_plugin_folder(SC_Filesystem::instance().getDirectory(DirName::Resource) / SC_PLUGIN_DIR_NAME); factory->load_plugin_folder(SC_Filesystem::instance().getDirectory(DirName::SystemExtension)); factory->load_plugin_folder(SC_Filesystem::instance().getDirectory(DirName::UserExtension)); const char* env_plugin_path = getenv("SC_PLUGIN_PATH"); if (env_plugin_path) { vector<std::string> directories; boost::split(directories, env_plugin_path, boost::is_any_of(pathSeparator)); for (string const& path : directories) { factory->load_plugin_folder(path); } } } #ifndef NDEBUG cout << "Unit Generators initialized" << endl; #endif } void load_synthdef_folder(nova_server& server, path const& folder, bool verbose) { if (verbose) std::cout << "Loading synthdefs from path: " << folder.string() << std::endl; register_synthdefs(server, sc_read_synthdefs_dir(folder)); } void load_synthdefs(nova_server& server, server_arguments const& args) { using namespace std; #ifndef NDEBUG auto start_time = std::chrono::high_resolution_clock::now(); #endif if (args.load_synthdefs) { const char* env_synthdef_path = getenv("SC_SYNTHDEF_PATH"); vector<path> directories; if (env_synthdef_path) { boost::split(directories, env_synthdef_path, boost::is_any_of(pathSeparator)); } else { path synthdef_path = SC_Filesystem::instance().getDirectory(DirName::UserAppSupport); directories.push_back(synthdef_path / "synthdefs"); } for (path const& directory : directories) load_synthdef_folder(server, directory, args.verbosity > 0); } #ifndef NDEBUG auto end_time = std::chrono::high_resolution_clock::now(); cout << "SynthDefs loaded in " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count() << " ms" << endl; #endif } void drop_rt_scheduling() { bool success = nova::thread_set_priority(0); if (!success) cout << "Warning: cannot drop rt priority" << endl; } void enable_core_dumps(void) { #ifdef __LINUX__ rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY }; assert(setrlimit(RLIMIT_CORE, &core_limit) == 0); // enable core dumps for debug builds #endif } void lock_memory(server_arguments const& args) { #if (_POSIX_MEMLOCK - 0) >= 200112L if (args.memory_locking) { bool lock_memory = false; rlimit limit; int failure = getrlimit(RLIMIT_MEMLOCK, &limit); if (failure) printf("getrlimit failure\n"); else { if (limit.rlim_cur == RLIM_INFINITY and limit.rlim_max == RLIM_INFINITY) lock_memory = true; else printf("memory locking disabled due to resource limiting\n"); if (lock_memory) { if (mlockall(MCL_FUTURE) != -1) printf("memory locking enabled.\n"); } } } #endif } } /* namespace */ int supernova_main(int argc, char* argv[]) { drop_rt_scheduling(); // when being called from sclang, we inherit a low rt-scheduling priority. // but we don't want it! enable_core_dumps(); parse_hardware_topology(); server_arguments::initialize(argc, argv); server_arguments const& args = server_arguments::instance(); if (args.dump_version) { cout << "supernova " << SC_VersionString() << " (" << SC_BuildString() << ")" << endl; return 0; } EventLoop::setup(); #ifdef __APPLE__ ProcessSerialNumber psn; if (GetCurrentProcess(&psn) == noErr) { TransformProcessType(&psn, kProcessTransformToUIElementApplication); } SC::Apple::disableAppNap(); #endif rt_pool.init(args.rt_pool_size * 1024, args.memory_locking); lock_memory(args); cout << "Supernova booting" << endl; #ifndef NDEBUG cout << "compiled for debugging" << endl; #endif startServerBootDelayWarningTimer(); // FIXME should have more granular error handling try { server_shared_memory_creator::cleanup(args.port()); nova_server server(args); register_signal_handler(); set_plugin_paths(args, sc_factory.get()); load_synthdefs(server, args); stopServerBootDelayWarningTimer(); if (!args.non_rt) { try { start_audio_backend(args); cout << "Supernova ready" << endl; } catch (exception const& e) { cout << "\n*** ERROR: could not start audio backend: " << e.what() << endl; exit(1); } EventLoop::run([&server]() { server.run(); }); } else server.run_nonrt_synthesis(args); } catch (const std::exception& exc) { cout << "\n*** ERROR: in main(): " << exc.what() << endl; exit(1); } catch (...) { cout << "\n*** ERROR: unknown error in main()" << endl; exit(1); } return 0; } #ifdef _WIN32 int wmain(int argc, wchar_t** wargv) { // convert args to utf-8 std::vector<char*> argv; for (int i = 0; i < argc; i++) { auto argSize = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, nullptr, 0, nullptr, nullptr); argv.push_back(new char[argSize]); WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], argSize, nullptr, nullptr); } // set codepage to UTF-8 and remember the old codepage auto oldCodePage = GetConsoleOutputCP(); if (!SetConsoleOutputCP(65001)) cout << "WARNING: could not set codepage to UTF-8" << endl; // run main int result = supernova_main(argv.size(), argv.data()); // reset codepage from UTF-8 SetConsoleOutputCP(oldCodePage); // clear vector with converted args for (auto* arg : argv) delete[] arg; return result; } #else int main(int argc, char** argv) { return supernova_main(argc, argv); }; #endif
13,409
C++
.cpp
344
32.648256
119
0.633626
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
29,933
buffer_manager.cpp
supercollider_supercollider/server/supernova/server/buffer_manager.cpp
// nova server, buffer manager class, implementation // 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. #include "buffer_manager.hpp" #include "malloc_aligned.hpp" #include "utilities/sized_array.hpp" #include "../../common/SC_SndFileHelpers.hpp" namespace nova { void buffer_wrapper::allocate(size_t frames, uint channels) { if (data) free_aligned(data); data = calloc_aligned<sample_t>(frames * channels); frames_ = frames; channels_ = channels; } namespace { SndfileHandle open_file(const char* file, std::size_t start_frame) { auto sndfile = makeSndfileHandle(file); if (!sndfile) throw std::runtime_error(std::string("could not open file: ") + std::string(file)); long seek = sndfile.seek(start_frame, SEEK_SET); if (seek == -1) throw std::runtime_error(std::string("could not seek file: ") + std::string(file)); return sndfile; } } /* namespace */ void buffer_wrapper::read_file(const char* file, size_t start_frame, size_t frames) { free(); SndfileHandle sndfile = open_file(file, start_frame); sample_rate_ = sndfile.samplerate(); channels_ = sndfile.channels(); size_t end_frame = std::min(start_frame + frames, size_t(sndfile.frames())); size_t frame_count = end_frame - start_frame; data = malloc_aligned<sample_t>(frame_count * channels_); size_t read = sndfile.readf(data, frame_count); if (read != frame_count) throw std::runtime_error(std::string("could not read from file: ") + std::string(file)); } void buffer_wrapper::read_file_channels(const char* file, size_t start_frame, size_t frames, uint channel_count, uint* channels) { free(); SndfileHandle sndfile = open_file(file, start_frame); channels_ = channel_count; sample_rate_ = sndfile.samplerate(); for (uint c = 0; c != channel_count; ++c) { if (channels[c] >= uint(sndfile.channels())) throw std::runtime_error(std::string("requesting channel, that is not in file: ") + std::string(file)); } size_t end_frame = std::min(start_frame + frames, size_t(sndfile.frames())); size_t frame_count = end_frame - start_frame; data = malloc_aligned<sample_t>(frame_count * channels_); sized_array<sample_t> tmp_array(channels_); for (size_t i = 0; i != frame_count; ++i) { size_t read = sndfile.readf(tmp_array.c_array(), 1); if (read != 1) throw std::runtime_error(std::string("could not from read file: ") + std::string(file)); sample_t* data_frame = data + channel_count * i; for (uint c = 0; c != channel_count; ++c) data_frame[c] = tmp_array[channels[c]]; } } void buffer_wrapper::write_file(const char* file, const char* header_format, const char* sample_format, size_t start_frame, size_t frames) { int format = headerFormatFromString(header_format); if (format == 0) throw std::runtime_error("unknown header format requested"); int sample_format_tag = sampleFormatFromString(sample_format); if (sample_format_tag == 0) throw std::runtime_error("unknown sample format requested"); format |= sample_format_tag; auto sndfile = makeSndfileHandle(file, SFM_WRITE, format, channels_, sample_rate_); if (!sndfile) throw std::runtime_error(std::string("could not open file: ") + std::string(file)); sndfile.command(SFC_SET_CLIPPING, nullptr, SF_TRUE); size_t written = sndfile.writef(data, frames_); if (written != frames_) throw std::runtime_error(std::string("could not write file: ") + std::string(file)); } } /* namespace nova */
4,444
C++
.cpp
93
42.44086
115
0.669831
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
29,934
server.cpp
supercollider_supercollider/server/supernova/server/server.cpp
// nova server // 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. #include <stdexcept> #include "SC_Win32Utils.h" #include "nova-tt/thread_affinity.hpp" #include "nova-tt/thread_priority.hpp" #include "nova-tt/name_thread.hpp" #include "server.hpp" #include "sync_commands.hpp" #include "nrt_synthesis.hpp" #include "sc/sc_synth_definition.hpp" #include "sc/sc_ugen_factory.hpp" #ifdef __APPLE__ # include <AvailabilityMacros.h> # include <CoreAudio/HostTime.h> # include <CoreAudio/CoreAudioTypes.h> #endif #define DEBUG_THREAD_PINNING 0 namespace nova { class nova_server* instance = nullptr; nova_server::nova_server(server_arguments const& args): // FIXME: In case of multiple supernova instances on the same port (e.g. when running on // different interfaces), they can end up using the same shmem location. server_shared_memory_creator(args.port(), args.control_busses), scheduler<thread_init_functor>(args.threads, !args.non_rt, args.thread_pinning), buffer_manager(args.buffers), sc_osc_handler(args) { assert(instance == 0); instance = this; use_system_clock = (args.use_system_clock == 1); non_rt = args.non_rt; pin_threads = args.thread_pinning; smooth_samplerate = args.samplerate; if (!args.non_rt) { audio_backend::initialize(); io_interpreter.start_thread(); } sc_factory.reset(new sc_ugen_factory); sc_factory->initialize(args, server_shared_memory_creator::shm->get_control_busses()); /** first guess: needs to be updated, once the backend is started */ time_per_tick = time_tag::from_samples(args.blocksize, args.samplerate ? args.samplerate : 44100); if (!args.non_rt) start_receive_thread(); } void nova_server::prepare_backend(void) { /* register audio backend ports */ const int blocksize = get_audio_blocksize(); const int input_channels = get_input_count(); const int output_channels = get_output_count(); std::vector<sample*> inputs, outputs; for (int channel = 0; channel != input_channels; ++channel) inputs.push_back(sc_factory->world.mAudioBus + (blocksize * (output_channels + channel))); audio_backend::input_mapping(inputs.begin(), inputs.end()); for (int channel = 0; channel != output_channels; ++channel) outputs.push_back(sc_factory->world.mAudioBus + blocksize * channel); audio_backend::output_mapping(outputs.begin(), outputs.end()); time_per_tick = time_tag::from_samples(blocksize, get_samplerate()); } nova_server::~nova_server(void) { // we should delete but get chrashes at the moment on linux and macosx // delete sc_factory; #if defined(JACK_BACKEND) || defined(PORTAUDIO_BACKEND) deactivate_audio(); #endif group_free_all(static_cast<abstract_group*>(find_node(0))); // free the root group scheduler<thread_init_functor>::terminate(); io_interpreter.join_thread(); sc_factory.reset(); instance = nullptr; } void nova_server::perform_node_add(server_node* node, node_position_constraint const& constraints, bool update_dsp_queue) { node_graph::add_node(node, constraints, [&](server_node& node) { finalize_node(node); }); if (constraints.second == replace || update_dsp_queue) request_dsp_queue_update(); notification_node_started(node); } abstract_synth* nova_server::add_synth(const char* name, int id, node_position_constraint const& constraints) { abstract_synth* ret = synth_factory::create_instance(name, id); if (ret == nullptr) return nullptr; perform_node_add(ret, constraints, true); return ret; } group* nova_server::add_group(int id, node_position_constraint const& constraints) { group* g = new group(id); if (g == nullptr) return nullptr; perform_node_add(g, constraints, false); return g; } parallel_group* nova_server::add_parallel_group(int id, node_position_constraint const& constraints) { parallel_group* g = new parallel_group(id); if (g == nullptr) return nullptr; perform_node_add(g, constraints, false); return g; } void nova_server::set_node_slot(int node_id, slot_index_t slot, float value) { server_node* node = find_node(node_id); if (node) node->set(slot, value); } void nova_server::set_node_slot(int node_id, const char* slot, float value) { server_node* node = find_node(node_id); if (node) node->set(slot, value); } void nova_server::finalize_node(server_node& node) { if (node.is_synth()) { sc_synth& synth = static_cast<sc_synth&>(node); synth.finalize(); } notification_node_ended(&node); } void nova_server::free_node(server_node* node) { if (node->get_parent() == nullptr) return; // has already been freed by a different event node_graph::remove_node(node, [&](server_node& node) { finalize_node(node); }); request_dsp_queue_update(); } void nova_server::group_free_all(abstract_group* group) { std::vector<server_node*, rt_pool_allocator<server_node*>> nodes_to_free; group->apply_on_children([&](server_node& node) { nodes_to_free.push_back(&node); }); for (server_node* node : nodes_to_free) free_node(node); } void nova_server::group_free_deep(abstract_group* group) { std::vector<server_node*, rt_pool_allocator<server_node*>> nodes_to_free; group->apply_deep_on_children([&](server_node& node) { if (node.is_synth()) nodes_to_free.push_back(&node); }); for (server_node* node : nodes_to_free) free_node(node); } void nova_server::run_nonrt_synthesis(server_arguments const& args) { start_dsp_threads(); non_realtime_synthesis_engine engine(args); engine.run(); } void nova_server::rebuild_dsp_queue(void) { assert(dsp_queue_dirty); node_graph::dsp_thread_queue_ptr new_queue = node_graph::generate_dsp_queue(); scheduler<thread_init_functor>::reset_queue_sync(std::move(new_queue)); dsp_queue_dirty = false; } static void name_current_thread(int thread_index) { char buf[1024]; sprintf(buf, "DSP Thread %d", thread_index); #if defined(__linux__) name_thread(buf); #elif defined(__APPLE__) // TODO #elif defined(_WIN32) win32_name_thread(buf); #endif } static void set_daz_ftz(void) { #if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSE_VERSION /* denormal handling */ _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _mm_setcsr(_mm_getcsr() | 0x40); #endif } static bool set_realtime_priority(int thread_index) { bool success = false; #ifdef NOVA_TT_PRIORITY_PERIOD_COMPUTATION_CONSTRAINT double blocksize = server_arguments::instance().blocksize; double samplerate = server_arguments::instance().samplerate ? server_arguments::instance().samplerate : 44100; double ns_per_block = 1e9 / samplerate * blocksize; # ifdef __APPLE__ success = thread_set_priority_rt(0, AudioConvertNanosToHostTime(ns_per_block - 5000), AudioConvertNanosToHostTime(ns_per_block), true); # else success = thread_set_priority_rt(ns_per_block, ns_per_block - 2, ns_per_block - 1, false); # endif if (!success) std::cout << "Warning: initialize deadline scheduling" << std::endl; #endif if (!success) { #ifdef NOVA_TT_PRIORITY_RT # if defined(JACK_BACKEND) int priority = instance->realtime_priority(); /* This line has effectively been bypassed for years because * of a logic error further below. With the logic error fixed, * it would cause lower realtime priorities for DSP helper threads. * Let's keep the old behavior until we figure out what this code * is supposed to do in the first place... */ # if 0 if (priority >= 0) success = true; # endif # elif defined(_WIN32) int priority = thread_priority_interval_rt().second; # else int min, max; boost::tie(min, max) = thread_priority_interval_rt(); int priority = max - 3; priority = std::max(min, priority); # endif if (!success) success = thread_set_priority_rt(priority); #endif } if (!success) std::cout << "Warning: cannot raise thread priority" << std::endl; return success; } /* utilities/hardware_topology.cpp */ int get_cpu_for_thread_index(int thread_index); void thread_init_functor::operator()(int thread_index) { set_daz_ftz(); name_current_thread(thread_index); if (rt) set_realtime_priority(thread_index); if (pin) { auto cpu = get_cpu_for_thread_index(thread_index); #if DEBUG_THREAD_PINNING std::cout << "pin thread " << thread_index << " to CPU " << cpu << std::endl; #endif #ifdef _WIN32 // nova::thread_set_affinity() is not implemented for Windows bool result = win32_thread_set_affinity(cpu); #else bool result = thread_set_affinity(cpu); #endif if (!result) std::cout << "Warning: cannot set thread affinity of audio helper thread" << std::endl; } } void io_thread_init_functor::operator()() const { /* NB: on macOS we just keep the default thread priority */ #ifdef NOVA_TT_PRIORITY_RT int priority = thread_priority_interval_rt().first; thread_set_priority_rt(priority); #endif name_thread("Network Send"); } void synth_definition_deleter::dispose(synth_definition* ptr) { if (instance) /// todo: hack to fix test suite instance->add_system_callback(new delete_callback<synth_definition>(ptr)); else delete ptr; } void realtime_engine_functor::init_thread(void) { set_daz_ftz(); if (instance->pin_threads) { auto cpu = get_cpu_for_thread_index(0); #if DEBUG_THREAD_PINNING std::cout << "pin thread 0 to CPU " << cpu << std::endl; #endif #ifdef _WIN32 // nova::thread_set_affinity() is not implemented for Windows bool result = win32_thread_set_affinity(cpu); #else bool result = thread_set_affinity(cpu); #endif if (!result) std::cout << "Warning: cannot set thread affinity of main audio thread" << std::endl; } #ifdef JACK_BACKEND set_realtime_priority(0); #endif if (instance->use_system_clock) { double nows = (uint64)(OSCTime(std::chrono::system_clock::now())) * kOSCtoSecs; instance->mDLL.Reset(sc_factory->world.mSampleRate, sc_factory->world.mBufLength, SC_TIME_DLL_BW, nows); } name_current_thread(0); } void realtime_engine_functor::log_(const char* str) { // Silently drop messages; if instance is null it means something failed while constructing nova_server if (instance) instance->log_printf(str); } void realtime_engine_functor::log_printf_(const char* fmt, ...) { // Silently drop messages; if instance is null it means something failed while constructing nova_server if (instance == nullptr) return; va_list vargs; va_start(vargs, fmt); instance->log_printf(fmt, vargs); va_end(vargs); } } /* namespace nova */
11,867
C++
.cpp
300
34.853333
114
0.681383
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
29,935
server_args.cpp
supercollider_supercollider/server/supernova/server/server_args.cpp
// server arguments, implementation // 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. #include <iostream> #include <thread> #include <boost/lexical_cast.hpp> #include <boost/program_options.hpp> #include <boost/thread.hpp> #include "server_args.hpp" namespace nova { server_arguments::server_arguments(int argc, char* argv[]) { using namespace boost::program_options; using namespace std; /* prepare options */ options_description options("general options"); // only enable thread pinning by default on Linux #if defined(__linux__) bool def_thread_pinning = true; #else bool def_thread_pinning = false; #endif // clang-format off options.add_options() ("help,h", "show this help") ("udp-port,u", value<uint32_t>(&udp_port)->default_value(0), "udp port") ("tcp-port,t", value<uint32_t>(&tcp_port)->default_value(0), "tdp port") ("control-busses,c", value<uint32_t>(&control_busses)->default_value(16384), "number of control busses") ("audio-busses,a", value<uint32_t>(&audio_busses)->default_value(1024), "number of audio busses") ("block-size,z", value<uint32_t>(&blocksize)->default_value(64), "audio block size") ("hardware-buffer-size,Z", value<int32_t>(&hardware_buffer_size)->default_value(0), "hardware buffer size") ("use-system-clock,C", value<uint16_t>(&use_system_clock)->default_value(1), "type of clock sampleclock=0 systemclock=1") ("samplerate,S", value<uint32_t>(&samplerate)->default_value(0), "hardware sample rate") ("buffers,b", value<uint32_t>(&buffers)->default_value(1024), "number of sample buffers") ("max-nodes,n", value<uint32_t>(&max_nodes)->default_value(1024), "maximum number of server nodes") ("max-synthdefs,d", value<uint32_t>(&max_synthdefs)->default_value(1024), "maximum number of synthdefs") ("rt-memory,m", value<uint32_t>(&rt_pool_size)->default_value(8192), "size of real-time memory pool in kb") ("wires,w", value<uint32_t>(&wires)->default_value(64), "number of wire buffers") ("randomseeds,r", value<uint32_t>(&rng_count)->default_value(64), "number of random number generators") ("load-synthdefs,D", value<uint16_t>(&load_synthdefs)->default_value(1), "load synthdefs? (1 or 0)") ("rendezvous,R", value<uint16_t>()->default_value(1), "publish to Rendezvous? (1 or 0)") ("max-logins,l", value<uint32_t>()->default_value(64), "maximum number of named return addresses") ("password,p", value<string>(&server_password)->default_value(""), "When using TCP, the session password must be the first command sent.\n" "The default is no password.\n" "UDP ports never require passwords, so for security use TCP.") ("nrt,N", value<vector<string> >()->multitoken(), "nrt synthesis <cmd-filename> <input-filename> <output-filename> <sample-rate> <header-format> <sample-format>") ("memory-locking,L", "enable memory locking") ("version,v", "print the supercollider version and exit") ("hardware-device-name,H", value<vector<string> >()->multitoken(), "hardware device name") ("verbose,V", value<int16_t>(&verbosity)->default_value(0), "verbosity: 0 is normal behaviour\n-1 suppresses informational messages\n" "-2 suppresses informational and many error messages, as well as\n" "messages from Poll.") #ifdef _WIN32 ("ugen-search-path,U", value<vector<string> >(&ugen_paths), "A list of paths separated by `;`.\n" "If specified, standard paths are NOT searched for plugins.\nMay be specified several times.") #else ("ugen-search-path,U", value<vector<string> >(&ugen_paths), "A list of paths separated by `:`.\n" "If specified, standard paths are NOT searched for plugins.\nMay be specified several times.") #endif ("restricted-path,P", value<vector<string> >(&restrict_paths), "if specified, prevents file-accessing OSC commands from accessing files outside <restricted-path>") ("threads,T", value<uint16_t>(&threads)->default_value(boost::thread::physical_concurrency()), "number of audio threads") ("thread-pinning,y", value<bool>(&thread_pinning)->default_value(def_thread_pinning), "pin threads to CPU cores") ("socket-address,B", value<string>(&socket_address_str)->default_value("127.0.0.1"), "Bind the UDP or TCP socket to this address.\n" "Set to 0.0.0.0 to listen on all interfaces.") ; options_description audio_options("audio options"); audio_options.add_options() ("inchannels,i", value<uint16_t>(&input_channels)->default_value(8), "number of input channels") ("outchannels,o", value<uint16_t>(&output_channels)->default_value(8), "number of output channels") #ifdef __APPLE__ ("safety-clip-threshold,s", value<float>(&safety_clip_threshold)->default_value(1.26), "absolute amplitude value outputs will be clipped to.\n" "Set to <= 0 or inf to completely disable clipping.") #endif ; // clang-format on options_description cmdline_options; cmdline_options.add(options).add(audio_options); /* parse options */ boost::program_options::variables_map vm; try { store(command_line_parser(argc, argv).options(cmdline_options).run(), vm); } catch (error const& e) { cout << "Error when parsing command line arguments:" << endl << e.what() << endl << endl; std::exit(EXIT_FAILURE); }; notify(vm); dump_version = vm.count("version"); memory_locking = vm.count("memory-locking"); if (vm.count("help")) { cout << cmdline_options << endl; std::exit(EXIT_SUCCESS); } non_rt = vm.count("nrt"); if (non_rt) { std::vector<std::string> const& nrt_options = vm["nrt"].as<std::vector<std::string>>(); if (nrt_options.size() != 6) { cout << "Error when parsing command line:" << endl; std::exit(EXIT_FAILURE); } command_file = nrt_options[0]; input_file = nrt_options[1]; output_file = nrt_options[2]; samplerate = boost::lexical_cast<uint32_t>(nrt_options[3]); header_format = nrt_options[4]; sample_format = nrt_options[5]; } if (vm.count("hardware-device-name")) hw_name = vm["hardware-device-name"].as<std::vector<std::string>>(); try { socket_address = boost::asio::ip::make_address(vm["socket-address"].as<std::string>()); } catch (boost::exception const& e) { cout << "Cannot parse `" << vm["socket-address"].as<std::string>() << "` as a valid IP address. Exiting." << endl; std::exit(EXIT_FAILURE); }; } std::unique_ptr<server_arguments> server_arguments::instance_; } /* namespace nova */
8,027
C++
.cpp
133
50.654135
171
0.624317
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
29,936
TestUGens.cpp
supercollider_supercollider/server/plugins/TestUGens.cpp
/* * TestUGens.cpp * Plugins * Copyright (c) 2007 Scott Wilson <i@scottwilson.ca>. 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 * * Created by Scott Wilson on 22/06/2007. * Modified by James Harkins on 28/07/2007. * * */ #include "SC_PlugIn.h" #include <cstdio> ////////////////////////////////////////////////////////////////////////////////////////////////// static InterfaceTable* ft; struct CheckBadValues : public Unit { long sameCount; int prevclass; }; struct Sanitize : public Unit {}; // declare unit generator functions static void CheckBadValues_Ctor(CheckBadValues* unit); static void CheckBadValues_next(CheckBadValues* unit, int inNumSamples); static const char* CheckBadValues_fpclassString(int fpclass); inline int CheckBadValues_fold_fpclasses(int fpclass); static void Sanitize_Ctor(Sanitize* unit); static void Sanitize_next_aa(Sanitize* unit, int inNumSamples); static void Sanitize_next_ak(Sanitize* unit, int inNumSamples); static void Sanitize_next_kk(Sanitize* unit, int inNumSamples); ////////////////////////////////////////////////////////////////////////////////////////////////// void CheckBadValues_Ctor(CheckBadValues* unit) { unit->prevclass = FP_NORMAL; unit->sameCount = 0; SETCALC(CheckBadValues_next); CheckBadValues_next(unit, 1); } void CheckBadValues_next(CheckBadValues* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); float id = ZIN0(1); int post = (int)ZIN0(2); float samp; int classification; switch (post) { case 1: // post a line on every bad value LOOP1( inNumSamples, samp = ZXP(in); classification = std::fpclassify(samp); switch (classification) { case FP_INFINITE: Print("Infinite number found in Synth %d, ID: %d\n", unit->mParent->mNode.mID, (int)id); ZXP(out) = 2; break; case FP_NAN: Print("NaN found in Synth %d, ID: %d\n", unit->mParent->mNode.mID, (int)id); ZXP(out) = 1; break; case FP_SUBNORMAL: Print("Denormal found in Synth %d, ID: %d\n", unit->mParent->mNode.mID, (int)id); ZXP(out) = 3; break; default: ZXP(out) = 0; };); break; case 2: LOOP1( inNumSamples, samp = ZXP(in); classification = CheckBadValues_fold_fpclasses(std::fpclassify(samp)); if (classification != unit->prevclass) { if (unit->sameCount == 0) { Print("CheckBadValues: %s found in Synth %d, ID %d\n", CheckBadValues_fpclassString(classification), unit->mParent->mNode.mID, (int)id); } else { Print("CheckBadValues: %s found in Synth %d, ID %d (previous %d values were %s)\n", CheckBadValues_fpclassString(classification), unit->mParent->mNode.mID, (int)id, (int)unit->sameCount, CheckBadValues_fpclassString(unit->prevclass)); }; unit->sameCount = 0; }; switch (classification) { case FP_INFINITE: ZXP(out) = 2; break; case FP_NAN: ZXP(out) = 1; break; case FP_SUBNORMAL: ZXP(out) = 3; break; default: ZXP(out) = 0; }; unit->sameCount++; unit->prevclass = classification;); break; default: // no post LOOP1( inNumSamples, samp = ZXP(in); classification = std::fpclassify(samp); switch (classification) { case FP_INFINITE: ZXP(out) = 2; break; case FP_NAN: ZXP(out) = 1; break; case FP_SUBNORMAL: ZXP(out) = 3; break; default: ZXP(out) = 0; };); break; } } const char* CheckBadValues_fpclassString(int fpclass) { switch (fpclass) { case FP_NORMAL: return "normal"; case FP_NAN: return "NaN"; case FP_INFINITE: return "infinity"; case FP_ZERO: return "zero"; case FP_SUBNORMAL: return "denormal"; default: return "unknown"; } } inline int CheckBadValues_fold_fpclasses(int fpclass) { switch (fpclass) { case FP_ZERO: return FP_NORMAL; // a bit hacky. we mean "zero is fine too". default: return fpclass; } } /////////////////////////////////////////////////////////////////////////////////////// void Sanitize_Ctor(Sanitize* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Sanitize_next_aa); } else { SETCALC(Sanitize_next_ak); } } else { SETCALC(Sanitize_next_kk); } Sanitize_next_kk(unit, 1); } void Sanitize_next_aa(Sanitize* unit, int inNumSamples) { float* in = IN(0); float* replace = IN(1); float* out = OUT(0); float samp; for (int i = 0; i < inNumSamples; i++) { samp = in[i]; switch (std::fpclassify(samp)) { case FP_INFINITE: case FP_NAN: case FP_SUBNORMAL: out[i] = replace[i]; break; default: out[i] = samp; }; }; } void Sanitize_next_ak(Sanitize* unit, int inNumSamples) { float* in = IN(0); float replace = IN0(1); float* out = OUT(0); float samp; for (int i = 0; i < inNumSamples; i++) { samp = in[i]; switch (std::fpclassify(samp)) { case FP_INFINITE: case FP_NAN: case FP_SUBNORMAL: out[i] = replace; break; default: out[i] = samp; }; }; } void Sanitize_next_kk(Sanitize* unit, int inNumSamples) { float samp = IN0(0); float replace = IN0(1); switch (std::fpclassify(samp)) { case FP_INFINITE: case FP_NAN: case FP_SUBNORMAL: OUT0(0) = replace; break; default: OUT0(0) = samp; }; } //////////////////////////////////////////////////////////////////// // the load function is called by the host when the plug-in is loaded PluginLoad(Test) { ft = inTable; DefineSimpleUnit(CheckBadValues); DefineSimpleUnit(Sanitize); }
7,344
C++
.cpp
216
25.481481
120
0.540628
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
29,937
UnaryOpUGens.cpp
supercollider_supercollider/server/plugins/UnaryOpUGens.cpp
/* 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_PlugIn.h" #include <boost/utility/enable_if.hpp> #include <boost/align/is_aligned.hpp> #ifdef NOVA_SIMD # include "simd_unary_arithmetic.hpp" # include "simd_binary_arithmetic.hpp" # include "simd_ternary_arithmetic.hpp" # include "simd_math.hpp" # include "simd_memory.hpp" # include "softclip.hpp" # include "simd_unit_conversion.hpp" # include "function_attributes.h" using nova::wrap_argument; # define NOVA_WRAPPER(NAME, NOVANAME) \ FLATTEN void NAME##_nova(UnaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), inNumSamples); \ } # define NOVA_WRAPPER_CT_UNROLL(NAME, NOVANAME) \ FLATTEN void NAME##_nova(UnaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd(OUT(0), IN(0), inNumSamples); \ } \ \ FLATTEN void NAME##_nova_64(UnaryOpUGen* unit, int inNumSamples) { \ nova::NOVANAME##_vec_simd<64>(OUT(0), IN(0)); \ } struct sc_distort_functor { template <typename FloatType> inline FloatType operator()(FloatType arg) const { return sc_distort(arg); } template <typename FloatType> inline nova::vec<FloatType> operator()(nova::vec<FloatType> arg) const { nova::vec<FloatType> one(1.f); return arg * reciprocal(one + abs(arg)); } }; struct sc_scurve_functor { template <typename FloatType> inline FloatType operator()(FloatType arg) const { return sc_scurve(arg); } template <typename FloatType> inline nova::vec<FloatType> operator()(nova::vec<FloatType> arg) const { return perform(arg); } template <typename VecType> inline typename boost::disable_if_c<VecType::has_compare_bitmask, VecType>::type perform(VecType arg) const { typedef VecType vec; vec result; for (int i = 0; i != result.size; ++i) result.set(i, sc_scurve(arg.get(i))); return result; } template <typename VecType> inline typename boost::enable_if_c<VecType::has_compare_bitmask, VecType>::type perform(VecType arg) const { typedef VecType vec; vec one(1.f); vec zero(0.f); vec two(2.f); vec three(3.f); vec result = (arg * arg) * (three - (two * arg)); vec boundLow = mask_lt(arg, zero); vec boundHigh = mask_gt(arg, one); result = select(result, zero, boundLow); result = select(result, one, boundHigh); return result; } }; namespace nova { NOVA_SIMD_DEFINE_UNARY_WRAPPER(distort, sc_distort_functor) NOVA_SIMD_DEFINE_UNARY_WRAPPER(scurve, sc_scurve_functor) } #endif using namespace std; // for math functions static InterfaceTable* ft; ////////////////////////////////////////////////////////////////////////////////////////////////// /* special unary math operators */ enum { opNeg, opNot, opIsNil, opNotNil, opBitNot, opAbs, opAsFloat, opAsInteger, opCeil, opFloor, opFrac, opSign, opSquared, opCubed, opSqrt, opExp, opRecip, opMIDICPS, opCPSMIDI, opMIDIRatio, opRatioMIDI, opDbAmp, opAmpDb, opOctCPS, opCPSOct, opLog, opLog2, opLog10, opSin, opCos, opTan, opArcSin, opArcCos, opArcTan, opSinH, opCosH, opTanH, opRand, opRand2, opLinRand, opBiLinRand, opSum3Rand, opDistort, opSoftClip, opCoin, opDigitValue, opSilence, opThru, opRectWindow, opHanWindow, opWelchWindow, opTriWindow, opRamp, opSCurve, opNumUnarySelectors }; struct UnaryOpUGen : public Unit {}; typedef void (*UnaryOpFunc)(UnaryOpUGen* unit, int inNumSamples); extern "C" { void UnaryOpUGen_Ctor(UnaryOpUGen* unit); } bool ChooseOperatorFunc(UnaryOpUGen* unit); void UnaryOpUGen_Ctor(UnaryOpUGen* unit) { bool initialized = ChooseOperatorFunc(unit); if (!initialized) (unit->mCalcFunc)(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// #define DEFINE_UNARY_OP_FUNCS(name, function) \ extern "C" void name##_a(UnaryOpUGen* unit, int inNumSamples) { \ float* out = ZOUT(0); \ float* a = ZIN(0); \ \ LOOP1(inNumSamples, ZXP(out) = function(ZXP(a));); \ } \ \ extern "C" void name##_1(UnaryOpUGen* unit, int inNumSamples) { ZOUT0(0) = function(ZIN0(0)); } \ \ extern "C" void name##_d(UnaryOpUGen* unit, int inNumSamples) { \ if (inNumSamples) { \ float x = DEMANDINPUT_A(0, inNumSamples); \ OUT0(0) = sc_isnan(x) ? NAN : function(x); \ } else { \ RESETINPUT(0); \ } \ } template <typename F> inline F sc_invert(F x) { return -x; } DEFINE_UNARY_OP_FUNCS(invert, sc_invert) #ifdef NOVA_SIMD FLATTEN void invert_nova(UnaryOpUGen* unit, int inNumSamples) { nova::minus_vec_simd(OUT(0), 0.f, IN(0), inNumSamples); } FLATTEN void invert_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::minus_vec_simd<64>(OUT(0), 0.f, IN(0)); } #endif template <typename F> inline F sc_not(F x) { return x > 0.f ? 0.f : 1.f; } DEFINE_UNARY_OP_FUNCS(not, sc_not) DEFINE_UNARY_OP_FUNCS(bitNot, sc_bitNot) void zero_a(UnaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); ZClear(inNumSamples, out); } void thru_a(UnaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); ZCopy(inNumSamples, out, a); } DEFINE_UNARY_OP_FUNCS(abs, std::abs) #ifdef NOVA_SIMD FLATTEN void zero_nova(UnaryOpUGen* unit, int inNumSamples) { nova::zerovec_simd(OUT(0), inNumSamples); } FLATTEN void zero_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::zerovec_simd<64>(OUT(0)); } FLATTEN void thru_nova(UnaryOpUGen* unit, int inNumSamples) { nova::copyvec_simd(OUT(0), IN(0), inNumSamples); } FLATTEN void thru_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::copyvec_simd<64>(OUT(0), IN(0)); } FLATTEN void abs_nova(UnaryOpUGen* unit, int inNumSamples) { nova::abs_vec_simd(OUT(0), IN(0), inNumSamples); } FLATTEN void abs_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::abs_vec_simd<64>(OUT(0), IN(0)); } #endif DEFINE_UNARY_OP_FUNCS(recip, sc_reciprocal) #ifdef NOVA_SIMD FLATTEN void recip_nova(UnaryOpUGen* unit, int inNumSamples) { nova::reciprocal_vec_simd(OUT(0), IN(0), inNumSamples); } FLATTEN void recip_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::reciprocal_vec_simd<64>(OUT(0), IN(0)); } #endif DEFINE_UNARY_OP_FUNCS(floor, floor) DEFINE_UNARY_OP_FUNCS(ceil, ceil) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(floor, floor) NOVA_WRAPPER_CT_UNROLL(ceil, ceil) #endif DEFINE_UNARY_OP_FUNCS(sin, sin) DEFINE_UNARY_OP_FUNCS(cos, cos) DEFINE_UNARY_OP_FUNCS(tan, tan) DEFINE_UNARY_OP_FUNCS(asin, asin) DEFINE_UNARY_OP_FUNCS(acos, acos) DEFINE_UNARY_OP_FUNCS(atan, atan) DEFINE_UNARY_OP_FUNCS(sinh, sinh) DEFINE_UNARY_OP_FUNCS(cosh, cosh) DEFINE_UNARY_OP_FUNCS(tanh, tanh) #ifdef NOVA_SIMD NOVA_WRAPPER(sin, sin) NOVA_WRAPPER(cos, cos) NOVA_WRAPPER(tan, tan) NOVA_WRAPPER(asin, asin) NOVA_WRAPPER(acos, acos) NOVA_WRAPPER(atan, atan) NOVA_WRAPPER(tanh, tanh) #endif DEFINE_UNARY_OP_FUNCS(log, std::log) DEFINE_UNARY_OP_FUNCS(log2, sc_log2) DEFINE_UNARY_OP_FUNCS(log10, sc_log10) DEFINE_UNARY_OP_FUNCS(exp, exp) #ifdef NOVA_SIMD NOVA_WRAPPER(log, log) NOVA_WRAPPER(log2, log2) NOVA_WRAPPER(log10, log10) NOVA_WRAPPER(exp, exp) #endif DEFINE_UNARY_OP_FUNCS(sqrt, sc_sqrt) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(sqrt, signed_sqrt) #endif DEFINE_UNARY_OP_FUNCS(ampdb, sc_ampdb) DEFINE_UNARY_OP_FUNCS(dbamp, sc_dbamp) DEFINE_UNARY_OP_FUNCS(midicps, sc_midicps) DEFINE_UNARY_OP_FUNCS(cpsmidi, sc_cpsmidi) DEFINE_UNARY_OP_FUNCS(midiratio, sc_midiratio) DEFINE_UNARY_OP_FUNCS(ratiomidi, sc_ratiomidi) DEFINE_UNARY_OP_FUNCS(cpsoct, sc_cpsoct) DEFINE_UNARY_OP_FUNCS(octcps, sc_octcps) #ifdef NOVA_SIMD NOVA_WRAPPER(ampdb, amp2db) NOVA_WRAPPER(dbamp, db2amp) NOVA_WRAPPER(midicps, midi2freq) NOVA_WRAPPER(cpsmidi, freq2midi) NOVA_WRAPPER(midiratio, midi2ratio) NOVA_WRAPPER(ratiomidi, ratio2midi) NOVA_WRAPPER(cpsoct, freq2oct) NOVA_WRAPPER(octcps, oct2freq) #endif DEFINE_UNARY_OP_FUNCS(frac, sc_frac) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(frac, frac) #endif DEFINE_UNARY_OP_FUNCS(squared, sc_squared) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(squared, square) #endif DEFINE_UNARY_OP_FUNCS(cubed, sc_cubed) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(cubed, cube) #endif DEFINE_UNARY_OP_FUNCS(sign, sc_sign) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(sign, sgn) #endif DEFINE_UNARY_OP_FUNCS(distort, sc_distort) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(distort, distort) #endif DEFINE_UNARY_OP_FUNCS(distortneg, sc_distortneg) DEFINE_UNARY_OP_FUNCS(softclip, sc_softclip) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(softclip, softclip) #endif DEFINE_UNARY_OP_FUNCS(rectwindow, sc_rectwindow) DEFINE_UNARY_OP_FUNCS(hanwindow, sc_hanwindow) DEFINE_UNARY_OP_FUNCS(welwindow, sc_welwindow) DEFINE_UNARY_OP_FUNCS(triwindow, sc_triwindow) DEFINE_UNARY_OP_FUNCS(scurve, sc_scurve) #ifdef NOVA_SIMD NOVA_WRAPPER_CT_UNROLL(scurve, scurve) #endif DEFINE_UNARY_OP_FUNCS(ramp, sc_ramp) #ifdef NOVA_SIMD FLATTEN void ramp_nova(UnaryOpUGen* unit, int inNumSamples) { nova::clip_vec_simd(OUT(0), wrap_argument(IN(0)), wrap_argument(0.f), wrap_argument(1.f), inNumSamples); } FLATTEN void ramp_nova_64(UnaryOpUGen* unit, int inNumSamples) { nova::clip_vec_simd<64>(OUT(0), wrap_argument(IN(0)), wrap_argument(0.f), wrap_argument(1.f)); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// void zero_d(UnaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); OUT0(0) = sc_isnan(x) ? NAN : 0.f; } else { RESETINPUT(0); } } void thru_d(UnaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); OUT0(0) = sc_isnan(x) ? NAN : (x); } else { RESETINPUT(0); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// #define DEFINE_UNARY_OP_RANDOM_FUNCS(name, function) \ extern "C" void name##_a(UnaryOpUGen* unit, int inNumSamples) { \ float* out = ZOUT(0); \ float* a = ZIN(0); \ RGen& rgen = *unit->mParent->mRGen; \ LOOP1(inNumSamples, ZXP(out) = rgen.function() * ZXP(a);); \ } \ \ extern "C" void name##_1(UnaryOpUGen* unit, int inNumSamples) { \ RGen& rgen = *unit->mParent->mRGen; \ ZOUT0(0) = rgen.function() * ZIN0(0); \ } \ \ extern "C" void name##_d(UnaryOpUGen* unit, int inNumSamples) { \ if (inNumSamples) { \ float x = DEMANDINPUT_A(0, inNumSamples); \ RGen& rgen = *unit->mParent->mRGen; \ OUT0(0) = sc_isnan(x) ? NAN : (rgen.function() * x); \ } else { \ RESETINPUT(0); \ } \ } DEFINE_UNARY_OP_RANDOM_FUNCS(rand, frand); DEFINE_UNARY_OP_RANDOM_FUNCS(rand2, frand2); DEFINE_UNARY_OP_RANDOM_FUNCS(linrand, flinrand); DEFINE_UNARY_OP_RANDOM_FUNCS(bilinrand, fbilinrand); DEFINE_UNARY_OP_RANDOM_FUNCS(sum3rand, fsum3rand); void coin_a(UnaryOpUGen* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); RGen& rgen = *unit->mParent->mRGen; LOOP1(inNumSamples, ZXP(out) = (rgen.frand() < ZXP(a)) ? 1.f : 0.f;); } void coin_1(UnaryOpUGen* unit, int inNumSamples) { RGen& rgen = *unit->mParent->mRGen; float x = ZIN0(0); ZOUT0(0) = (rgen.frand() < x) ? 1.f : 0.f; } void coin_d(UnaryOpUGen* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); RGen& rgen = *unit->mParent->mRGen; float val = (rgen.frand() < x) ? 1.f : 0.f; OUT0(0) = sc_isnan(x) ? NAN : val; } else { RESETINPUT(0); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// static UnaryOpFunc ChooseNormalFunc(UnaryOpUGen* unit) { void (*func)(UnaryOpUGen * unit, int inNumSamples); switch (unit->mSpecialIndex) { case opSilence: func = &zero_a; break; case opThru: func = &thru_a; break; case opNeg: func = &invert_a; break; case opNot: func = &not_a; break; case opBitNot: func = &bitNot_a; break; case opAbs: func = &abs_a; break; case opCeil: func = &ceil_a; break; case opFloor: func = &floor_a; break; case opFrac: func = &frac_a; break; case opSign: func = &sign_a; break; case opSquared: func = &squared_a; break; case opCubed: func = &cubed_a; break; case opSqrt: func = &sqrt_a; break; case opExp: func = &exp_a; break; case opRecip: func = &recip_a; break; case opMIDICPS: func = &midicps_a; break; case opCPSMIDI: func = &cpsmidi_a; break; case opMIDIRatio: func = &midiratio_a; break; case opRatioMIDI: func = &ratiomidi_a; break; case opDbAmp: func = &dbamp_a; break; case opAmpDb: func = &ampdb_a; break; case opOctCPS: func = &octcps_a; break; case opCPSOct: func = &cpsoct_a; break; case opLog: func = &log_a; break; case opLog2: func = &log2_a; break; case opLog10: func = &log10_a; break; case opSin: func = &sin_a; break; case opCos: func = &cos_a; break; case opTan: func = &tan_a; break; case opArcSin: func = &asin_a; break; case opArcCos: func = &acos_a; break; case opArcTan: func = &atan_a; break; case opSinH: func = &sinh_a; break; case opCosH: func = &cosh_a; break; case opTanH: func = &tanh_a; break; case opRand: func = &rand_a; break; case opRand2: func = &rand2_a; break; case opLinRand: func = &linrand_a; break; case opBiLinRand: func = &bilinrand_a; break; case opSum3Rand: func = &sum3rand_a; break; case opCoin: func = &coin_a; break; case opDistort: func = &distort_a; break; case opSoftClip: func = &softclip_a; break; case opRectWindow: func = &rectwindow_a; break; case opHanWindow: func = &hanwindow_a; break; case opWelchWindow: func = &welwindow_a; break; case opTriWindow: func = &triwindow_a; break; case opSCurve: func = &scurve_a; break; case opRamp: func = &ramp_a; break; default: func = &thru_a; break; } return func; } static UnaryOpFunc ChooseOneFunc(UnaryOpUGen* unit) { void (*func)(UnaryOpUGen * unit, int inNumSamples); switch (unit->mSpecialIndex) { case opSilence: func = &zero_a; break; case opThru: func = &thru_a; break; case opNeg: func = &invert_1; break; case opNot: func = &not_1; break; case opBitNot: func = &bitNot_1; break; case opAbs: func = &abs_1; break; case opCeil: func = &ceil_1; break; case opFloor: func = &floor_1; break; case opFrac: func = &frac_1; break; case opSign: func = &sign_1; break; case opSquared: func = &squared_1; break; case opCubed: func = &cubed_1; break; case opSqrt: func = &sqrt_1; break; case opExp: func = &exp_1; break; case opRecip: func = &recip_1; break; case opMIDICPS: func = &midicps_1; break; case opCPSMIDI: func = &cpsmidi_1; break; case opMIDIRatio: func = &midiratio_1; break; case opRatioMIDI: func = &ratiomidi_1; break; case opDbAmp: func = &dbamp_1; break; case opAmpDb: func = &ampdb_1; break; case opOctCPS: func = &octcps_1; break; case opCPSOct: func = &cpsoct_1; break; case opLog: func = &log_1; break; case opLog2: func = &log2_1; break; case opLog10: func = &log10_1; break; case opSin: func = &sin_1; break; case opCos: func = &cos_1; break; case opTan: func = &tan_1; break; case opArcSin: func = &asin_1; break; case opArcCos: func = &acos_1; break; case opArcTan: func = &atan_1; break; case opSinH: func = &sinh_1; break; case opCosH: func = &cosh_1; break; case opTanH: func = &tanh_1; break; case opRand: func = &rand_1; break; case opRand2: func = &rand2_1; break; case opLinRand: func = &linrand_1; break; case opBiLinRand: func = &bilinrand_1; break; case opSum3Rand: func = &sum3rand_1; break; case opCoin: func = &coin_1; break; case opDistort: func = &distort_1; break; case opSoftClip: func = &softclip_1; break; case opRectWindow: func = &rectwindow_1; break; case opHanWindow: func = &hanwindow_1; break; case opWelchWindow: func = &welwindow_1; break; case opTriWindow: func = &triwindow_1; break; case opSCurve: func = &scurve_1; break; case opRamp: func = &ramp_1; break; default: func = &thru_a; break; } return func; } static UnaryOpFunc ChooseDemandFunc(UnaryOpUGen* unit) { void (*func)(UnaryOpUGen * unit, int inNumSamples); switch (unit->mSpecialIndex) { case opSilence: func = &zero_d; break; case opThru: func = &thru_d; break; case opNeg: func = &invert_d; break; case opNot: func = &not_d; break; case opBitNot: func = &bitNot_d; break; case opAbs: func = &abs_d; break; case opCeil: func = &ceil_d; break; case opFloor: func = &floor_d; break; case opFrac: func = &frac_d; break; case opSign: func = &sign_d; break; case opSquared: func = &squared_d; break; case opCubed: func = &cubed_d; break; case opSqrt: func = &sqrt_d; break; case opExp: func = &exp_d; break; case opRecip: func = &recip_d; break; case opMIDICPS: func = &midicps_d; break; case opCPSMIDI: func = &cpsmidi_d; break; case opMIDIRatio: func = &midiratio_d; break; case opRatioMIDI: func = &ratiomidi_d; break; case opDbAmp: func = &dbamp_d; break; case opAmpDb: func = &ampdb_d; break; case opOctCPS: func = &octcps_d; break; case opCPSOct: func = &cpsoct_d; break; case opLog: func = &log_d; break; case opLog2: func = &log2_d; break; case opLog10: func = &log10_d; break; case opSin: func = &sin_d; break; case opCos: func = &cos_d; break; case opTan: func = &tan_d; break; case opArcSin: func = &asin_d; break; case opArcCos: func = &acos_d; break; case opArcTan: func = &atan_d; break; case opSinH: func = &sinh_d; break; case opCosH: func = &cosh_d; break; case opTanH: func = &tanh_d; break; case opRand: func = &rand_d; break; case opRand2: func = &rand2_d; break; case opLinRand: func = &linrand_d; break; case opBiLinRand: func = &bilinrand_d; break; case opSum3Rand: func = &sum3rand_d; break; case opCoin: func = &coin_d; break; case opDistort: func = &distort_d; break; case opSoftClip: func = &softclip_d; break; case opRectWindow: func = &rectwindow_d; break; case opHanWindow: func = &hanwindow_d; break; case opWelchWindow: func = &welwindow_d; break; case opTriWindow: func = &triwindow_d; break; case opSCurve: func = &scurve_d; break; case opRamp: func = &ramp_d; break; default: func = &thru_d; break; } return func; } #ifdef NOVA_SIMD static UnaryOpFunc ChooseNovaSimdFunc(UnaryOpUGen* unit) { void (*func)(UnaryOpUGen * unit, int inNumSamples); if (BUFLENGTH == 64) { switch (unit->mSpecialIndex) { case opSilence: return &zero_nova_64; case opThru: func = &thru_nova; break; case opNeg: return &invert_nova_64; case opNot: func = &not_a; break; case opBitNot: func = &bitNot_a; break; case opAbs: return &abs_nova_64; case opCeil: func = &ceil_nova_64; break; case opFloor: func = &floor_nova_64; break; case opFrac: func = &frac_nova_64; break; case opSign: return &sign_nova_64; case opSquared: return &squared_nova_64; case opCubed: return &cubed_nova_64; case opSqrt: # ifdef __ARM_NEON // remove this once nova-simd implementation is fixed func = &sqrt_a; # else func = &sqrt_nova_64; # endif break; case opExp: func = &exp_nova; break; case opRecip: # ifdef __ARM_NEON // remove this once nova-simd implementation is fixed return &recip_a; # else return &recip_nova_64; # endif case opMIDICPS: func = &midicps_nova; break; case opCPSMIDI: func = &cpsmidi_nova; break; case opMIDIRatio: func = &midiratio_nova; break; case opRatioMIDI: func = &ratiomidi_nova; break; case opDbAmp: func = &dbamp_nova; break; case opAmpDb: func = &ampdb_nova; break; case opOctCPS: func = &octcps_nova; break; case opCPSOct: func = &cpsoct_nova; break; case opLog: func = &log_nova; break; case opLog2: func = &log2_nova; break; case opLog10: func = &log10_nova; break; case opSin: func = &sin_nova; break; case opCos: func = &cos_nova; break; case opTan: func = &tan_nova; break; case opArcSin: func = &asin_nova; break; case opArcCos: func = &acos_nova; break; case opArcTan: func = &atan_nova; break; case opSinH: func = &sinh_a; break; case opCosH: func = &cosh_a; break; case opTanH: func = &tanh_nova; break; case opRand: func = &rand_a; break; case opRand2: func = &rand2_a; break; case opLinRand: func = &linrand_a; break; case opBiLinRand: func = &bilinrand_a; break; case opSum3Rand: func = &sum3rand_a; break; case opCoin: func = &coin_a; break; case opDistort: func = &distort_nova_64; break; case opSoftClip: func = &softclip_nova_64; break; case opRectWindow: func = &rectwindow_a; break; case opHanWindow: func = &hanwindow_a; break; case opWelchWindow: func = &welwindow_a; break; case opTriWindow: func = &triwindow_a; break; case opSCurve: func = &scurve_nova_64; break; case opRamp: return &ramp_nova_64; default: return &thru_nova_64; } return func; } switch (unit->mSpecialIndex) { case opSilence: func = &zero_nova; break; case opThru: func = &thru_nova; break; case opNeg: func = &invert_nova; break; case opNot: func = &not_a; break; case opBitNot: func = &bitNot_a; break; case opAbs: func = &abs_nova; break; case opCeil: func = &ceil_nova; break; case opFloor: func = &floor_nova; break; case opFrac: func = &frac_nova; break; case opSign: func = &sign_nova; break; case opSquared: func = &squared_nova; break; case opCubed: func = &cubed_nova; break; case opSqrt: # ifdef __ARM_NEON // remove this once nova-simd implementation is fixed func = &sqrt_a; # else func = &sqrt_nova; # endif break; case opExp: func = &exp_nova; break; case opRecip: # ifdef __ARM_NEON // remove this once nova-simd implementation is fixed func = &recip_a; # else func = &recip_nova; # endif break; case opMIDICPS: func = &midicps_nova; break; case opCPSMIDI: func = &cpsmidi_nova; break; case opMIDIRatio: func = &midiratio_nova; break; case opRatioMIDI: func = &ratiomidi_nova; break; case opDbAmp: func = &dbamp_nova; break; case opAmpDb: func = &ampdb_nova; break; case opOctCPS: func = &octcps_nova; break; case opCPSOct: func = &cpsoct_nova; break; case opLog: func = &log_nova; break; case opLog2: func = &log2_nova; break; case opLog10: func = &log10_nova; break; case opSin: func = &sin_nova; break; case opCos: func = &cos_nova; break; case opTan: func = &tan_nova; break; case opArcSin: func = &asin_nova; break; case opArcCos: func = &acos_nova; break; case opArcTan: func = &atan_nova; break; case opSinH: func = &sinh_a; break; case opCosH: func = &cosh_a; break; case opTanH: func = &tanh_nova; break; case opRand: func = &rand_a; break; case opRand2: func = &rand2_a; break; case opLinRand: func = &linrand_a; break; case opBiLinRand: func = &bilinrand_a; break; case opSum3Rand: func = &sum3rand_a; break; case opCoin: func = &coin_a; break; case opDistort: func = &distort_nova; break; case opSoftClip: func = &softclip_nova; break; case opRectWindow: func = &rectwindow_a; break; case opHanWindow: func = &hanwindow_a; break; case opWelchWindow: func = &welwindow_a; break; case opTriWindow: func = &triwindow_a; break; case opSCurve: func = &scurve_nova; break; case opRamp: func = &ramp_nova; break; default: func = &thru_nova; break; } return func; } #endif bool ChooseOperatorFunc(UnaryOpUGen* unit) { // Print("->ChooseOperatorFunc %d\n", unit->mSpecialIndex); UnaryOpFunc func; bool ret = false; if (unit->mCalcRate == calc_DemandRate) { func = ChooseDemandFunc(unit); } else if (BUFLENGTH == 1) { func = ChooseOneFunc(unit); #if defined(NOVA_SIMD) } else if (boost::alignment::is_aligned(BUFLENGTH, 16)) { /* select normal function for initialization */ func = ChooseNormalFunc(unit); func(unit, 1); /* select simd function */ func = ChooseNovaSimdFunc(unit); ret = true; #endif } else { func = ChooseNormalFunc(unit); } unit->mCalcFunc = (UnitCalcFunc)func; // Print("<-ChooseOperatorFunc %p\n", func); // Print("calc %d\n", unit->mCalcRate); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(UnaryOp) { ft = inTable; DefineSimpleUnit(UnaryOpUGen); }
34,535
C++
.cpp
1,189
21.619849
120
0.498855
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
29,938
FFTInterfaceTable.cpp
supercollider_supercollider/server/plugins/FFTInterfaceTable.cpp
/* 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 */ // third party Phase Vocoder UGens #include "FFT_UGens.h" InterfaceTable* ft; // these are defined in the relevant files extern void initFFT(InterfaceTable* inTable); extern void initPV(InterfaceTable* inTable); extern void initPartConv(InterfaceTable* inTable); PluginLoad(FFT_UGens) { ft = inTable; initFFT(inTable); initPV(inTable); initPartConv(inTable); }
1,257
C++
.cpp
29
39.517241
81
0.765189
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
29,939
FFT_UGens.cpp
supercollider_supercollider/server/plugins/FFT_UGens.cpp
/* Improved FFT and IFFT UGens for SuperCollider 3 Copyright (c) 2007-2008 Dan Stowell, incorporating code from SuperCollider 3 Copyright (c) 2002 James McCartney. 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 */ #include "FFT_UGens.h" // We include vDSP even if not using for FFT, since we want to use some vectorised add/mul tricks #if defined(__APPLE__) && !defined(SC_IPHONE) # include <Accelerate/Accelerate.h> #endif struct FFTBase : public Unit { SndBuf* m_fftsndbuf; float* m_fftbuf; int m_pos, m_fullbufsize, m_audiosize; // "fullbufsize" includes any zero-padding, "audiosize" does not. int m_log2n_full, m_log2n_audio; uint32 m_fftbufnum; scfft* m_scfft; int m_hopsize, m_shuntsize; // These add up to m_audiosize int m_wintype; int m_numSamples; }; struct FFT : public FFTBase { float* m_inbuf; }; struct IFFT : public FFTBase { float* m_olabuf; int m_numSamples; }; struct FFTTrigger : public FFTBase { int m_numPeriods, m_periodsRemain, m_polar; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void FFT_Ctor(FFT* unit); void FFT_ClearUnitOutputs(FFT* unit, int wrongNumSamples); void FFT_next(FFT* unit, int inNumSamples); void FFT_Dtor(FFT* unit); void IFFT_Ctor(IFFT* unit); void IFFT_next(IFFT* unit, int inNumSamples); void IFFT_Dtor(IFFT* unit); void FFTTrigger_Ctor(FFTTrigger* unit); void FFTTrigger_next(FFTTrigger* unit, int inNumSamples); } ////////////////////////////////////////////////////////////////////////////////////////////////// static int FFTBase_Ctor(FFTBase* unit, int frmsizinput) { World* world = unit->mWorld; uint32 bufnum = (uint32)ZIN0(0); SndBuf* buf; if (bufnum >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localMaxBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { if (unit->mWorld->mVerbosity > -1) { Print("FFTBase_Ctor error: invalid buffer number: %i.\n", bufnum); } return 0; } } else { buf = world->mSndBufs + bufnum; } if (!buf->data) { if (unit->mWorld->mVerbosity > -1) { Print("FFTBase_Ctor error: Buffer %i not initialised.\n", bufnum); } return 0; } unit->m_fftsndbuf = buf; unit->m_fftbufnum = bufnum; unit->m_fullbufsize = buf->samples; int framesize = (int)ZIN0(frmsizinput); if (framesize < 1) unit->m_audiosize = buf->samples; else unit->m_audiosize = sc_min(buf->samples, framesize); unit->m_log2n_full = LOG2CEIL(unit->m_fullbufsize); unit->m_log2n_audio = LOG2CEIL(unit->m_audiosize); // Although FFTW allows non-power-of-two buffers (vDSP doesn't), this would complicate the windowing, so we don't // allow it. if (!ISPOWEROFTWO(unit->m_fullbufsize)) { Print("FFTBase_Ctor error: buffer size (%i) not a power of two.\n", unit->m_fullbufsize); return 0; } else if (!ISPOWEROFTWO(unit->m_audiosize)) { Print("FFTBase_Ctor error: audio frame size (%i) not a power of two.\n", unit->m_audiosize); return 0; } else if (unit->m_audiosize < SC_FFT_MINSIZE || (((int)(unit->m_audiosize / unit->mWorld->mFullRate.mBufLength)) * unit->mWorld->mFullRate.mBufLength != unit->m_audiosize)) { Print("FFTBase_Ctor error: audio frame size (%i) not a multiple of the block size (%i).\n", unit->m_audiosize, unit->mWorld->mFullRate.mBufLength); return 0; } unit->m_pos = 0; ZOUT0(0) = ZIN0(0); return 1; } ////////////////////////////////////////////////////////////////////////////////////////////////// void FFT_Ctor(FFT* unit) { int winType = sc_clip((int)ZIN0(3), -1, 1); // wintype may be used by the base ctor unit->m_wintype = winType; // These zeroes are to prevent the dtor freeing things that don't exist: unit->m_inbuf = nullptr; unit->m_scfft = nullptr; if (!FFTBase_Ctor(unit, 5)) { SETCALC(FFT_ClearUnitOutputs); return; } int audiosize = unit->m_audiosize * sizeof(float); int hopsize = (int)(sc_max(sc_min(ZIN0(2), 1.f), 0.f) * unit->m_audiosize); if (hopsize < unit->mWorld->mFullRate.mBufLength) { Print("FFT_Ctor: hopsize smaller than SC's block size (%i) - automatically corrected.\n", hopsize, unit->mWorld->mFullRate.mBufLength); hopsize = unit->mWorld->mFullRate.mBufLength; } else if (((int)(hopsize / unit->mWorld->mFullRate.mBufLength)) * unit->mWorld->mFullRate.mBufLength != hopsize) { Print("FFT_Ctor: hopsize (%i) not an exact multiple of SC's block size (%i) - automatically corrected.\n", hopsize, unit->mWorld->mFullRate.mBufLength); hopsize = ((int)(hopsize / unit->mWorld->mFullRate.mBufLength)) * unit->mWorld->mFullRate.mBufLength; } unit->m_hopsize = hopsize; unit->m_shuntsize = unit->m_audiosize - hopsize; unit->m_inbuf = (float*)RTAlloc(unit->mWorld, audiosize); ClearFFTUnitIfMemFailed(unit->m_inbuf); SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft = scfft_create(unit->m_fullbufsize, unit->m_audiosize, (SCFFT_WindowFunction)unit->m_wintype, unit->m_inbuf, unit->m_fftsndbuf->data, kForward, alloc); ClearFFTUnitIfMemFailed(unit->m_scfft); memset(unit->m_inbuf, 0, audiosize); // Print("FFT_Ctor: hopsize %i, shuntsize %i, bufsize %i, wintype %i, \n", // unit->m_hopsize, unit->m_shuntsize, unit->m_bufsize, unit->m_wintype); if (INRATE(1) == calc_FullRate) { unit->m_numSamples = unit->mWorld->mFullRate.mBufLength; } else { unit->m_numSamples = 1; } SETCALC(FFT_next); } void FFT_Dtor(FFT* unit) { SCWorld_Allocator alloc(ft, unit->mWorld); if (unit->m_scfft) scfft_destroy(unit->m_scfft, alloc); if (unit->m_inbuf) RTFree(unit->mWorld, unit->m_inbuf); } void FFT_next(FFT* unit, int wrongNumSamples) { float* in = IN(1); float* out = unit->m_inbuf + unit->m_pos + unit->m_shuntsize; int numSamples = unit->m_numSamples; // copy input memcpy(out, in, numSamples * sizeof(float)); unit->m_pos += numSamples; bool gate = ZIN0(4) > 0.f; // Buffer shunting continues, but no FFTing if (unit->m_pos != unit->m_hopsize || !unit->m_fftsndbuf->data || unit->m_fftsndbuf->samples != unit->m_fullbufsize) { if (unit->m_pos == unit->m_hopsize) unit->m_pos = 0; ZOUT0(0) = -1.f; } else { unit->m_pos = 0; if (gate) { scfft_dofft(unit->m_scfft); unit->m_fftsndbuf->coord = coord_Complex; ZOUT0(0) = unit->m_fftbufnum; } else { ZOUT0(0) = -1; } // Shunt input buf down memmove(unit->m_inbuf, unit->m_inbuf + unit->m_hopsize, unit->m_shuntsize * sizeof(float)); } } ///////////////////////////////////////////////////////////////////////////////////////////// void IFFT_Ctor(IFFT* unit) { int winType = sc_clip((int)ZIN0(1), -1, 1); // wintype may be used by the base ctor unit->m_wintype = winType; // These zeroes are to prevent the dtor freeing things that don't exist: unit->m_olabuf = nullptr; unit->m_scfft = nullptr; if (!FFTBase_Ctor(unit, 2)) { SETCALC(*ClearUnitOutputs); return; } // This will hold the transformed and progressively overlap-added data ready for outputting. unit->m_olabuf = (float*)RTAlloc(unit->mWorld, unit->m_audiosize * sizeof(float)); ClearUnitIfMemFailed(unit->m_olabuf); memset(unit->m_olabuf, 0, unit->m_audiosize * sizeof(float)); SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft = scfft_create(unit->m_fullbufsize, unit->m_audiosize, (SCFFT_WindowFunction)unit->m_wintype, unit->m_fftsndbuf->data, unit->m_fftsndbuf->data, kBackward, alloc); ClearUnitIfMemFailed(unit->m_scfft); // "pos" will be reset to zero when each frame comes in. Until then, the following ensures silent output at first: unit->m_pos = 0; // unit->m_audiosize; if (unit->mCalcRate == calc_FullRate) { unit->m_numSamples = unit->mWorld->mFullRate.mBufLength; } else { unit->m_numSamples = 1; } SETCALC(IFFT_next); ClearUnitOutputs(unit, 1); } void IFFT_Dtor(IFFT* unit) { if (unit->m_olabuf) RTFree(unit->mWorld, unit->m_olabuf); SCWorld_Allocator alloc(ft, unit->mWorld); if (unit->m_scfft) scfft_destroy(unit->m_scfft, alloc); } void IFFT_next(IFFT* unit, int wrongNumSamples) { float* out = OUT(0); // NB not ZOUT0 // Load state from struct into local scope int pos = unit->m_pos; int audiosize = unit->m_audiosize; int numSamples = unit->m_numSamples; float* olabuf = unit->m_olabuf; float fbufnum = ZIN0(0); // Only run the IFFT if we're receiving a new block of input data - otherwise just output data already received if (fbufnum >= 0.f) { // Ensure it's in cartesian format, not polar ToComplexApx(unit->m_fftsndbuf); float* fftbuf = unit->m_fftsndbuf->data; scfft_doifft(unit->m_scfft); // Then shunt the "old" time-domain output down by one hop int hopsamps = pos; int shuntsamps = audiosize - hopsamps; if (hopsamps != audiosize) // There's only copying to be done if the position isn't all the way to the end of the buffer memmove(olabuf, olabuf + hopsamps, shuntsamps * sizeof(float)); // Then mix the "new" time-domain data in - adding at first, then just setting (copying) where the "old" is supposed to // be zero. #if defined(__APPLE__) && !defined(SC_IPHONE) vDSP_vadd(olabuf, 1, fftbuf, 1, olabuf, 1, shuntsamps); #else // NB we re-use the "pos" variable temporarily here for write rather than read for (pos = 0; pos < shuntsamps; ++pos) { olabuf[pos] += fftbuf[pos]; } #endif memcpy(olabuf + shuntsamps, fftbuf + shuntsamps, (hopsamps) * sizeof(float)); // Move the pointer back to zero, which is where playback will next begin pos = 0; } // End of has-the-chain-fired // Now we can output some stuff, as long as there is still data waiting to be output. // If there is NOT data waiting to be output, we output zero. (Either irregular/negative-overlap // FFT firing, or FFT has given up, or at very start of execution.) if (pos >= audiosize) ClearUnitOutputs(unit, numSamples); else { memcpy(out, olabuf + pos, numSamples * sizeof(float)); pos += numSamples; } unit->m_pos = pos; } ///////////////////////////////////////////////////////////////////////////////////////////// void FFTTrigger_Ctor(FFTTrigger* unit) { World* world = unit->mWorld; /* uint32 bufnum = (uint32)IN0(0); Print("FFTTrigger_Ctor: bufnum is %i\n", bufnum); if (bufnum >= world->mNumSndBufs) bufnum = 0; SndBuf *buf = world->mSndBufs + bufnum; */ uint32 bufnum = (uint32)IN0(0); // Print("FFTTrigger_Ctor: bufnum is %i\n", bufnum); SndBuf* buf; if (bufnum >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localMaxBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { bufnum = 0; buf = world->mSndBufs + bufnum; } } else { buf = world->mSndBufs + bufnum; } LOCK_SNDBUF(buf); unit->m_fftsndbuf = buf; unit->m_fftbufnum = bufnum; unit->m_fullbufsize = buf->samples; int numSamples = unit->mWorld->mFullRate.mBufLength; float dataHopSize = IN0(1); unit->m_numPeriods = unit->m_periodsRemain = (int)(((float)unit->m_fullbufsize * dataHopSize) / numSamples) - 1; buf->coord = (IN0(2) == 1.f) ? coord_Polar : coord_Complex; OUT0(0) = IN0(0); SETCALC(FFTTrigger_next); } void FFTTrigger_next(FFTTrigger* unit, int inNumSamples) { if (unit->m_periodsRemain > 0) { ZOUT0(0) = -1.f; unit->m_periodsRemain--; } else { ZOUT0(0) = unit->m_fftbufnum; unit->m_pos = 0; unit->m_periodsRemain = unit->m_numPeriods; } } void initFFT(InterfaceTable* inTable) { ft = inTable; DefineDtorUnit(FFT); DefineDtorUnit(IFFT); DefineSimpleUnit(FFTTrigger); }
13,411
C++
.cpp
314
36.398089
119
0.617595
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
29,940
ChaosUGens.cpp
supercollider_supercollider/server/plugins/ChaosUGens.cpp
/* 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 Chaos Ugens created by Lance Putnam on Mon Jul 19 2004. */ #include "SC_PlugIn.h" #define TWOPI 6.283185307179586 #define PI 3.141592653589793 #define RECPI 0.3183098861837907 #define RECTWOPI 0.1591549430918953 #define ONESIXTH 0.1666666666666667 static InterfaceTable* ft; struct NonLinear : public Unit { double x0, y0, xn, yn, xnm1, ynm1; float counter; // bool stable; }; struct CuspN : public NonLinear {}; struct CuspL : public CuspN { double frac; }; struct GbmanN : public NonLinear {}; struct GbmanL : public GbmanN { double frac; }; struct HenonN : public Unit { double x0, x1, xn, xnm1, xnm2, a, b; float counter; bool stable; }; struct HenonL : public HenonN { double frac; }; struct HenonC : public HenonL { double xnm3, c0, c1, c2, c3; }; struct LatoocarfianN : public NonLinear {}; struct LatoocarfianL : public LatoocarfianN { double frac; }; struct LatoocarfianC : public LatoocarfianL { double xnm3, xnm2, c0, c1, c2, c3; }; struct LinCongN : public NonLinear {}; struct LinCongL : public LinCongN { double frac; }; struct LinCongC : public LinCongL { double xnm3, xnm2, c0, c1, c2, c3; }; struct LorenzN : public NonLinear { double z0, zn, znm1; }; struct LorenzL : public LorenzN { double frac; }; struct QuadN : public NonLinear {}; struct QuadL : public QuadN { double frac; }; struct QuadC : public QuadL { double xnm3, xnm2; double c0, c1, c2, c3; }; struct StandardN : public NonLinear {}; struct StandardL : public StandardN { double frac; }; struct FBSineN : public NonLinear {}; struct FBSineL : public FBSineN { double frac; }; struct FBSineC : public FBSineL { double xnm3, xnm2; double c0, c1, c2, c3; }; extern "C" { void CuspN_next(CuspN* unit, int inNumSamples); void CuspN_Ctor(CuspN* unit); void CuspL_next(CuspL* unit, int inNumSamples); void CuspL_Ctor(CuspL* unit); void GbmanN_next(GbmanN* unit, int inNumSamples); void GbmanN_Ctor(GbmanN* unit); void GbmanL_next(GbmanL* unit, int inNumSamples); void GbmanL_Ctor(GbmanL* unit); void HenonN_next(HenonN* unit, int inNumSamples); void HenonN_Ctor(HenonN* unit); void HenonL_next(HenonL* unit, int inNumSamples); void HenonL_Ctor(HenonL* unit); void HenonC_next(HenonC* unit, int inNumSamples); void HenonC_Ctor(HenonC* unit); void LinCongN_next(LinCongN* unit, int inNumSamples); void LinCongN_Ctor(LinCongN* unit); void LinCongL_next(LinCongL* unit, int inNumSamples); void LinCongL_Ctor(LinCongL* unit); void LinCongC_next(LinCongC* unit, int inNumSamples); void LinCongC_Ctor(LinCongC* unit); void LatoocarfianN_next(LatoocarfianN* unit, int inNumSamples); void LatoocarfianN_Ctor(LatoocarfianN* unit); void LatoocarfianL_next(LatoocarfianL* unit, int inNumSamples); void LatoocarfianL_Ctor(LatoocarfianL* unit); void LatoocarfianC_next(LatoocarfianC* unit, int inNumSamples); void LatoocarfianC_Ctor(LatoocarfianC* unit); void LorenzL_next(LorenzL* unit, int inNumSamples); void LorenzL_Ctor(LorenzL* unit); void QuadN_next(QuadN* unit, int inNumSamples); void QuadN_Ctor(QuadN* unit); void QuadL_next(QuadL* unit, int inNumSamples); void QuadL_Ctor(QuadL* unit); void QuadC_next(QuadC* unit, int inNumSamples); void QuadC_Ctor(QuadC* unit); void StandardN_next(StandardN* unit, int inNumSamples); void StandardN_Ctor(StandardN* unit); void StandardL_next(StandardL* unit, int inNumSamples); void StandardL_Ctor(StandardL* unit); void FBSineN_next(FBSineN* unit, int inNumSamples); void FBSineN_Ctor(FBSineN* unit); void FBSineL_next(FBSineL* unit, int inNumSamples); void FBSineL_Ctor(FBSineL* unit); void FBSineC_next(FBSineC* unit, int inNumSamples); void FBSineC_Ctor(FBSineC* unit); } //////////////////////////////////////////////////////////////////////////////// // calc 3rd order interpolation coefs from four points static inline void ipol3Coef(double xnm3, double xnm2, double xnm1, double xn, double& c0, double& c1, double& c2, double& c3) { c0 = xnm2; c1 = 0.5f * (xnm1 - xnm3); c2 = xnm3 - (2.5f * xnm2) + xnm1 + xnm1 - 0.5f * xn; c3 = 0.5f * (xn - xnm3) + 1.5f * (xnm2 - xnm1); } // do 3rd order interpolation using coefs static inline double ipol3(float frac, double c0, double c1, double c2, double c3) { return ((c3 * frac + c2) * frac + c1) * frac + c0; } // quick 2pi modulo inline double mod2pi(double in) { const double lo = (double)0.; const double hi = TWOPI; if (in >= hi) { in -= hi; if (in < hi) return in; } else if (in < lo) { in += hi; if (in >= lo) return in; } else return in; return in - hi * (double)((int)(in * RECTWOPI)); } //////////////////////////////////////////////////////////////////////////////// void CuspN_next(CuspN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double x0 = ZIN0(3); double xn = unit->xn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if (unit->x0 != x0) { unit->x0 = xn = x0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; xn = a - (b * sqrt(sc_abs(xn))); } counter++; ZXP(out) = xn; } unit->xn = xn; unit->counter = counter; } void CuspN_Ctor(CuspN* unit) { SETCALC(CuspN_next); unit->x0 = ZIN0(3); unit->xn = unit->x0; unit->counter = 0.f; CuspN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void CuspL_next(CuspL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double x0 = ZIN0(3); double xn = unit->xn; float counter = unit->counter; double xnm1 = unit->xnm1; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if (unit->x0 != x0) { xnm1 = xn; unit->x0 = xn = x0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xn; xn = a - (b * sqrt(sc_abs(xn))); dx = xn - xnm1; } counter++; ZXP(out) = xnm1 + dx * frac; frac += slope; } unit->xn = xn; unit->counter = counter; unit->xnm1 = xnm1; unit->frac = frac; } void CuspL_Ctor(CuspL* unit) { SETCALC(CuspL_next); unit->x0 = ZIN0(3); unit->xn = unit->x0; unit->xnm1 = unit->x0; unit->counter = 0.f; unit->frac = 0.f; CuspL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void FBSineN_next(FBSineN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if ((unit->x0 != x0) || (unit->y0 != y0)) { unit->x0 = xn = x0; unit->y0 = yn = y0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; xn = sin(a * yn + b * xn); yn = c * yn + d; yn = mod2pi(yn); } counter++; ZXP(out) = xn; } unit->xn = xn; unit->yn = yn; unit->counter = counter; } void FBSineN_Ctor(FBSineN* unit) { SETCALC(FBSineN_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->counter = 0.f; FBSineN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void FBSineL_next(FBSineL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double yn = unit->yn; double xnm1 = unit->xnm1; float counter = unit->counter; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if ((unit->x0 != x0) || (unit->y0 != y0)) { xnm1 = xn; unit->x0 = xn = x0; unit->y0 = yn = y0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; xnm1 = xn; xn = sin(a * yn + b * xn); yn = c * yn + d; yn = mod2pi(yn); dx = xn - xnm1; } counter++; ZXP(out) = xnm1 + dx * frac; frac += slope; } unit->xn = xn; unit->yn = yn; unit->xnm1 = xnm1; unit->counter = counter; unit->frac = frac; } void FBSineL_Ctor(FBSineL* unit) { SETCALC(FBSineL_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->xnm1 = unit->x0; unit->counter = 0.f; unit->frac = 0.0; FBSineL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void FBSineC_next(FBSineC* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; double xnm3 = unit->xnm3; double yn = unit->yn; float counter = unit->counter; double frac = unit->frac; double c0 = unit->c0; double c1 = unit->c1; double c2 = unit->c2; double c3 = unit->c3; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; if ((unit->x0 != x0) || (unit->y0 != y0)) { unit->x0 = xn = x0; unit->y0 = y0; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; xn = sin(a * yn + b * xn); yn = c * yn + d; yn = mod2pi(yn); ipol3Coef(xnm3, xnm2, xnm1, xn, c0, c1, c2, c3); } counter++; ZXP(out) = ipol3(frac, c0, c1, c2, c3); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->xnm3 = xnm3; unit->yn = yn; unit->counter = counter; unit->frac = frac; unit->c0 = c0; unit->c1 = c1; unit->c2 = c2; unit->c3 = c3; } void FBSineC_Ctor(FBSineC* unit) { SETCALC(FBSineC_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->xnm1 = unit->xnm2 = unit->xnm3 = unit->x0; unit->counter = 0.f; unit->frac = 0.0; unit->c0 = unit->c1 = unit->c2 = unit->c3 = 0.; FBSineC_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void GbmanN_next(GbmanN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; double xPrev = xn; if (xPrev < 0.f) xn = 1.f - yn - xPrev; else xn = 1.f - yn + xPrev; yn = xPrev; } counter++; ZXP(out) = xn; } unit->xn = xn; unit->yn = yn; unit->counter = counter; } void GbmanN_Ctor(GbmanN* unit) { SETCALC(GbmanN_next); unit->xn = ZIN0(1); unit->yn = ZIN0(2); unit->counter = 0.f; GbmanN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void GbmanL_next(GbmanL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } double diff = xn - yn; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; double xPrev = xn; if (xPrev < 0.f) xn = 1.f - yn - xPrev; else xn = 1.f - yn + xPrev; yn = xPrev; diff = xn - xPrev; } counter++; ZXP(out) = yn + (frac * diff); frac += slope; } unit->xn = xn; unit->yn = yn; unit->counter = counter; unit->frac = frac; } void GbmanL_Ctor(GbmanL* unit) { SETCALC(GbmanL_next); unit->xn = ZIN0(1); unit->yn = ZIN0(2); unit->counter = 0.f; unit->frac = 0.f; GbmanL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void HenonN_next(HenonN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double x0 = ZIN0(3); double x1 = ZIN0(4); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; float counter = unit->counter; bool stable = unit->stable; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if ((unit->a != a) || (unit->b != b) || (unit->x0 != x0) || (unit->x1 != x1)) { if (!stable) { xnm2 = x0; xnm1 = x0; xn = x1; } stable = true; unit->a = a; unit->b = b; unit->x0 = x0; unit->x1 = x1; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; if (stable) { xn = 1.f - (a * xnm1 * xnm1) + (b * xnm2); // Print("%g, ", xn); if ((xn > 1.5f) || (xn < -1.5f)) { stable = false; xn = 0.f; xnm2 = x0; xnm1 = x1; } else { xnm2 = xnm1; xnm1 = xn; } } } counter++; ZXP(out) = xnm2; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->counter = counter; unit->stable = stable; } void HenonN_Ctor(HenonN* unit) { SETCALC(HenonN_next); unit->x0 = ZIN0(3); unit->x1 = ZIN0(4); unit->xn = unit->x1; unit->xnm1 = unit->x0; unit->xnm2 = unit->x1; unit->a = ZIN0(1); unit->b = ZIN0(2); unit->counter = 0.f; unit->stable = true; HenonN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void HenonL_next(HenonL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double x0 = ZIN0(3); double x1 = ZIN0(4); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; float counter = unit->counter; bool stable = unit->stable; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; if ((unit->a != a) || (unit->b != b) || (unit->x0 != x0) || (unit->x1 != x1)) { if (!stable) { xnm2 = x0; xnm1 = x0; xn = x1; } stable = true; unit->a = a; unit->b = b; unit->x0 = x0; unit->x1 = x1; } double diff = xnm1 - xnm2; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; if (stable) { xn = 1.f - (a * xnm1 * xnm1) + (b * xnm2); if (xn > 1.5f || xn < -1.5f) { stable = false; diff = 0.f; xn = 1.f; xnm1 = 0.f; xnm2 = 0.f; } else { xnm2 = xnm1; xnm1 = xn; diff = xnm1 - xnm2; } frac = 0.f; } // Print("slope %g, x2 %g\n", slope, x2); } counter++; ZXP(out) = xnm2 + (diff * frac); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->counter = counter; unit->stable = stable; unit->frac = frac; } void HenonL_Ctor(HenonL* unit) { SETCALC(HenonL_next); unit->x0 = ZIN0(3); unit->x1 = ZIN0(4); unit->xn = unit->x1; unit->xnm1 = unit->x0; unit->xnm2 = unit->x1; unit->a = ZIN0(1); unit->b = ZIN0(2); unit->counter = 0.f; unit->stable = true; unit->frac = 0.; HenonL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void HenonC_next(HenonC* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double x0 = ZIN0(3); double x1 = ZIN0(4); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; double xnm3 = unit->xnm3; float counter = unit->counter; bool stable = unit->stable; double frac = unit->frac; double c0 = unit->c0; double c1 = unit->c1; double c2 = unit->c2; double c3 = unit->c3; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; if ((unit->a != a) || (unit->b != b) || (unit->x0 != x0) || (unit->x1 != x1)) { if (!stable) { xnm3 = xnm2; xnm2 = x0; xnm1 = x0; xn = x1; } stable = true; unit->a = a; unit->b = b; unit->x0 = x0; unit->x1 = x1; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; if (stable) { xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; xn = 1.f - (a * xnm1 * xnm1) + (b * xnm2); if ((xn > 1.5) || (xn < -1.5)) { stable = false; xn = 1.; xnm1 = xnm2 = xnm3 = 0.; } ipol3Coef(xnm3, xnm2, xnm1, xn, c0, c1, c2, c3); } // Print("slope %g, x2 %g\n", slope, x2); } counter++; ZXP(out) = ipol3(frac, c0, c1, c2, c3); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->xnm3 = xnm3; unit->counter = counter; unit->stable = stable; unit->frac = frac; unit->c0 = c0; unit->c1 = c1; unit->c2 = c2; unit->c3 = c3; } void HenonC_Ctor(HenonC* unit) { SETCALC(HenonC_next); unit->x0 = ZIN0(3); unit->x1 = ZIN0(4); unit->xn = unit->x1; unit->xnm1 = unit->x0; unit->xnm2 = unit->xnm3 = unit->x1; unit->a = ZIN0(1); unit->b = ZIN0(2); unit->counter = 0.f; unit->stable = true; unit->frac = 0.0; unit->c0 = unit->c1 = unit->c2 = unit->c3 = 0.; HenonC_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LatoocarfianN_next(LatoocarfianN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if ((unit->x0 != x0) || (unit->y0 != y0)) { unit->x0 = xn = x0; unit->y0 = yn = y0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; const double xnm1 = xn; xn = sin(yn * b) + c * sin(xnm1 * b); yn = sin(xnm1 * a) + d * sin(yn * a); } counter++; ZXP(out) = xn; } unit->xn = xn; unit->yn = yn; unit->counter = counter; } void LatoocarfianN_Ctor(LatoocarfianN* unit) { SETCALC(LatoocarfianN_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->counter = 0.f; LatoocarfianN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LatoocarfianL_next(LatoocarfianL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; double xnm1 = unit->xnm1; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if ((unit->x0 != x0) || (unit->y0 != y0)) { xnm1 = xn; unit->x0 = xn = x0; unit->y0 = yn = y0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xn; xn = sin(yn * b) + c * sin(xnm1 * b); yn = sin(xnm1 * a) + d * sin(yn * a); dx = xn - xnm1; } counter++; ZXP(out) = xnm1 + dx * frac; frac += slope; } unit->xn = xn; unit->yn = yn; unit->counter = counter; unit->xnm1 = xnm1; unit->frac = frac; } void LatoocarfianL_Ctor(LatoocarfianL* unit) { SETCALC(LatoocarfianL_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->xnm1 = unit->x0; unit->counter = 0.f; unit->frac = 0.f; LatoocarfianL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LatoocarfianC_next(LatoocarfianC* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double d = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; double xnm3 = unit->xnm3; double yn = unit->yn; float counter = unit->counter; double frac = unit->frac; double c0 = unit->c0; double c1 = unit->c1; double c2 = unit->c2; double c3 = unit->c3; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; if ((unit->x0 != x0) || (unit->y0 != y0)) { xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; unit->x0 = xn = x0; unit->y0 = yn = y0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; xn = sin(yn * b) + c * sin(xnm1 * b); yn = sin(xnm1 * a) + d * sin(yn * a); ipol3Coef(xnm3, xnm2, xnm1, xn, c0, c1, c2, c3); } counter++; ZXP(out) = ipol3(frac, c0, c1, c2, c3); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->xnm3 = xnm3; unit->yn = yn; unit->counter = counter; unit->frac = frac; unit->c0 = c0; unit->c1 = c1; unit->c2 = c2; unit->c3 = c3; } void LatoocarfianC_Ctor(LatoocarfianC* unit) { SETCALC(LatoocarfianC_next); unit->x0 = ZIN0(5); unit->y0 = ZIN0(6); unit->xn = unit->x0; unit->yn = unit->y0; unit->xnm1 = unit->xnm2 = unit->xnm3 = unit->x0; unit->counter = 0.f; unit->frac = 0.0; unit->c0 = unit->c1 = unit->c2 = unit->c3 = unit->x0; LatoocarfianC_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LinCongN_next(LinCongN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); // multiplier double c = ZIN0(2); // increment double m = sc_max(ZIN0(3), 0.001f); // modulus double xn = unit->xn; float counter = unit->counter; double scaleFactor = 2.f / m; double xscaled = (xn * scaleFactor) - 1.f; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; xn = (xn * a) + c; xn = sc_mod(xn, m); xscaled = (xn * scaleFactor) - 1.f; } counter++; ZXP(out) = xscaled; } unit->xn = xn; unit->counter = counter; } void LinCongN_Ctor(LinCongN* unit) { SETCALC(LinCongN_next); unit->xn = ZIN0(4); // initial x unit->counter = 0.f; LinCongN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LinCongL_next(LinCongL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); // multiplier double c = ZIN0(2); // increment double m = sc_max(ZIN0(3), 0.001f); // modulus double xn = unit->xn; float counter = unit->counter; double xnm1 = unit->xnm1; double frac = unit->frac; double scaleFactor = 2.f / m; double xscaled = (xn * scaleFactor) - 1.f; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } double diff = xscaled - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xscaled; xn = (xn * a) + c; xn = sc_mod(xn, m); xscaled = (xn * scaleFactor) - 1.f; diff = xscaled - xnm1; } counter++; ZXP(out) = xnm1 + (frac * diff); frac += slope; } unit->xn = xn; unit->counter = counter; unit->xnm1 = xnm1; unit->frac = frac; } void LinCongL_Ctor(LinCongL* unit) { SETCALC(LinCongL_next); unit->xn = ZIN0(4); unit->counter = 0.f; unit->xnm1 = unit->xn; unit->frac = 0.f; LinCongL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LinCongC_next(LinCongC* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); // multiplier double c = ZIN0(2); // increment double m = sc_max(ZIN0(3), 0.001f); // modulus double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; double xnm3 = unit->xnm3; float counter = unit->counter; double frac = unit->frac; double c0 = unit->c0; double c1 = unit->c1; double c2 = unit->c2; double c3 = unit->c3; double scaleFactor = 2.f / m; double xscaled = (xn * scaleFactor) - 1.f; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xscaled; xn = (xn * a) + c; xn = sc_mod(xn, m); xscaled = (xn * scaleFactor) - 1.f; ipol3Coef(xnm3, xnm2, xnm1, xscaled, c0, c1, c2, c3); } counter++; ZXP(out) = ipol3(frac, c0, c1, c2, c3); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->xnm3 = xnm3; unit->counter = counter; unit->frac = frac; unit->c0 = c0; unit->c1 = c1; unit->c2 = c2; unit->c3 = c3; } void LinCongC_Ctor(LinCongC* unit) { SETCALC(LinCongC_next); unit->x0 = ZIN0(4); unit->xn = unit->x0; unit->xnm1 = unit->xnm2 = unit->xnm3 = unit->x0; unit->counter = 0.f; unit->frac = 0.0; unit->c0 = unit->c1 = unit->c2 = unit->c3 = unit->x0; LinCongC_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void LorenzL_next(LorenzL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double s = ZIN0(1); double r = ZIN0(2); double b = ZIN0(3); double h = ZIN0(4); double x0 = ZIN0(5); double y0 = ZIN0(6); double z0 = ZIN0(7); double xn = unit->xn; double yn = unit->yn; double zn = unit->zn; float counter = unit->counter; double xnm1 = unit->xnm1; double ynm1 = unit->ynm1; double znm1 = unit->znm1; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if ((unit->x0 != x0) || (unit->y0 != y0) || (unit->z0 != z0)) { xnm1 = xn; ynm1 = yn; znm1 = zn; unit->x0 = xn = x0; unit->y0 = yn = y0; unit->z0 = zn = z0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xn; ynm1 = yn; znm1 = zn; double k1x, k2x, k3x, k4x, k1y, k2y, k3y, k4y, k1z, k2z, k3z, k4z, kxHalf, kyHalf, kzHalf; double hTimesS = h * s; // 4th order Runge-Kutta k1x = hTimesS * (ynm1 - xnm1); k1y = h * (xnm1 * (r - znm1) - ynm1); k1z = h * (xnm1 * ynm1 - b * znm1); kxHalf = k1x * 0.5; kyHalf = k1y * 0.5; kzHalf = k1z * 0.5; k2x = hTimesS * (ynm1 + kyHalf - xnm1 - kxHalf); k2y = h * ((xnm1 + kxHalf) * (r - znm1 - kzHalf) - (ynm1 + kyHalf)); k2z = h * ((xnm1 + kxHalf) * (ynm1 + kyHalf) - b * (znm1 + kzHalf)); kxHalf = k2x * 0.5; kyHalf = k2y * 0.5; kzHalf = k2z * 0.5; k3x = hTimesS * (ynm1 + kyHalf - xnm1 - kxHalf); k3y = h * ((xnm1 + kxHalf) * (r - znm1 - kzHalf) - (ynm1 + kyHalf)); k3z = h * ((xnm1 + kxHalf) * (ynm1 + kyHalf) - b * (znm1 + kzHalf)); k4x = hTimesS * (ynm1 + k3y - xnm1 - k3x); k4y = h * ((xnm1 + k3x) * (r - znm1 - k3z) - (ynm1 + k3y)); k4z = h * ((xnm1 + k3x) * (ynm1 + k3y) - b * (znm1 + k3z)); xn = xn + (k1x + 2.0 * (k2x + k3x) + k4x) * ONESIXTH; yn = yn + (k1y + 2.0 * (k2y + k3y) + k4y) * ONESIXTH; zn = zn + (k1z + 2.0 * (k2z + k3z) + k4z) * ONESIXTH; // Euler's method // xn = xnm1 + h * (s * (ynm1 - xnm1)); // yn = ynm1 + h * (xnm1 * (r - znm1) - ynm1); // zn = znm1 + h * (xnm1 * ynm1 - b * znm1); dx = xn - xnm1; } counter++; ZXP(out) = (xnm1 + dx * frac) * 0.04f; frac += slope; } unit->xn = xn; unit->yn = yn; unit->zn = zn; unit->counter = counter; unit->xnm1 = xnm1; unit->ynm1 = ynm1; unit->znm1 = znm1; unit->frac = frac; } void LorenzL_Ctor(LorenzL* unit) { SETCALC(LorenzL_next); unit->x0 = unit->xn = unit->xnm1 = ZIN0(5); unit->y0 = unit->yn = unit->ynm1 = ZIN0(6); unit->z0 = unit->zn = unit->znm1 = ZIN0(7); unit->counter = 0.f; unit->frac = 0.f; LorenzL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void QuadN_next(QuadN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double x0 = ZIN0(4); double xn = unit->xn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if (unit->x0 != x0) { unit->x0 = xn = x0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; xn = a * xn * xn + b * xn + c; } counter++; ZXP(out) = xn; } unit->xn = xn; unit->counter = counter; } void QuadN_Ctor(QuadN* unit) { SETCALC(QuadN_next); unit->x0 = ZIN0(4); unit->xn = unit->x0; unit->counter = 0.f; QuadN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void QuadL_next(QuadL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double x0 = ZIN0(4); double xn = unit->xn; float counter = unit->counter; double xnm1 = unit->xnm1; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if (unit->x0 != x0) { xnm1 = xn; unit->x0 = xn = x0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xn; xn = a * xn * xn + b * xn + c; dx = xn - xnm1; } counter++; ZXP(out) = xnm1 + dx * frac; frac += slope; } unit->xn = xn; unit->counter = counter; unit->xnm1 = xnm1; unit->frac = frac; } void QuadL_Ctor(QuadL* unit) { SETCALC(QuadL_next); unit->x0 = ZIN0(4); unit->xn = unit->x0; unit->xnm1 = unit->x0; unit->counter = 0.f; unit->frac = 0.f; QuadL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void QuadC_next(QuadC* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double a = ZIN0(1); double b = ZIN0(2); double c = ZIN0(3); double x0 = ZIN0(4); double xn = unit->xn; double xnm1 = unit->xnm1; double xnm2 = unit->xnm2; double xnm3 = unit->xnm3; float counter = unit->counter; double frac = unit->frac; double c0 = unit->c0; double c1 = unit->c1; double c2 = unit->c2; double c3 = unit->c3; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else samplesPerCycle = slope = 1.f; if (unit->x0 != x0) { xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; unit->x0 = xn = x0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.0; xnm3 = xnm2; xnm2 = xnm1; xnm1 = xn; xn = a * xn * xn + b * xn + c; ipol3Coef(xnm3, xnm2, xnm1, xn, c0, c1, c2, c3); } counter++; ZXP(out) = ipol3(frac, c0, c1, c2, c3); frac += slope; } unit->xn = xn; unit->xnm1 = xnm1; unit->xnm2 = xnm2; unit->xnm3 = xnm3; unit->counter = counter; unit->frac = frac; unit->c0 = c0; unit->c1 = c1; unit->c2 = c2; unit->c3 = c3; } void QuadC_Ctor(QuadC* unit) { SETCALC(QuadC_next); unit->x0 = ZIN0(4); unit->xn = unit->x0; unit->xnm1 = unit->xnm2 = unit->xnm3 = unit->x0; unit->c0 = unit->c1 = unit->c2 = unit->c3 = unit->x0; unit->counter = 0.f; unit->frac = 0.0; QuadC_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void StandardN_next(StandardN* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double k = ZIN0(1); double x0 = ZIN0(2); double y0 = ZIN0(3); double xn = unit->xn; double output = (xn - PI) * RECPI; double yn = unit->yn; float counter = unit->counter; float samplesPerCycle; if (freq < unit->mRate->mSampleRate) samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); else samplesPerCycle = 1.f; if ((unit->x0 != x0) || (unit->y0 != y0)) { unit->x0 = xn = x0; unit->y0 = yn = y0; } for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; yn = yn + k * sin(xn); yn = mod2pi(yn); xn = xn + yn; xn = mod2pi(xn); output = (xn - PI) * RECPI; } counter++; ZXP(out) = output; } unit->xn = xn; unit->yn = yn; unit->counter = counter; } void StandardN_Ctor(StandardN* unit) { SETCALC(StandardN_next); unit->x0 = ZIN0(2); unit->y0 = ZIN0(3); unit->xn = unit->x0; unit->yn = unit->y0; unit->counter = 0.f; StandardN_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// void StandardL_next(StandardL* unit, int inNumSamples) { float* out = ZOUT(0); float freq = ZIN0(0); double k = ZIN0(1); double x0 = ZIN0(2); double y0 = ZIN0(3); double xn = unit->xn; double yn = unit->yn; float counter = unit->counter; double xnm1 = unit->xnm1; double frac = unit->frac; float samplesPerCycle; double slope; if (freq < unit->mRate->mSampleRate) { samplesPerCycle = unit->mRate->mSampleRate / sc_max(freq, 0.001f); slope = 1.f / samplesPerCycle; } else { samplesPerCycle = 1.f; slope = 1.f; } if ((unit->x0 != x0) || (unit->y0 != y0)) { xnm1 = xn; unit->x0 = xn = x0; unit->y0 = yn = y0; } double dx = xn - xnm1; for (int i = 0; i < inNumSamples; ++i) { if (counter >= samplesPerCycle) { counter -= samplesPerCycle; frac = 0.f; xnm1 = xn; yn = yn + k * sin(xn); yn = mod2pi(yn); xn = xn + yn; xn = mod2pi(xn); dx = xn - xnm1; } counter++; ZXP(out) = (xnm1 + dx * frac - PI) * RECPI; frac += slope; } unit->xn = xn; unit->yn = yn; unit->counter = counter; unit->xnm1 = xnm1; unit->frac = frac; } void StandardL_Ctor(StandardL* unit) { SETCALC(StandardL_next); unit->x0 = ZIN0(2); unit->y0 = ZIN0(3); unit->xn = unit->x0; unit->yn = unit->y0; unit->xnm1 = unit->x0; unit->counter = 0.f; unit->frac = 0.f; StandardL_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////// PluginLoad(Chaos) { ft = inTable; DefineSimpleUnit(CuspN); DefineSimpleUnit(CuspL); DefineSimpleUnit(FBSineN); DefineSimpleUnit(FBSineL); DefineSimpleUnit(FBSineC); DefineSimpleUnit(GbmanN); DefineSimpleUnit(GbmanL); DefineSimpleUnit(HenonN); DefineSimpleUnit(HenonL); DefineSimpleUnit(HenonC); DefineSimpleUnit(LatoocarfianN); DefineSimpleUnit(LatoocarfianL); DefineSimpleUnit(LatoocarfianC); DefineSimpleUnit(LinCongN); DefineSimpleUnit(LinCongL); DefineSimpleUnit(LinCongC); DefineSimpleUnit(LorenzL); DefineSimpleUnit(QuadN); DefineSimpleUnit(QuadL); DefineSimpleUnit(QuadC); DefineSimpleUnit(StandardN); DefineSimpleUnit(StandardL); }
44,015
C++
.cpp
1,456
23.698489
114
0.521339
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
29,941
UnpackFFTUGens.cpp
supercollider_supercollider/server/plugins/UnpackFFTUGens.cpp
/* "Unpack FFT" UGens for SuperCollider 3. Copyright (c) 2007 Dan Stowell. All rights reserved. (Written during the SC Symposium 2007! Thanks to all whose conversation fed into this.) 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_PlugIn.h" #include "SCComplex.h" #include "FFT_UGens.h" struct Unpack1FFT : Unit { int bufsize; int latestMomentProcessed; // To avoid processing a given FFT frame more than once int binindex; bool wantmag; // yes for mag, no for phase float outval; // int numOldSkipped; // for debug }; struct PackFFT : Unit { int bufsize, numinvals, frombin, tobin; bool zeroothers; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void Unpack1FFT_Ctor(Unpack1FFT* unit); void Unpack1FFT_next_dc(Unpack1FFT* unit, int inNumSamples); void Unpack1FFT_next_nyq(Unpack1FFT* unit, int inNumSamples); void Unpack1FFT_next_mag(Unpack1FFT* unit, int inNumSamples); void Unpack1FFT_next_phase(Unpack1FFT* unit, int inNumSamples); void PackFFT_Ctor(PackFFT* unit); void PackFFT_Dtor(PackFFT* unit); void PackFFT_next(PackFFT* unit, int inNumSamples); } InterfaceTable* ft; //////////////////////////////////////////////////////////////////////////////////////////////////////// void Unpack1FFT_Ctor(Unpack1FFT* unit) { unit->bufsize = (int)ZIN0(1); unit->latestMomentProcessed = -1; // unit->numOldSkipped = 0; unit->outval = 0.f; unit->binindex = (int)ZIN0(2); if (ZIN0(3) == 0.f) { // Mags if (unit->binindex == 0) { SETCALC(Unpack1FFT_next_dc); } else if (unit->binindex == unit->bufsize >> 1) { SETCALC(Unpack1FFT_next_nyq); } else { SETCALC(Unpack1FFT_next_mag); } } else { // Phases if (unit->binindex == 0) { SETCALC(*ClearUnitOutputs); } else if (unit->binindex == unit->bufsize >> 1) { SETCALC(*ClearUnitOutputs); } else { SETCALC(Unpack1FFT_next_phase); } } ZOUT0(0) = unit->outval; } #define UNPACK1FFT_NEXT_COMMON \ float fbufnum = ZIN0(0); \ if (fbufnum < 0.f) { \ if (unit->mWorld->mVerbosity > -1) { \ Print("Unpack1FFT_next: warning, fbufnum < 0\n"); \ } \ ZOUT0(0) = unit->outval; \ return; \ } \ uint32 ibufnum = (uint32)fbufnum; \ World* world = unit->mWorld; \ SndBuf* buf; \ if (ibufnum >= world->mNumSndBufs) { \ int localBufNum = ibufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ buf = world->mSndBufs; \ if (unit->mWorld->mVerbosity > -1) { \ Print("Unpack1FFT_next: warning, bufnum too large: i%\n", ibufnum); \ } \ } \ } else { \ buf = world->mSndBufs + ibufnum; \ } \ int binindex __attribute__((__unused__)) = unit->binindex; \ LOCK_SNDBUF(buf); \ SCComplexBuf* p = ToComplexApx(buf); void Unpack1FFT_next_mag(Unpack1FFT* unit, int inNumSamples) { if (unit->latestMomentProcessed != unit->mWorld->mBufCounter) { UNPACK1FFT_NEXT_COMMON unit->outval = hypotf(p->bin[binindex - 1].real, p->bin[binindex - 1].imag); unit->latestMomentProcessed = unit->mWorld->mBufCounter; // So we won't copy it again, not this frame anyway // unit->numOldSkipped = 0; //}else{ // Print("skipold{%i,%i}", unit->mWorld->mBufCounter, ++unit->numOldSkipped); // Print("Calculation previously done - skipping. unit->mWorld->mBufCounter = %i\n", unit->mWorld->mBufCounter); } ZOUT0(0) = unit->outval; } void Unpack1FFT_next_phase(Unpack1FFT* unit, int inNumSamples) { if (unit->latestMomentProcessed != unit->mWorld->mBufCounter) { UNPACK1FFT_NEXT_COMMON unit->outval = atan2(p->bin[binindex - 1].imag, p->bin[binindex - 1].real); unit->latestMomentProcessed = unit->mWorld->mBufCounter; // So we won't copy it again, not this frame anyway // unit->numOldSkipped = 0; //}else{ // Print("skipold{%i,%i}", unit->mWorld->mBufCounter, ++unit->numOldSkipped); // Print("Calculation previously done - skipping. unit->mWorld->mBufCounter = %i\n", unit->mWorld->mBufCounter); } ZOUT0(0) = unit->outval; } void Unpack1FFT_next_dc(Unpack1FFT* unit, int inNumSamples) { if (unit->latestMomentProcessed != unit->mWorld->mBufCounter) { UNPACK1FFT_NEXT_COMMON unit->outval = p->dc; unit->latestMomentProcessed = unit->mWorld->mBufCounter; // So we won't copy it again, not this frame anyway // unit->numOldSkipped = 0; //}else{ // Print("skipold{%i,%i}", unit->mWorld->mBufCounter, ++unit->numOldSkipped); // Print("Calculation previously done - skipping. unit->mWorld->mBufCounter = %i\n", unit->mWorld->mBufCounter); } ZOUT0(0) = unit->outval; } void Unpack1FFT_next_nyq(Unpack1FFT* unit, int inNumSamples) { if (unit->latestMomentProcessed != unit->mWorld->mBufCounter) { UNPACK1FFT_NEXT_COMMON unit->outval = p->nyq; unit->latestMomentProcessed = unit->mWorld->mBufCounter; // So we won't copy it again, not this frame anyway // unit->numOldSkipped = 0; //}else{ // Print("skipold{%i,%i}", unit->mWorld->mBufCounter, ++unit->numOldSkipped); // Print("Calculation previously done - skipping. unit->mWorld->mBufCounter = %i\n", unit->mWorld->mBufCounter); } ZOUT0(0) = unit->outval; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PackFFT_Ctor(PackFFT* unit) { SETCALC(PackFFT_next); unit->bufsize = (int)ZIN0(1); unit->frombin = (int)ZIN0(2); unit->tobin = (int)ZIN0(3); unit->zeroothers = ZIN0(4) > 0; unit->numinvals = (int)ZIN0(5); // Print("PackFFT_Ctor: Passing chain through, val %g\n", ZIN0(0)); ZOUT0(0) = ZIN0(0); // Required: allows the buffer index to fall through nicely to the IFFT } #define PACKFFT_INPUTSOFFSET 6 void PackFFT_next(PackFFT* unit, int inNumSamples) { /////////////////// cf PV_GET_BUF float fbufnum = ZIN0(0); if (fbufnum < 0.f) { ZOUT0(0) = -1.f; return; } uint32 ibufnum = (uint32)fbufnum; World* world = unit->mWorld; SndBuf* buf; if (ibufnum >= world->mNumSndBufs) { int localBufNum = ibufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { buf = world->mSndBufs; } } else { buf = world->mSndBufs + ibufnum; } LOCK_SNDBUF(buf); int numbins = (buf->samples - 2) >> 1; /////////////////// cf PV_GET_BUF // RM Print("PackFFT_next: fbufnum = %g\n", fbufnum); int numinvals = unit->numinvals; SCComplexBuf* p = ToComplexApx(buf); int frombin = unit->frombin; int tobin = unit->tobin; int zeroothers = unit->zeroothers; // Load data from inputs into "p" if (frombin == 0) { p->dc = DEMANDINPUT(PACKFFT_INPUTSOFFSET); } else if (zeroothers) { p->dc = 0.f; } // Print("New DC is %g\n", p->dc); if (tobin == numbins + 1) { // Print("PackFFT: Fetching nyquist from input #%i\n", (PACKFFT_INPUTSOFFSET + numinvals - 2 - frombin - // frombin)); p->nyq = DEMANDINPUT(PACKFFT_INPUTSOFFSET + numinvals - 2 - frombin - frombin); } else if (zeroothers) { p->nyq = 0.f; } // Print("New nyq (input #%i) is %g\n", numinvals, p->nyq); // real, imag = (mag * cos(phase), mag * sin(phase)) float mag, phase; int startat = frombin == 0 ? 0 : frombin - 1; int endbefore = sc_min(numbins, tobin); for (int i = startat; i < endbefore; i++) { // Print("PackFFT: Fetching mag from input #%i\n", (i + i + PACKFFT_INPUTSOFFSET + 2 - frombin - frombin)); mag = DEMANDINPUT(i + i + PACKFFT_INPUTSOFFSET + 2 - frombin - frombin); phase = DEMANDINPUT(i + i + PACKFFT_INPUTSOFFSET + 3 - frombin - frombin); p->bin[i].real = mag * cos(phase); p->bin[i].imag = mag * sin(phase); } // Print("New bin 7 is %g,%g\n", p->bin[7].real, p->bin[7].imag); if (zeroothers) { // Iterate through the ones we didn't fill in, wiping the magnitude for (int i = 0; i < startat; i++) p->bin[i].real = p->bin[i].imag = 0.f; for (int i = endbefore; i < numbins; i++) p->bin[i].real = p->bin[i].imag = 0.f; } ZOUT0(0) = fbufnum; // Print("PackFFT: fbufnum=%g, ibufnum=%i, numinvals=%i, frombin=%i, tobin=%i, zeroothers=%i\n", // fbufnum, ibufnum, numinvals, frombin, tobin, zeroothers); // Print("PackFFT: p->bin[4].real=%g, p->bin[4].imag=%g, p->bin[5].real=%g, p->bin[5].imag=%g\n", // p->bin[4].real, p->bin[4].imag, p->bin[5].real, p->bin[5].imag); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(UnpackFFTUGens) { ft = inTable; DefineSimpleUnit(Unpack1FFT); DefineSimpleUnit(PackFFT); }
12,471
C++
.cpp
236
46.584746
120
0.478143
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
29,942
PanUGens.cpp
supercollider_supercollider/server/plugins/PanUGens.cpp
/* 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_PlugIn.h" #include "function_attributes.h" #ifdef NOVA_SIMD # include "simd_memory.hpp" # include "simd_binary_arithmetic.hpp" # include "simd_pan.hpp" # include "simd_mix.hpp" using nova::slope_argument; #endif #include <boost/align/is_aligned.hpp> using namespace std; // for math functions static InterfaceTable* ft; struct LinPan2 : public Unit { float m_pos, m_level, m_leftamp, m_rightamp; }; struct Balance2 : public Unit { float m_pos, m_level, m_leftamp, m_rightamp; }; struct Rotate2 : public Unit { float m_pos, m_sint, m_cost; }; struct XFade2 : public Unit { float m_pos, m_level, m_leftamp, m_rightamp; }; struct LinXFade2 : public Unit { float m_pos, m_amp; }; struct Pan2 : public Unit { float m_pos, m_level, m_leftamp, m_rightamp; }; struct Pan4 : public Unit { float m_xpos, m_ypos, m_level, m_LF_amp, m_RF_amp, m_LB_amp, m_RB_amp; }; struct PanB : public Unit { float m_azimuth, m_elevation, m_level, m_W_amp, m_X_amp, m_Y_amp, m_Z_amp; }; struct PanB2 : public Unit { float m_azimuth, m_level, m_W_amp, m_X_amp, m_Y_amp; }; struct BiPanB2 : public Unit { float m_azimuth, m_level, m_W_amp, m_X_amp, m_Y_amp; }; struct PanAz : public Unit { float* m_chanamp; }; struct DecodeB2 : public Unit { float m_cosa, m_sina; float m_W_amp, m_X_amp, m_Y_amp; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void LinPan2_next_ak(LinPan2* unit, int inNumSamples); void LinPan2_next_aa(LinPan2* unit, int inNumSamples); void LinPan2_Ctor(LinPan2* unit); void Balance2_next_ak(Balance2* unit, int inNumSamples); #ifdef NOVA_SIMD FLATTEN void Balance2_next_ak_nova(Balance2* unit, int inNumSamples); FLATTEN void Balance2_next_ak_nova_64(Balance2* unit, int inNumSamples); #endif void Balance2_next_aa(Balance2* unit, int inNumSamples); void Balance2_Ctor(Balance2* unit); void XFade2_next_ak(XFade2* unit, int inNumSamples); void XFade2_next_aa(XFade2* unit, int inNumSamples); void XFade2_Ctor(XFade2* unit); void LinXFade2_next_k(LinXFade2* unit, int inNumSamples); void LinXFade2_next_a(LinXFade2* unit, int inNumSamples); void LinXFade2_Ctor(LinXFade2* unit); void Pan2_next_ak(Pan2* unit, int inNumSamples); void vPan2_next_ak(Pan2* unit, int inNumSamples); void Pan2_next_aa(Pan2* unit, int inNumSamples); void Pan2_Ctor(Pan2* unit); void Pan4_next(Pan4* unit, int inNumSamples); void Pan4_Ctor(Pan4* unit); void PanB_next(PanB* unit, int inNumSamples); void PanB_Ctor(PanB* unit); void PanB2_next(PanB2* unit, int inNumSamples); void PanB2_Ctor(PanB2* unit); void BiPanB2_next(BiPanB2* unit, int inNumSamples); void BiPanB2_Ctor(BiPanB2* unit); void DecodeB2_next(DecodeB2* unit, int inNumSamples); void DecodeB2_next_nova(DecodeB2* unit, int inNumSamples); void vDecodeB2_next(DecodeB2* unit, int inNumSamples); void DecodeB2_Ctor(DecodeB2* unit); void PanAz_next_ak(PanAz* unit, int inNumSamples); void PanAz_next_aa(PanAz* unit, int inNumSamples); void PanAz_Ctor(PanAz* unit); void Rotate2_next_ak(Rotate2* unit, int inNumSamples); void Rotate2_Ctor(Rotate2* unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD FLATTEN void LinPan2_next_ak_nova(LinPan2* unit, int inNumSamples); FLATTEN void LinPan2_next_ak_nova_64(LinPan2* unit, int inNumSamples); #endif void LinPan2_Ctor(LinPan2* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(LinPan2_next_aa); } else { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(LinPan2_next_ak_nova_64); if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(LinPan2_next_ak_nova); else #endif SETCALC(LinPan2_next_ak); } // Now we need to initialise some values, which on the first _next run will be "previous" float pan = ZIN0(1) * 0.5f + 0.5f; unit->m_level = ZIN0(2); unit->m_rightamp = unit->m_level * pan; unit->m_leftamp = unit->m_level - unit->m_rightamp; LinPan2_next_aa(unit, 1); } void LinPan2_next_ak(LinPan2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* in = ZIN(0); float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { float pan = pos * 0.5f + 0.5f; float nextrightamp = level * pan; float nextleftamp = level - nextrightamp; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; LOOP1(inNumSamples, float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp; leftamp += leftampslope; rightamp += rightampslope;); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else { LOOP1(inNumSamples, float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp;); } } #ifdef NOVA_SIMD void LinPan2_next_ak_nova(LinPan2* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { float pan = pos * 0.5f + 0.5f; float nextrightamp = level * pan; float nextleftamp = level - nextrightamp; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::pan2_vec_simd(OUT(0), OUT(1), IN(0), leftamp, leftampslope, rightamp, rightampslope, inNumSamples); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::pan2_vec_simd(OUT(0), OUT(1), IN(0), leftamp, rightamp, inNumSamples); } void LinPan2_next_ak_nova_64(LinPan2* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { float pan = pos * 0.5f + 0.5f; float nextrightamp = level * pan; float nextleftamp = level - nextrightamp; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::pan2_vec_simd<64>(OUT(0), OUT(1), IN(0), leftamp, leftampslope, rightamp, rightampslope); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::pan2_vec_simd<64>(OUT(0), OUT(1), IN(0), leftamp, rightamp); } #endif void LinPan2_next_aa(LinPan2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* in = ZIN(0); float* pos = ZIN(1); float nextlevel = ZIN0(2); float level = unit->m_level; float levelSlope = (nextlevel - level) * unit->mRate->mSlopeFactor; LOOP1(inNumSamples, float pan = ZXP(pos) * 0.5f + 0.5f; float rightamp = level * pan; float leftamp = level - rightamp; float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp; level += levelSlope;); unit->m_level = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Balance2_Ctor(Balance2* unit) { if (INRATE(2) == calc_FullRate) { SETCALC(Balance2_next_aa); } else { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(Balance2_next_ak_nova_64); else if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Balance2_next_ak_nova); else SETCALC(Balance2_next_ak); #else SETCALC(Balance2_next_ak); #endif } unit->m_pos = ZIN0(2); unit->m_level = ZIN0(3); int32 ipos = (int32)(1024.f * unit->m_pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); unit->m_leftamp = unit->m_level * ft->mSine[2048 - ipos]; unit->m_rightamp = unit->m_level * ft->mSine[ipos]; Balance2_next_aa(unit, 1); } void Balance2_next_ak(Balance2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* leftin = ZIN(0); float* rightin = ZIN(1); float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; LOOP1(inNumSamples, ZXP(leftout) = ZXP(leftin) * leftamp; ZXP(rightout) = ZXP(rightin) * rightamp; leftamp += leftampslope; rightamp += rightampslope;); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else { LOOP1(inNumSamples, ZXP(leftout) = ZXP(leftin) * leftamp; ZXP(rightout) = ZXP(rightin) * rightamp;); } } #ifdef NOVA_SIMD void Balance2_next_ak_nova(Balance2* unit, int inNumSamples) { float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; // nova::times_vec2_ramp_simd(OUT(0), IN(0), leftamp, leftampslope, OUT(1), IN(1), rightamp, rightampslope, // inNumSamples); nova::times_vec_simd(OUT(0), IN(0), slope_argument(leftamp, leftampslope), inNumSamples); nova::times_vec_simd(OUT(1), IN(1), slope_argument(rightamp, rightampslope), inNumSamples); } else { // nova::times_vec2_simd(OUT(0), IN(0), leftamp, OUT(1), IN(1), rightamp, inNumSamples); nova::times_vec_simd(OUT(0), IN(0), leftamp, inNumSamples); nova::times_vec_simd(OUT(1), IN(1), rightamp, inNumSamples); } } void Balance2_next_ak_nova_64(Balance2* unit, int inNumSamples) { float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; // nova::times_vec2_ramp_simd(OUT(0), IN(0), leftamp, leftampslope, OUT(1), IN(1), rightamp, rightampslope, // inNumSamples); nova::times_vec_simd(OUT(0), IN(0), slope_argument(leftamp, leftampslope), inNumSamples); nova::times_vec_simd(OUT(1), IN(1), slope_argument(rightamp, rightampslope), inNumSamples); } else { // nova::times_vec2_simd(OUT(0), IN(0), leftamp, OUT(1), IN(1), rightamp, inNumSamples); nova::times_vec_simd<64>(OUT(0), IN(0), leftamp); nova::times_vec_simd<64>(OUT(1), IN(1), rightamp); } } #endif void Balance2_next_aa(Balance2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* leftin = ZIN(0); float* rightin = ZIN(1); float* pos = ZIN(2); float nextlevel = ZIN0(3); float level = unit->m_level; float* sineTable = ft->mSine; if (level != nextlevel) { float levelSlope = (nextlevel - level) * unit->mRate->mSlopeFactor; LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * sineTable[2048 - ipos]; float rightamp = level * sineTable[ipos]; ZXP(leftout) = ZXP(leftin) * leftamp; ZXP(rightout) = ZXP(rightin) * rightamp; level += levelSlope;); unit->m_level = level; } else { LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * sineTable[2048 - ipos]; float rightamp = level * sineTable[ipos]; ZXP(leftout) = ZXP(leftin) * leftamp; ZXP(rightout) = ZXP(rightin) * rightamp;); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD FLATTEN void XFade2_next_ak_nova(XFade2* unit, int inNumSamples); FLATTEN void XFade2_next_ak_nova_64(XFade2* unit, int inNumSamples); #endif void XFade2_Ctor(XFade2* unit) { if (INRATE(2) == calc_FullRate) { SETCALC(XFade2_next_aa); } else { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(XFade2_next_ak_nova_64); if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(XFade2_next_ak_nova); else #endif SETCALC(XFade2_next_ak); } unit->m_pos = ZIN0(2); unit->m_level = ZIN0(3); int32 ipos = (int32)(1024.f * unit->m_pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); unit->m_leftamp = unit->m_level * ft->mSine[2048 - ipos]; unit->m_rightamp = unit->m_level * ft->mSine[ipos]; XFade2_next_aa(unit, 1); } void XFade2_next_ak(XFade2* unit, int inNumSamples) { float* out = ZOUT(0); float* leftin = ZIN(0); float* rightin = ZIN(1); float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; LOOP1(inNumSamples, ZXP(out) = ZXP(leftin) * leftamp + ZXP(rightin) * rightamp; leftamp += leftampslope; rightamp += rightampslope;); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else { LOOP1(inNumSamples, ZXP(out) = ZXP(leftin) * leftamp + ZXP(rightin) * rightamp;); } } #ifdef NOVA_SIMD void XFade2_next_ak_nova(XFade2* unit, int inNumSamples) { float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::mix_vec_simd(OUT(0), IN(0), slope_argument(leftamp, leftampslope), IN(1), slope_argument(rightamp, rightampslope), inNumSamples); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::mix_vec_simd(OUT(0), IN(0), leftamp, IN(1), rightamp, inNumSamples); } void XFade2_next_ak_nova_64(XFade2* unit, int inNumSamples) { float pos = ZIN0(2); float level = ZIN0(3); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::mix_vec_simd<64>(OUT(0), IN(0), slope_argument(leftamp, leftampslope), IN(1), slope_argument(rightamp, rightampslope)); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::mix_vec_simd<64>(OUT(0), IN(0), leftamp, IN(1), rightamp); } #endif void XFade2_next_aa(XFade2* unit, int inNumSamples) { float* out = ZOUT(0); float* leftin = ZIN(0); float* rightin = ZIN(1); float* pos = ZIN(2); float nextlevel = ZIN0(3); float level = unit->m_level; float* sineTable = ft->mSine; if (level != nextlevel) { float levelSlope = (nextlevel - level) * unit->mRate->mSlopeFactor; LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * sineTable[2048 - ipos]; float rightamp = level * sineTable[ipos]; ZXP(out) = ZXP(leftin) * leftamp + ZXP(rightin) * rightamp; level += levelSlope;); unit->m_level = level; } else { LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * sineTable[2048 - ipos]; float rightamp = level * sineTable[ipos]; ZXP(out) = ZXP(leftin) * leftamp + ZXP(rightin) * rightamp;); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void LinXFade2_next_i(LinXFade2* unit, int inNumSamples) { float* out = ZOUT(0); float* leftin = ZIN(0); float* rightin = ZIN(1); float amp = unit->m_amp; LOOP1(inNumSamples, float l = ZXP(leftin); float r = ZXP(rightin); ZXP(out) = l + amp * (r - l);); } void LinXFade2_next_k(LinXFade2* unit, int inNumSamples) { float* out = ZOUT(0); float* leftin = ZIN(0); float* rightin = ZIN(1); float pos = ZIN0(2); float amp = unit->m_amp; if (pos != unit->m_pos) { pos = sc_clip(pos, -1.f, 1.f); float nextamp = pos * 0.5f + 0.5f; float amp_slope = (nextamp - amp) * unit->mRate->mSlopeFactor; LOOP1(inNumSamples, float l = ZXP(leftin); float r = ZXP(rightin); ZXP(out) = l + amp * (r - l); amp += amp_slope;); unit->m_pos = pos; unit->m_amp = amp; } else { LOOP1(inNumSamples, float l = ZXP(leftin); float r = ZXP(rightin); ZXP(out) = l + amp * (r - l);); } } void LinXFade2_next_a(LinXFade2* unit, int inNumSamples) { float* out = ZOUT(0); float* leftin = ZIN(0); float* rightin = ZIN(1); float* posp = ZIN(2); LOOP1(inNumSamples, float pos = ZXP(posp); pos = sc_clip(pos, -1.f, 1.f); float amp = pos * 0.5f + 0.5f; float l = ZXP(leftin); float r = ZXP(rightin); ZXP(out) = l + amp * (r - l);); } #ifdef NOVA_SIMD FLATTEN void LinXFade2_next_i_nova(LinXFade2* unit, int inNumSamples) { float amp = unit->m_amp; nova::mix_vec_simd(OUT(0), IN(0), 1.f - amp, IN(1), amp, inNumSamples); } FLATTEN void LinXFade2_next_k_nova(LinXFade2* unit, int inNumSamples) { float pos = ZIN0(2); float amp = unit->m_amp; if (pos != unit->m_pos) { float oldAmpRight = amp; float oldAmpLeft = 1.f - amp; pos = sc_clip(pos, -1.f, 1.f); float nextAmpRight = pos * 0.5f + 0.5f; float nextAmpLeft = 1.f - nextAmpRight; float leftSlope = CALCSLOPE(nextAmpLeft, oldAmpLeft); float rightSlope = CALCSLOPE(nextAmpRight, oldAmpRight); unit->m_amp = nextAmpRight; unit->m_pos = pos; nova::mix_vec_simd(OUT(0), IN(0), nova::slope_argument(oldAmpLeft, leftSlope), IN(1), nova::slope_argument(oldAmpRight, rightSlope), inNumSamples); } else nova::mix_vec_simd(OUT(0), IN(0), 1.f - amp, IN(1), amp, inNumSamples); } #endif void LinXFade2_Ctor(LinXFade2* unit) { switch (INRATE(2)) { case calc_FullRate: SETCALC(LinXFade2_next_a); break; case calc_BufRate: #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(LinXFade2_next_k_nova); else SETCALC(LinXFade2_next_k); #else SETCALC(LinXFade2_next_k); #endif break; case calc_ScalarRate: #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(LinXFade2_next_i_nova); else SETCALC(LinXFade2_next_i); #else SETCALC(LinXFade2_next_i); #endif break; } unit->m_pos = ZIN0(2); unit->m_pos = sc_clip(unit->m_pos, -1.f, 1.f); unit->m_amp = unit->m_pos * 0.5f + 0.5f; LinXFade2_next_a(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Pan2_next_ak(Pan2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* in = ZIN(0); float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; LOOP1(inNumSamples, float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp; leftamp += leftampslope; rightamp += rightampslope;); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else { LOOP1(inNumSamples, float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp;); } } #ifdef NOVA_SIMD void Pan2_next_ak_nova(Pan2* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::pan2_vec_simd(OUT(0), OUT(1), IN(0), leftamp, leftampslope, rightamp, rightampslope, inNumSamples); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::pan2_vec_simd(OUT(0), OUT(1), IN(0), leftamp, rightamp, inNumSamples); } void Pan2_next_ak_nova_64(Pan2* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float leftamp = unit->m_leftamp; float rightamp = unit->m_rightamp; if (pos != unit->m_pos || unit->m_level != level) { int32 ipos = (int32)(1024.f * pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float nextleftamp = level * ft->mSine[2048 - ipos]; float nextrightamp = level * ft->mSine[ipos]; float slopeFactor = unit->mRate->mSlopeFactor; float leftampslope = (nextleftamp - leftamp) * slopeFactor; float rightampslope = (nextrightamp - rightamp) * slopeFactor; nova::pan2_vec_simd<64>(OUT(0), OUT(1), IN(0), leftamp, leftampslope, rightamp, rightampslope); unit->m_pos = pos; unit->m_level = level; unit->m_leftamp = nextleftamp; unit->m_rightamp = nextrightamp; } else nova::pan2_vec_simd<64>(OUT(0), OUT(1), IN(0), leftamp, rightamp); } #endif void Pan2_next_aa(Pan2* unit, int inNumSamples) { float* leftout = ZOUT(0); float* rightout = ZOUT(1); float* in = ZIN(0); float* pos = ZIN(1); float nextlevel = ZIN0(2); float level = unit->m_level; if (level != nextlevel) { float levelSlope = (nextlevel - level) * unit->mRate->mSlopeFactor; LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * ft->mSine[2048 - ipos]; float rightamp = level * ft->mSine[ipos]; float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp; level += levelSlope;); unit->m_level = level; } else { LOOP1(inNumSamples, int32 ipos = (int32)(1024.f * ZXP(pos) + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); float leftamp = level * ft->mSine[2048 - ipos]; float rightamp = level * ft->mSine[ipos]; float zin = ZXP(in); ZXP(leftout) = zin * leftamp; ZXP(rightout) = zin * rightamp;); } } void Pan2_Ctor(Pan2* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(Pan2_next_aa); } else { #if defined(NOVA_SIMD) if (BUFLENGTH == 64) SETCALC(Pan2_next_ak_nova_64); if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Pan2_next_ak_nova); else SETCALC(Pan2_next_ak); #else SETCALC(Pan2_next_ak); #endif } unit->m_pos = ZIN0(1); unit->m_level = ZIN0(2); int32 ipos = (int32)(1024.f * unit->m_pos + 1024.f + 0.5f); ipos = sc_clip(ipos, 0, 2048); unit->m_leftamp = unit->m_level * ft->mSine[2048 - ipos]; unit->m_rightamp = unit->m_level * ft->mSine[ipos]; Pan2_next_aa(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Pan4_Ctor(Pan4* unit) { SETCALC(Pan4_next); // float *in = ZIN(0); float xpos = ZIN0(1); float ypos = ZIN0(2); float level = ZIN0(3); unit->m_xpos = xpos; unit->m_ypos = ypos; unit->m_level = level; if (xpos < -1.f || xpos > 1.f || ypos < -1.f || ypos > 1.f) { float xabs = fabs(xpos); if (ypos > xabs) { xpos = (xpos + ypos) / ypos - 1.f; ypos = 1.f; } else if (ypos < -xabs) { xpos = (xpos - ypos) / -ypos - 1.f; ypos = -1.f; } else { float yabs = fabs(ypos); if (yabs < xpos) { ypos = (ypos + xpos) / xpos - 1.f; xpos = 1.f; } else { ypos = (ypos - xpos) / -xpos - 1.f; xpos = -1.f; } } } int32 ixpos = (int32)(1024.f * xpos + 1024.f + 0.5f); ixpos = sc_clip(ixpos, 0, 2048); float leftamp = ft->mSine[2048 - ixpos]; float rightamp = ft->mSine[ixpos]; int32 iypos = (int32)(1024.f * ypos + 1024.f + 0.5f); iypos = sc_clip(iypos, 0, 2048); float frontamp = ft->mSine[iypos]; float backamp = ft->mSine[2048 - iypos]; frontamp *= level; backamp *= level; unit->m_LF_amp = leftamp * frontamp; unit->m_RF_amp = rightamp * frontamp; unit->m_LB_amp = leftamp * backamp; unit->m_RB_amp = rightamp * backamp; float z = ZIN0(0); ZOUT0(0) = z * unit->m_LF_amp; ZOUT0(1) = z * unit->m_RF_amp; ZOUT0(2) = z * unit->m_LB_amp; ZOUT0(3) = z * unit->m_RB_amp; } void Pan4_next(Pan4* unit, int inNumSamples) { float* LFout = ZOUT(0); float* RFout = ZOUT(1); float* LBout = ZOUT(2); float* RBout = ZOUT(3); float* in = ZIN(0); float xpos = ZIN0(1); float ypos = ZIN0(2); float level = ZIN0(3); float LF_amp = unit->m_LF_amp; float RF_amp = unit->m_RF_amp; float LB_amp = unit->m_LB_amp; float RB_amp = unit->m_RB_amp; if (xpos != unit->m_xpos || ypos != unit->m_ypos || level != unit->m_level) { unit->m_xpos = xpos; unit->m_ypos = ypos; unit->m_level = level; if (xpos < -1.f || xpos > 1.f || ypos < -1.f || ypos > 1.f) { float xabs = fabs(xpos); if (ypos > xabs) { xpos = (xpos + ypos) / ypos - 1.f; ypos = 1.f; } else if (ypos < -xabs) { xpos = (xpos - ypos) / -ypos - 1.f; ypos = -1.f; } else { float yabs = fabs(ypos); if (yabs < xpos) { ypos = (ypos + xpos) / xpos - 1.f; xpos = 1.f; } else { ypos = (ypos - xpos) / -xpos - 1.f; xpos = -1.f; } } } int32 ixpos = (int32)(1024.f * xpos + 1024.f + 0.5f); ixpos = sc_clip(ixpos, 0, 2048); float leftamp = ft->mSine[2048 - ixpos]; float rightamp = ft->mSine[ixpos]; int32 iypos = (int32)(1024.f * ypos + 1024.f + 0.5f); iypos = sc_clip(iypos, 0, 2048); float frontamp = ft->mSine[iypos]; float backamp = ft->mSine[2048 - iypos]; frontamp *= level; backamp *= level; float next_LF_amp = leftamp * frontamp; float next_RF_amp = rightamp * frontamp; float next_LB_amp = leftamp * backamp; float next_RB_amp = rightamp * backamp; float LF_slope = CALCSLOPE(next_LF_amp, LF_amp); float RF_slope = CALCSLOPE(next_RF_amp, RF_amp); float LB_slope = CALCSLOPE(next_LB_amp, LB_amp); float RB_slope = CALCSLOPE(next_RB_amp, RB_amp); LOOP1(inNumSamples, float z = ZXP(in); ZXP(LFout) = z * LF_amp; ZXP(RFout) = z * RF_amp; ZXP(LBout) = z * LB_amp; ZXP(RBout) = z * RB_amp; LF_amp += LF_slope; RF_amp += RF_slope; LB_amp += LB_slope; RB_amp += RB_slope;); unit->m_LF_amp = LF_amp; unit->m_RF_amp = RF_amp; unit->m_LB_amp = LB_amp; unit->m_RB_amp = RB_amp; } else { LOOP1(inNumSamples, float z = ZXP(in); ZXP(LFout) = z * LF_amp; ZXP(RFout) = z * RF_amp; ZXP(LBout) = z * LB_amp; ZXP(RBout) = z * RB_amp;); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PanB_Ctor(PanB* unit) { SETCALC(PanB_next); float azimuth = unit->m_azimuth = ZIN0(1); float elevation = unit->m_elevation = ZIN0(2); float level = unit->m_level = ZIN0(3); int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; long iazimuth = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); long ielevation = kSineMask & (long)(elevation * (float)(kSineSize >> 2)); float sina = -ft->mSine[iazimuth]; float sinb = ft->mSine[ielevation]; iazimuth = kSineMask & (iazimuth + (kSineSize >> 2)); ielevation = kSineMask & (ielevation + (kSineSize >> 2)); float cosa = ft->mSine[iazimuth]; float cosb = ft->mSine[ielevation]; unit->m_W_amp = rsqrt2_f * level; unit->m_X_amp = cosa * cosb * level; unit->m_Y_amp = sina * cosb * level; unit->m_Z_amp = sinb * level; PanB_next(unit, 1); } void PanB_next(PanB* unit, int inNumSamples) { float* Wout = ZOUT(0); float* Xout = ZOUT(1); float* Yout = ZOUT(2); float* Zout = ZOUT(3); float* in = ZIN(0); float azimuth = ZIN0(1); float elevation = ZIN0(2); float level = ZIN0(3); float W_amp = unit->m_W_amp; float X_amp = unit->m_X_amp; float Y_amp = unit->m_Y_amp; float Z_amp = unit->m_Z_amp; int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; if (azimuth != unit->m_azimuth || elevation != unit->m_elevation || level != unit->m_level) { unit->m_azimuth = azimuth; unit->m_elevation = elevation; unit->m_level = level; long iazimuth = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); long ielevation = kSineMask & (long)(elevation * (float)(kSineSize >> 2)); float sina = -ft->mSine[iazimuth]; float sinb = ft->mSine[ielevation]; iazimuth = kSineMask & (iazimuth + (kSineSize >> 2)); ielevation = kSineMask & (ielevation + (kSineSize >> 2)); float cosa = ft->mSine[iazimuth]; float cosb = ft->mSine[ielevation]; float next_W_amp = rsqrt2_f * level; float next_X_amp = cosa * cosb * level; float next_Y_amp = sina * cosb * level; float next_Z_amp = sinb * level; float W_slope = CALCSLOPE(next_W_amp, W_amp); float X_slope = CALCSLOPE(next_X_amp, X_amp); float Y_slope = CALCSLOPE(next_Y_amp, Y_amp); float Z_slope = CALCSLOPE(next_Z_amp, Z_amp); LOOP1(inNumSamples, float z = ZXP(in); ZXP(Wout) = z * W_amp; ZXP(Xout) = z * X_amp; ZXP(Yout) = z * Y_amp; ZXP(Zout) = z * Z_amp; W_amp += W_slope; X_amp += X_slope; Y_amp += Y_slope; Z_amp += Z_slope;); unit->m_W_amp = W_amp; unit->m_X_amp = X_amp; unit->m_Y_amp = Y_amp; unit->m_Z_amp = Z_amp; } else { LOOP1(inNumSamples, float z = ZXP(in); ZXP(Wout) = z * W_amp; ZXP(Xout) = z * X_amp; ZXP(Yout) = z * Y_amp; ZXP(Zout) = z * Z_amp;); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PanB2_next(PanB2* unit, int inNumSamples) { float* Wout = ZOUT(0); float* Xout = ZOUT(1); float* Yout = ZOUT(2); float* in = ZIN(0); float azimuth = ZIN0(1); float level = ZIN0(2); float W_amp = unit->m_W_amp; float X_amp = unit->m_X_amp; float Y_amp = unit->m_Y_amp; int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; if (azimuth != unit->m_azimuth || level != unit->m_level) { unit->m_azimuth = azimuth; unit->m_level = level; long isinpos = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); float sina = -ft->mSine[isinpos]; long icospos = kSineMask & (isinpos + (kSineSize >> 2)); float cosa = ft->mSine[icospos]; float next_W_amp = rsqrt2_f * level; float next_X_amp = cosa * level; float next_Y_amp = sina * level; float W_slope = CALCSLOPE(next_W_amp, W_amp); float X_slope = CALCSLOPE(next_X_amp, X_amp); float Y_slope = CALCSLOPE(next_Y_amp, Y_amp); LOOP1(inNumSamples, float z = ZXP(in); ZXP(Wout) = z * W_amp; ZXP(Xout) = z * X_amp; ZXP(Yout) = z * Y_amp; W_amp += W_slope; X_amp += X_slope; Y_amp += Y_slope;); unit->m_W_amp = W_amp; unit->m_X_amp = X_amp; unit->m_Y_amp = Y_amp; } else { LOOP1(inNumSamples, float z = ZXP(in); ZXP(Wout) = z * W_amp; ZXP(Xout) = z * X_amp; ZXP(Yout) = z * Y_amp;); } } #ifdef NOVA_SIMD FLATTEN void PanB2_next_nova(PanB2* unit, int inNumSamples) { float* Wout = OUT(0); float* Xout = OUT(1); float* Yout = OUT(2); float* in = IN(0); float azimuth = ZIN0(1); float level = ZIN0(2); float W_amp = unit->m_W_amp; float X_amp = unit->m_X_amp; float Y_amp = unit->m_Y_amp; int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; if (azimuth != unit->m_azimuth || level != unit->m_level) { unit->m_azimuth = azimuth; unit->m_level = level; long isinpos = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); float sina = -ft->mSine[isinpos]; long icospos = kSineMask & (isinpos + (kSineSize >> 2)); float cosa = ft->mSine[icospos]; float next_W_amp = rsqrt2_f * level; float next_X_amp = cosa * level; float next_Y_amp = sina * level; float W_slope = CALCSLOPE(next_W_amp, W_amp); float X_slope = CALCSLOPE(next_X_amp, X_amp); float Y_slope = CALCSLOPE(next_Y_amp, Y_amp); nova::times_vec_simd(Wout, in, slope_argument(W_amp, W_slope), inNumSamples); nova::times_vec_simd(Xout, in, slope_argument(X_amp, X_slope), inNumSamples); nova::times_vec_simd(Yout, in, slope_argument(Y_amp, Y_slope), inNumSamples); unit->m_W_amp = next_W_amp; unit->m_X_amp = next_X_amp; unit->m_Y_amp = next_Y_amp; } else { // TODO: can be further optimized by joining the loops nova::times_vec_simd(Wout, in, W_amp, inNumSamples); nova::times_vec_simd(Xout, in, X_amp, inNumSamples); nova::times_vec_simd(Yout, in, Y_amp, inNumSamples); } } #endif void PanB2_Ctor(PanB2* unit) { #if defined(NOVA_SIMD) if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(PanB2_next_nova); else #endif SETCALC(PanB2_next); float azimuth = unit->m_azimuth = ZIN0(1); float level = unit->m_level = ZIN0(2); int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; long isinpos = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); float sina = -ft->mSine[isinpos]; long icospos = kSineMask & (isinpos + (kSineSize >> 2)); float cosa = ft->mSine[icospos]; unit->m_W_amp = rsqrt2_f * level; unit->m_X_amp = cosa * level; unit->m_Y_amp = sina * level; PanB2_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BiPanB2_next(BiPanB2* unit, int inNumSamples) { float* Wout = ZOUT(0); float* Xout = ZOUT(1); float* Yout = ZOUT(2); float* inA = ZIN(0); float* inB = ZIN(1); float azimuth = ZIN0(2); float level = ZIN0(3); float W_amp = unit->m_W_amp; float X_amp = unit->m_X_amp; float Y_amp = unit->m_Y_amp; int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; if (azimuth != unit->m_azimuth || level != unit->m_level) { unit->m_azimuth = azimuth; unit->m_level = level; long isinpos = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); float sina = -ft->mSine[isinpos]; long icospos = kSineMask & (isinpos + (kSineSize >> 2)); float cosa = ft->mSine[icospos]; float next_W_amp = rsqrt2_f * level; float next_X_amp = cosa * level; float next_Y_amp = sina * level; float W_slope = CALCSLOPE(next_W_amp, W_amp); float X_slope = CALCSLOPE(next_X_amp, X_amp); float Y_slope = CALCSLOPE(next_Y_amp, Y_amp); if (W_slope == 0.f) { LOOP1(inNumSamples, float a = ZXP(inA); float b = ZXP(inB); float abdiff = a - b; ZXP(Wout) = (a + b) * W_amp; ZXP(Xout) = abdiff * X_amp; ZXP(Yout) = abdiff * Y_amp; X_amp += X_slope; Y_amp += Y_slope;); } else { LOOP1(inNumSamples, float a = ZXP(inA); float b = ZXP(inB); float abdiff = a - b; ZXP(Wout) = (a + b) * W_amp; ZXP(Xout) = abdiff * X_amp; ZXP(Yout) = abdiff * Y_amp; W_amp += W_slope; X_amp += X_slope; Y_amp += Y_slope;); unit->m_W_amp = W_amp; } unit->m_X_amp = X_amp; unit->m_Y_amp = Y_amp; } else { LOOP1(inNumSamples, float a = ZXP(inA); float b = ZXP(inB); float abdiff = a - b; ZXP(Wout) = (a + b) * W_amp; ZXP(Xout) = abdiff * X_amp; ZXP(Yout) = abdiff * Y_amp;); } } void BiPanB2_Ctor(BiPanB2* unit) { SETCALC(BiPanB2_next); float azimuth = unit->m_azimuth = ZIN0(2); float level = unit->m_level = ZIN0(3); int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; long iazimuth = kSineMask & (long)(azimuth * (float)(kSineSize >> 1)); float sina = -ft->mSine[iazimuth]; iazimuth = kSineMask & (iazimuth + (kSineSize >> 2)); float cosa = ft->mSine[iazimuth]; unit->m_W_amp = rsqrt2_f * level; unit->m_X_amp = cosa * level; unit->m_Y_amp = sina * level; BiPanB2_next(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// /* void calcPos(float pos, int numOutputs, float width, float orientation) { float rwidth = 1.f / width; float range = numOutputs * rwidth; float rrange = 1.f / range; float zpos = pos * 0.5 * numOutputs + width * 0.5 + orientation; Print("pos %6.2g rwidth %6.3g range %6.3g rrange %6.3g zpos %6.3g\n", pos, rwidth, range, rrange, zpos); for (int i=0; i<numOutputs; ++i) { float amp; float chanpos = zpos - i; chanpos *= rwidth; float zchanpos = chanpos - range * floor(rrange * chanpos); if (zchanpos > 1.f) { amp = 0.f; } else { amp = ft->mSine[(long)(4096.f * zchanpos)]; } Print(" %d chanpos %6.3g zchanpos %6.3g amp %g\n", i, chanpos, zchanpos, amp); } } */ #ifdef NOVA_SIMD void PanAz_next_ak_nova(PanAz* unit, int inNumSamples); #endif void PanAz_Ctor(PanAz* unit) { unit->m_chanamp = nullptr; if (INRATE(1) == calc_FullRate) { SETCALC(PanAz_next_aa); PanAz_next_aa(unit, 1); } else { int numOutputs = unit->mNumOutputs; for (int i = 0; i < numOutputs; ++i) ZOUT0(i) = 0.f; unit->m_chanamp = (float*)RTAlloc(unit->mWorld, numOutputs * sizeof(float)); ClearUnitIfMemFailed(unit->m_chanamp); std::fill_n(unit->m_chanamp, numOutputs, 0); #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(PanAz_next_ak_nova); else SETCALC(PanAz_next_ak); #else SETCALC(PanAz_next_ak); #endif PanAz_next_ak(unit, 1); } } void PanAz_Dtor(PanAz* unit) { if (unit->m_chanamp) RTFree(unit->mWorld, unit->m_chanamp); } void PanAz_next_ak(PanAz* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float width = std::abs(ZIN0(3)); float orientation = ZIN0(4); int numOutputs = unit->mNumOutputs; float rwidth = static_cast<float>(sc_reciprocal(static_cast<double>(width))); float range = numOutputs * rwidth; float rrange = static_cast<float>(sc_reciprocal(static_cast<double>(range))); pos = pos * 0.5f * numOutputs + width * 0.5f + orientation; float* zin0 = ZIN(0); for (int i = 0; i < numOutputs; ++i) { float* out = ZOUT(i); float nextchanamp; float chanpos = pos - i; chanpos *= rwidth; chanpos = chanpos - range * sc_floor(rrange * chanpos); if (chanpos >= 1.f) { nextchanamp = 0.f; } else { nextchanamp = level * ft->mSine[(long)(4096.f * chanpos)]; } float chanamp = unit->m_chanamp[i]; if (nextchanamp == chanamp) { if (nextchanamp == 0.f) { ZClear(inNumSamples, out); } else { float* in = zin0; LOOP1(inNumSamples, ZXP(out) = ZXP(in) * chanamp;) } } else { float chanampslope = CALCSLOPE(nextchanamp, chanamp); float* in = zin0; LOOP1(inNumSamples, ZXP(out) = ZXP(in) * chanamp; chanamp += chanampslope;) unit->m_chanamp[i] = nextchanamp; } } } #ifdef NOVA_SIMD FLATTEN void PanAz_next_ak_nova(PanAz* unit, int inNumSamples) { float pos = ZIN0(1); float level = ZIN0(2); float width = std::abs(ZIN0(3)); float orientation = ZIN0(4); int numOutputs = unit->mNumOutputs; float rwidth = static_cast<float>(sc_reciprocal(static_cast<double>(width))); float range = numOutputs * rwidth; float rrange = static_cast<float>(sc_reciprocal(static_cast<double>(range))); pos = pos * 0.5f * numOutputs + width * 0.5f + orientation; float* __restrict__ in = IN(0); float* __restrict__ chanamps = unit->m_chanamp; for (int i = 0; i < numOutputs; ++i) { float chanamp = chanamps[i]; float nextchanamp; float chanpos = pos - i; chanpos *= rwidth; chanpos = chanpos - range * sc_floor(rrange * chanpos); if (chanpos >= 1.f) { nextchanamp = 0.f; } else { nextchanamp = level * ft->mSine[(long)(4096.f * chanpos)]; } float* out = OUT(i); if (nextchanamp == chanamp) { if (nextchanamp == 0.f) nova::zerovec_simd(out, inNumSamples); else nova::times_vec_simd(out, in, chanamp, inNumSamples); } else { float chanampslope = CALCSLOPE(nextchanamp, chanamp); nova::times_vec_simd(out, in, slope_argument(chanamp, chanampslope), inNumSamples); chanamps[i] = nextchanamp; } } } #endif void PanAz_next_aa(PanAz* unit, int inNumSamples) { float level = ZIN0(2); float width = std::abs(ZIN0(3)); float orientation = ZIN0(4); int numOutputs = unit->mNumOutputs; float rwidth = static_cast<float>(sc_reciprocal(static_cast<double>(width))); float range = numOutputs * rwidth; float rrange = static_cast<float>(sc_reciprocal(static_cast<double>(range))); // compute constant parts with which the pos has to be multiplied/added to respect numOutputs, width and orientation // see PanAz_next_ak for details float alignedPosFac = 0.5f * numOutputs; float alignedPosConst = width * 0.5f + orientation; float* zin0 = ZIN(0); float* pos = ZIN(1); for (int i = 0; i < numOutputs; ++i) { float* out = ZOUT(i); float* in = zin0; float* thePos = pos; LOOP1( inNumSamples, float chanpos = ((ZXP(thePos) * alignedPosFac + alignedPosConst) - i) * rwidth; chanpos = chanpos - range * sc_floor(rrange * chanpos); float chanamp; if (chanpos >= 1.f) { chanamp = 0.f; } else { chanamp = level * ft->mSine[(long)(4096.f * chanpos)]; } ZXP(out) = ZXP(in) * chanamp; ) } } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// void Rotate2_next_ak(Rotate2* unit, int inNumSamples) { float* xout = ZOUT(0); float* yout = ZOUT(1); float* xin = ZIN(0); float* yin = ZIN(1); float pos = ZIN0(2); float sint = unit->m_sint; float cost = unit->m_cost; if (pos != unit->m_pos) { int kSineSize = ft->mSineSize; int kSineMask = kSineSize - 1; int32 isinpos = kSineMask & (int32)(pos * (float)(kSineSize >> 1)); int32 icospos = kSineMask & ((kSineSize >> 2) + isinpos); float nextsint = unit->m_sint = ft->mSine[isinpos]; float nextcost = unit->m_cost = ft->mSine[icospos]; float slopeFactor = unit->mRate->mSlopeFactor; float sinslope = (nextsint - sint) * slopeFactor; float cosslope = (nextcost - cost) * slopeFactor; LOOP1(inNumSamples, float x = ZXP(xin); float y = ZXP(yin); ZXP(xout) = cost * x + sint * y; ZXP(yout) = cost * y - sint * x; sint += sinslope; cost += cosslope;); unit->m_pos = pos; } else { LOOP1(inNumSamples, float x = ZXP(xin); float y = ZXP(yin); ZXP(xout) = cost * x + sint * y; ZXP(yout) = cost * y - sint * x;); } } void Rotate2_Ctor(Rotate2* unit) { SETCALC(Rotate2_next_ak); unit->m_pos = ZIN0(2); int32 isinpos = 8191 & (int32)(4096.f * unit->m_pos); int32 icospos = 8191 & (2048 + isinpos); unit->m_sint = ft->mSine[isinpos]; unit->m_cost = ft->mSine[icospos]; Rotate2_next_ak(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DecodeB2_Ctor(DecodeB2* unit) { #if defined(NOVA_SIMD) if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(DecodeB2_next_nova); else #endif SETCALC(DecodeB2_next); DecodeB2_next(unit, 1); float orientation = ZIN0(3); int numOutputs = unit->mNumOutputs; float angle = twopi_f / numOutputs; unit->m_cosa = cos(angle); unit->m_sina = sin(angle); unit->m_W_amp = 0.7071067811865476f; unit->m_X_amp = 0.5f * (float)cos(orientation * angle); unit->m_Y_amp = 0.5f * (float)sin(orientation * angle); } void DecodeB2_next(DecodeB2* unit, int inNumSamples) { float* Win0 = ZIN(0); float* Xin0 = ZIN(1); float* Yin0 = ZIN(2); float W_amp = unit->m_W_amp; float X_amp = unit->m_X_amp; float Y_amp = unit->m_Y_amp; float X_tmp; float cosa = unit->m_cosa; float sina = unit->m_sina; int numOutputs = unit->mNumOutputs; for (int i = 0; i < numOutputs; ++i) { float* out = ZOUT(i); float* Win = Win0; float* Xin = Xin0; float* Yin = Yin0; LOOP1(inNumSamples, ZXP(out) = ZXP(Win) * W_amp + ZXP(Xin) * X_amp + ZXP(Yin) * Y_amp;); X_tmp = X_amp * cosa + Y_amp * sina; Y_amp = Y_amp * cosa - X_amp * sina; X_amp = X_tmp; } } #ifdef NOVA_SIMD void DecodeB2_next_nova(DecodeB2* unit, int inNumSamples) { float* Win0 = IN(0); float* Xin0 = IN(1); float* Yin0 = IN(2); using namespace nova; vec<float> W_amp = unit->m_W_amp; vec<float> X_amp = unit->m_X_amp; vec<float> Y_amp = unit->m_Y_amp; vec<float> X_tmp; vec<float> cosa = unit->m_cosa; vec<float> sina = unit->m_sina; int numOutputs = unit->mNumOutputs; int vs = vec<float>::size; int loops = inNumSamples / vs; for (int i = 0; i < numOutputs; ++i) { float* out = OUT(i); float* Win = Win0; float* Xin = Xin0; float* Yin = Yin0; for (int j = 0; j != loops; ++j) { vec<float> result, w, x, y; w.load_aligned(Win); x.load_aligned(Xin); y.load_aligned(Yin); result = w * W_amp + x * X_amp + y * Y_amp; result.store_aligned(out); out += vs; Win += vs; Xin += vs; Yin += vs; }; X_tmp = X_amp * cosa + Y_amp * sina; Y_amp = Y_amp * cosa - X_amp * sina; X_amp = X_tmp; } } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Pan) { ft = inTable; DefineSimpleUnit(Pan2); DefineSimpleUnit(Pan4); DefineSimpleUnit(LinPan2); DefineSimpleCantAliasUnit(Balance2); DefineSimpleUnit(Rotate2); DefineSimpleUnit(XFade2); DefineSimpleUnit(LinXFade2); DefineSimpleUnit(PanB); DefineSimpleCantAliasUnit(PanB2); DefineSimpleUnit(BiPanB2); DefineDtorCantAliasUnit(PanAz); DefineSimpleCantAliasUnit(DecodeB2); } //////////////////////////////////////////////////////////////////////////////////////////////////
53,353
C++
.cpp
1,288
34.687112
120
0.57652
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
29,943
DiskIO_UGens.cpp
supercollider_supercollider/server/plugins/DiskIO_UGens.cpp
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. Copyright (c) 2009 Marije Baalman Copyright (c) 2008 Scott Wilson Copyright (c) 2012 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 */ #include "SC_SyncCondition.h" #include "SC_PlugIn.h" #include <sndfile.h> #include <atomic> #include <new> #include <functional> #include <SC_Lock.h> #include <boost/lockfree/queue.hpp> #include <boost/lockfree/spsc_queue.hpp> static InterfaceTable* ft; enum { diskinIdle, diskinStartingEmpty, diskinStartingFull, diskinNormal, diskinLastBuffer, diskinEndSilence }; enum { diskoutIdle, diskoutNormal }; struct DiskIn : public Unit { float m_fbufnum; SndBuf* m_buf; uint32 m_framepos; }; struct DiskOut : public Unit { float m_fbufnum; SndBuf* m_buf; uint32 m_framepos; uint32 m_framewritten; }; struct VDiskIn : public Unit { float m_fbufnum, m_pchRatio, m_rBufSize; double m_framePos, m_bufPos; uint32 m_count; SndBuf* m_buf; uint32 m_iFramePos, m_iBufPos; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void DiskIn_next(DiskIn* unit, int inNumSamples); void DiskIn_Ctor(DiskIn* unit); void DiskOut_next(DiskOut* unit, int inNumSamples); void DiskOut_Ctor(DiskOut* unit); void DiskOut_Dtor(DiskOut* unit); void VDiskIn_next(VDiskIn* unit, int inNumSamples); void VDiskIn_first(VDiskIn* unit, int inNumSamples); void VDiskIn_next_rate1(VDiskIn* unit, int inNumSamples); void VDiskIn_Ctor(VDiskIn* unit); } ////////////////////////////////////////////////////////////////////////////////////////////////// enum { kDiskCmd_Read, kDiskCmd_Write, kDiskCmd_ReadLoop, }; namespace { struct DiskIOMsg { World* mWorld; int16 mCommand; int16 mChannels; int32 mBufNum; int32 mPos; int32 mFrames; void Perform(); }; void DiskIOMsg::Perform() { NRTLock(mWorld); SndBuf* buf = World_GetNRTBuf(mWorld, mBufNum); if (mPos > buf->frames || mPos + mFrames > buf->frames || buf->channels != mChannels) goto leave; sf_count_t count; switch (mCommand) { case kDiskCmd_Read: count = buf->sndfile ? sf_readf_float(GETSNDFILE(buf), buf->data + mPos * buf->channels, mFrames) : 0; if (count < mFrames) { memset(buf->data + (mPos + count) * buf->channels, 0, (mFrames - count) * buf->channels * sizeof(float)); World_GetBuf(mWorld, mBufNum)->mask = mPos + count; // NOTE: Possible race condition above: The disk IO thread may write to the rt SndBuf // while the stage3 of the sequenced commands copies the non-rt SndBuf struct to the rt buf. // This only happens if the buffer is modified via an osc command. // We can't use the non-rt SndBuf above since buf->mask won't be reflected to the rt buf. } break; case kDiskCmd_ReadLoop: if (!buf->sndfile) { memset(buf->data + mPos * buf->channels, 0, mFrames * buf->channels * sizeof(float)); goto leave; } count = sf_readf_float(GETSNDFILE(buf), buf->data + mPos * buf->channels, mFrames); while (mFrames -= count) { sf_seek(GETSNDFILE(buf), 0, SEEK_SET); count = sf_readf_float(GETSNDFILE(buf), buf->data + (mPos + count) * buf->channels, mFrames); } break; case kDiskCmd_Write: // printf("kDiskCmd_Write %d %p\n", mBufNum, buf->sndfile); if (!buf->sndfile) goto leave; count = sf_writef_float(GETSNDFILE(buf), buf->data + mPos * buf->channels, mFrames); break; } leave: NRTUnlock(mWorld); } struct DiskIOThread { SC_SyncCondition mDiskFifoHasData; #ifdef SUPERNOVA boost::lockfree::queue<DiskIOMsg, boost::lockfree::capacity<256>> mDiskFifo; #else boost::lockfree::spsc_queue<DiskIOMsg, boost::lockfree::capacity<256>> mDiskFifo; #endif std::atomic<bool> mRunning; SC_Thread mThread; DiskIOThread(): mRunning(false) {} ~DiskIOThread() { if (mRunning) { mRunning.store(false); mDiskFifoHasData.Signal(); mThread.join(); } } void launchThread() { using namespace std; mRunning.store(true); mThread = thread(bind(&DiskIOThread::ioThreadFunc, this)); } bool Write(DiskIOMsg& data) { bool pushSucceeded = mDiskFifo.push(data); if (pushSucceeded) mDiskFifoHasData.Signal(); return pushSucceeded; } void ioThreadFunc() { while (mRunning.load()) { mDiskFifoHasData.WaitEach(); DiskIOMsg msg; bool popSucceeded = mDiskFifo.pop(msg); if (popSucceeded) msg.Perform(); } } }; DiskIOThread* gDiskIO; } ////////////////////////////////////////////////////////////////////////////////////////////////// #define SETUP_OUT(offset) \ if (unit->mNumOutputs != bufChannels) { \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } \ float* const* const out = &OUT(offset); #define SETUP_IN(offset) \ if (unit->mNumInputs - (uint32)offset != bufChannels) { \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } \ const float* const* const in = &IN(offset); void DiskIn_Ctor(DiskIn* unit) { unit->m_fbufnum = -1.f; unit->m_buf = unit->mWorld->mSndBufs; unit->m_framepos = 0; SETCALC(DiskIn_next); ClearUnitOutputs(unit, 1); } void DiskIn_next(DiskIn* unit, int inNumSamples) { GET_BUF_SHARED if (!bufData || ((bufFrames & ((unit->mWorld->mBufLength << 1) - 1)) != 0)) { unit->m_framepos = 0; ClearUnitOutputs(unit, inNumSamples); return; } SETUP_OUT(0) if (unit->m_framepos >= bufFrames) { unit->m_framepos = 0; } bufData += unit->m_framepos * bufChannels; // buffer must be allocated as a multiple of 2*blocksize. if (bufChannels > 2) { for (int j = 0; j < inNumSamples; ++j) { for (uint32 i = 0; i < bufChannels; ++i) out[i][j] = *bufData++; } } else if (bufChannels == 2) { float* out0 = out[0]; float* out1 = out[1]; for (int j = 0; j < inNumSamples; ++j) { out0[j] = *bufData++; out1[j] = *bufData++; } } else { float* out0 = out[0]; for (int j = 0; j < inNumSamples; ++j) { out0[j] = *bufData++; } } if (unit->m_buf->mask1 >= 0 && unit->m_framepos >= unit->m_buf->mask1) unit->mDone = true; unit->m_framepos += inNumSamples; uint32 bufFrames2 = bufFrames >> 1; if (unit->m_framepos == bufFrames) { unit->m_framepos = 0; goto sendMessage; } else if (unit->m_framepos == bufFrames2) { sendMessage: if (unit->m_buf->mask >= 0) unit->m_buf->mask1 = unit->m_buf->mask; if (unit->mWorld->mRealTime) { // send a message to read DiskIOMsg msg; msg.mWorld = unit->mWorld; msg.mCommand = (int)ZIN0(1) ? kDiskCmd_ReadLoop : kDiskCmd_Read; msg.mBufNum = (int)fbufnum; msg.mPos = bufFrames2 - unit->m_framepos; msg.mFrames = bufFrames2; msg.mChannels = bufChannels; gDiskIO->Write(msg); } else { SndBuf* bufr = World_GetNRTBuf(unit->mWorld, (int)fbufnum); uint32 mPos = bufFrames2 - unit->m_framepos; if (mPos > (uint32)bufr->frames || mPos + bufFrames2 > (uint32)bufr->frames || (uint32)bufr->channels != bufChannels) return; sf_count_t count; if ((int)ZIN0(1)) { // loop if (!bufr->sndfile) memset(bufr->data + mPos * bufr->channels, 0, bufFrames2 * bufr->channels * sizeof(float)); count = sf_readf_float(GETSNDFILE(bufr), bufr->data + mPos * bufr->channels, bufFrames2); while (bufFrames2 -= count) { sf_seek(GETSNDFILE(bufr), 0, SEEK_SET); count = sf_readf_float(GETSNDFILE(bufr), bufr->data + (mPos + count) * bufr->channels, bufFrames2); } } else { // non-loop count = bufr->sndfile ? sf_readf_float(GETSNDFILE(bufr), bufr->data + mPos * bufr->channels, bufFrames2) : 0; if (count < bufFrames2) { memset(bufr->data + (mPos + count) * bufr->channels, 0, (bufFrames2 - count) * bufr->channels * sizeof(float)); unit->m_buf->mask = mPos + count; } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DiskOut_Ctor(DiskOut* unit) { unit->m_fbufnum = -1.f; unit->m_buf = unit->mWorld->mSndBufs; unit->m_framepos = 0; unit->m_framewritten = 0; SETCALC(DiskOut_next); ClearUnitOutputs(unit, 1); } void DiskOut_next(DiskOut* unit, int inNumSamples) { GET_BUF if (!bufData || ((bufFrames & ((unit->mWorld->mBufLength << 1) - 1)) != 0)) { unit->m_framepos = 0; // unit->m_framewritten = 0; return; } SETUP_IN(1) float* out = OUT(0); uint32 framew = unit->m_framewritten; // printf("Start frames %i %i\n", unit->m_framewritten, framew ); if (unit->m_framepos >= bufFrames) unit->m_framepos = 0; bufData += unit->m_framepos * bufChannels; if (bufChannels > 2) { for (int j = 0; j < inNumSamples; ++j) { for (uint32 i = 0; i < bufChannels; ++i) *bufData++ = in[i][j]; out[j] = framew++; } } else if (bufChannels == 2) { const float* in0 = in[0]; const float* in1 = in[1]; for (int j = 0; j < inNumSamples; ++j) { *bufData++ = in0[j]; *bufData++ = in1[j]; out[j] = framew++; } } else { const float* in0 = in[0]; for (int j = 0; j < inNumSamples; ++j) { *bufData++ = in0[j]; out[j] = framew++; } } unit->m_framepos += inNumSamples; // unit->m_framewritten += inNumSamples; unit->m_framewritten = framew; // printf("frames %i %i\n", unit->m_framewritten, framew ); uint32 bufFrames2 = bufFrames >> 1; if (unit->m_framepos == bufFrames) { unit->m_framepos = 0; goto sendMessage; } else if (unit->m_framepos == bufFrames2) { sendMessage: // send a message to write DiskIOMsg msg; msg.mWorld = unit->mWorld; msg.mCommand = kDiskCmd_Write; msg.mBufNum = (int)fbufnum; msg.mPos = bufFrames2 - unit->m_framepos; msg.mFrames = bufFrames2; msg.mChannels = bufChannels; // printf("sendMessage %d %d %d %d\n", msg.mBufNum, msg.mPos, msg.mFrames, msg.mChannels); gDiskIO->Write(msg); } } void DiskOut_Dtor(DiskOut* unit) { GET_BUF uint32 framepos = unit->m_framepos; uint32 bufFrames2 = bufFrames >> 1; // check that we didn't just write if (framepos != 0 && framepos != bufFrames2) { // if not write the last chunk of samples uint32 writeStart; if (framepos > bufFrames2) { writeStart = bufFrames2; } else { writeStart = 0; } DiskIOMsg msg; msg.mWorld = unit->mWorld; msg.mCommand = kDiskCmd_Write; msg.mBufNum = (int)fbufnum; msg.mPos = writeStart; msg.mFrames = framepos - writeStart; msg.mChannels = bufChannels; // printf("sendMessage %d %d %d %d\n", msg.mBufNum, msg.mPos, msg.mFrames, msg.mChannels); gDiskIO->Write(msg); } } void VDiskIn_Ctor(VDiskIn* unit) { unit->m_fbufnum = -1.f; unit->m_buf = unit->mWorld->mSndBufs; unit->m_framePos = 0.; unit->m_bufPos = 0.; unit->m_pchRatio = sc_max(IN0(1), 0.f); unit->m_count = 0; unit->m_iFramePos = 0; unit->m_iBufPos = 0; if (INRATE(1) == calc_ScalarRate && (unit->m_pchRatio == 1)) SETCALC(VDiskIn_next_rate1); else SETCALC(VDiskIn_first); ClearUnitOutputs(unit, 1); } static void VDiskIn_request_buffer(VDiskIn* unit, float fbufnum, uint32 bufFrames2, uint32 bufChannels, double bufPos) { if (unit->m_buf->mask >= 0) unit->m_buf->mask1 = unit->m_buf->mask; unit->m_count++; if (unit->mWorld->mRealTime) { DiskIOMsg msg; msg.mWorld = unit->mWorld; msg.mCommand = (int)ZIN0(2) ? kDiskCmd_ReadLoop : kDiskCmd_Read; msg.mBufNum = (int)fbufnum; uint32 thisPos; if ((uint32)bufPos >= bufFrames2) thisPos = 0; else thisPos = bufFrames2; msg.mPos = thisPos; msg.mFrames = bufFrames2; msg.mChannels = bufChannels; gDiskIO->Write(msg); if ((int)ZIN0(3)) { // float outval = bufPos + sc_mod((float)(unit->m_count * bufFrames2), (float)buf->fileinfo.frames); float outval = bufPos + (float)(unit->m_count * bufFrames2); SendNodeReply(&unit->mParent->mNode, (int)ZIN0(3), "/diskin", 1, &outval); } } else { SndBuf* bufr = World_GetNRTBuf(unit->mWorld, (int)fbufnum); uint32 mPos; if ((uint32)bufPos >= bufFrames2) mPos = 0; else mPos = bufFrames2; if (mPos > (uint32)bufr->frames || mPos + bufFrames2 > (uint32)bufr->frames || (uint32)bufr->channels != bufChannels) return; sf_count_t count; if ((int)ZIN0(2)) { // loop if (!bufr->sndfile) memset(bufr->data + mPos * bufr->channels, 0, bufFrames2 * bufr->channels * sizeof(float)); count = sf_readf_float(GETSNDFILE(bufr), bufr->data + mPos * bufr->channels, bufFrames2); while (bufFrames2 -= count) { sf_seek(GETSNDFILE(bufr), 0, SEEK_SET); count = sf_readf_float(GETSNDFILE(bufr), bufr->data + (mPos + count) * bufr->channels, bufFrames2); } } else { // non-loop count = bufr->sndfile ? sf_readf_float(GETSNDFILE(bufr), bufr->data + mPos * bufr->channels, bufFrames2) : 0; if (count < bufFrames2) { memset(bufr->data + (mPos + count) * bufr->channels, 0, (bufFrames2 - count) * bufr->channels * sizeof(float)); unit->m_buf->mask = mPos + count; } } } } // first time through, the FIRST sample doesn't need the interpolation... the buffer won't be filled 'correctly' for // interpolation, so use the _first function to make this exception template <bool First> static inline void VDiskIn_next_(VDiskIn* unit, int inNumSamples) { bool test = false; GET_BUF_SHARED if (!bufData || ((bufFrames & ((unit->mWorld->mBufLength << 1) - 1)) != 0)) { unit->m_framePos = 0.; unit->m_count = 0; ClearUnitOutputs(unit, inNumSamples); return; } SETUP_OUT(0); if (First) unit->m_rBufSize = 1. / bufFrames; double framePos = unit->m_framePos; double bufPos = unit->m_bufPos; // where we are in the DiskIn buffer float newPchRatio = sc_max(IN0(1), 0.f); if ((newPchRatio * inNumSamples * unit->m_rBufSize) >= 0.5) { printf("pitch ratio is greater then max allowed (see VDiskIn help)\n"); ClearUnitOutputs(unit, inNumSamples); return; } float pchRatio = unit->m_pchRatio; float pchSlope = CALCSLOPE(newPchRatio, pchRatio); uint32 bufFrames2 = bufFrames >> 1; double fbufFrames2 = (double)bufFrames2; double fbufFrames = (double)bufFrames; if (First) { for (uint32 i = 0; i < bufChannels; i++) out[i][0] = bufData[0 + i]; } const int firstLoopSample = First ? 1 : 0; for (int j = firstLoopSample; j < inNumSamples; ++j) { int32 iBufPos = (int32)bufPos; double frac = bufPos - (double)iBufPos; int table1 = iBufPos * bufChannels; int table0 = table1 - bufChannels; int table2 = table1 + bufChannels; int table3 = table2 + bufChannels; while (table1 >= bufSamples) table1 -= bufSamples; while (table0 < 0) table0 += bufSamples; while (table2 >= bufSamples) table2 -= bufSamples; while (table3 >= bufSamples) table3 -= bufSamples; for (uint32 i = 0; i < bufChannels; i++) { float a, b, c, d; a = bufData[table0 + i]; b = bufData[table1 + i]; c = bufData[table2 + i]; d = bufData[table3 + i]; out[i][j] = cubicinterp(frac, a, b, c, d); }; pchRatio += pchSlope; framePos += pchRatio; const double oldBufPos = bufPos; bufPos += pchRatio; // the +1 is needed for the cubic interpolation... make SURE the old data isn't needed any more before // setting up the new buffer if ((oldBufPos < (fbufFrames2 + 1)) && ((bufPos >= (fbufFrames2 + 1)))) { test = true; } if (bufPos >= (fbufFrames + 1)) { test = true; bufPos -= fbufFrames; } } if (unit->m_buf->mask1 >= 0 && bufPos >= unit->m_buf->mask1) unit->mDone = true; if (test) VDiskIn_request_buffer(unit, fbufnum, bufFrames2, bufChannels, bufPos); unit->m_framePos = framePos; unit->m_pchRatio = pchRatio; unit->m_bufPos = bufPos; if (First) SETCALC(VDiskIn_next); } void VDiskIn_first(VDiskIn* unit, int inNumSamples) { VDiskIn_next_<true>(unit, inNumSamples); } void VDiskIn_next(VDiskIn* unit, int inNumSamples) { VDiskIn_next_<false>(unit, inNumSamples); } void VDiskIn_next_rate1(VDiskIn* unit, int inNumSamples) { bool test = false; GET_BUF_SHARED if (!bufData || ((bufFrames & ((unit->mWorld->mBufLength << 1) - 1)) != 0)) { unit->m_iFramePos = 0.; unit->m_count = 0; ClearUnitOutputs(unit, inNumSamples); return; } SETUP_OUT(0) uint32 framePos = unit->m_iFramePos; uint32 bufPos = unit->m_iBufPos; uint32 bufFrames2 = bufFrames >> 1; for (int sample = 0; sample < inNumSamples; ++sample) { int bufferIndex = bufPos * bufChannels; for (uint32 channel = 0; channel < bufChannels; channel++) out[channel][sample] = bufData[bufferIndex + channel]; const uint32 oldBufPos = bufPos; bufPos += 1; framePos += 1; if ((oldBufPos < bufFrames2) && (bufPos >= bufFrames2)) test = true; if (bufPos >= bufFrames) { test = true; bufPos -= bufFrames; } } if (unit->m_buf->mask1 >= 0 && bufPos >= unit->m_buf->mask1) unit->mDone = true; if (test) VDiskIn_request_buffer(unit, fbufnum, bufFrames2, bufChannels, bufPos); unit->m_iFramePos = framePos; unit->m_iBufPos = bufPos; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(DiskIO) { ft = inTable; gDiskIO = new DiskIOThread(); gDiskIO->launchThread(); DefineSimpleUnit(DiskIn); DefineDtorUnit(DiskOut); DefineSimpleUnit(VDiskIn); } PluginUnload(DiskIO) { delete gDiskIO; } //////////////////////////////////////////////////////////////////////////////////////////////////
21,346
C++
.cpp
539
31.879406
120
0.547795
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
29,944
PV_ThirdParty.cpp
supercollider_supercollider/server/plugins/PV_ThirdParty.cpp
/* 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 */ // third party Phase Vocoder UGens #include "FFT_UGens.h" extern "C" { void PV_ConformalMap_Ctor(PV_Unit* unit); void PV_ConformalMap_next(PV_Unit* unit, int inNumSamples); } void PV_ConformalMap_Ctor(PV_Unit* unit) { SETCALC(PV_ConformalMap_next); ZOUT0(0) = ZIN0(0); } void PV_ConformalMap_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCComplexBuf* p = ToComplexApx(buf); float real2 = ZIN0(1); float imag2 = ZIN0(2); for (int i = 0; i < numbins; ++i) { float real1 = p->bin[i].real; float imag1 = p->bin[i].imag; // apply conformal map z-> z-a/(1-za*) where z is the existing complex number in the bin and a is defined by // inputs 1 and 2 float numr = real1 - real2; float numi = imag1 - imag2; float denomr = 1.f - (real1 * real2 + imag1 * imag2); float denomi = (real1 * imag2 - real2 * imag1); numr = numr * denomr + numi * denomi; numi = numi * denomr - numr * denomi; // squared modulus denomr = denomr * denomr + denomi * denomi; // avoid possible divide by zero if (denomr < 0.001f) denomr = 0.001f; denomr = 1.f / denomr; p->bin[i].real = numr * denomr; p->bin[i].imag = numi * denomr; } } #define DefinePVUnit(name) (*ft->fDefineUnit)(#name, sizeof(PV_Unit), (UnitCtorFunc)&name##_Ctor, 0, 0); // void initPV_ThirdParty(InterfaceTable *it); void initPV_ThirdParty(InterfaceTable* it) { DefinePVUnit(PV_ConformalMap); }
2,412
C++
.cpp
55
38.127273
116
0.672525
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
29,945
GrainUGens.cpp
supercollider_supercollider/server/plugins/GrainUGens.cpp
/* * GrainUGens.cpp * xSC3plugins * * Created by Josh Parmenter on 2/4/05. * Copyright 2005 __MyCompanyName__. All rights reserved. * */ /* 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_PlugIn.h" #include "function_attributes.h" static InterfaceTable* ft; const int kMaxGrains = 64; struct GrainInG { double b1, y1, y2, curamp, winPos, winInc; // envelope int counter, chan; float pan1, pan2, winType; }; struct GrainIn : public Unit { int mNumActive, m_channels, mMaxGrains; float curtrig; bool mFirst; GrainInG* mGrains; }; struct GrainSinG { double b1, y1, y2, curamp, winPos, winInc; // envelope int counter, chan; float pan1, pan2, winType; int32 oscphase; // the phase of the osc inside this grain int32 freq; // the freq of the osc inside this grain in phase inc }; struct GrainSin : public Unit { int mNumActive, m_channels, mMaxGrains; uint32 m_lomask; float curtrig; bool mFirst; double m_cpstoinc, m_radtoinc; GrainSinG* mGrains; }; struct GrainFMG { int32 coscphase, moscphase; // the phase of the osc inside this grain int32 mfreq; // the freq of the osc inside this grain in phase inc double b1, y1, y2, curamp, winPos, winInc; // envelope float deviation, carbase, pan1, pan2, winType; int counter, chan; }; struct GrainFM : public Unit { int mNumActive, m_channels, mMaxGrains; uint32 m_lomask; float curtrig; bool mFirst; double m_cpstoinc, m_radtoinc; GrainFMG* mGrains; }; struct GrainBufG { double phase, rate; double b1, y1, y2, curamp, winPos, winInc; float pan1, pan2, winType; int counter, chan, bufnum, interp; }; struct GrainBuf : public Unit { int mNumActive, m_channels, mMaxGrains; float curtrig; GrainBufG* mGrains; }; struct WarpWinGrain { double phase, rate; double winPos, winInc, b1, y1, y2, curamp; // tells the grain where to look in the winBuf for an amp value int counter, bufnum, interp; float winType; }; struct Warp1 : public Unit { float m_fbufnum; SndBuf* m_buf; int mNumActive[16]; int mNextGrain[16]; WarpWinGrain mGrains[16][kMaxGrains]; }; //////////////////////////////////////////////////////////////////////// extern "C" { void GrainIn_Ctor(GrainIn* unit); void GrainIn_Dtor(GrainIn* unit); void GrainIn_next_a(GrainIn* unit, int inNumSamples); void GrainIn_next_k(GrainIn* unit, int inNumSamples); void GrainSin_Ctor(GrainSin* unit); void GrainSin_Dtor(GrainSin* unit); void GrainSin_next_a(GrainSin* unit, int inNumSamples); void GrainSin_next_k(GrainSin* unit, int inNumSamples); void GrainFM_Ctor(GrainFM* unit); void GrainFM_Dtor(GrainFM* unit); void GrainFM_next_a(GrainFM* unit, int inNumSamples); void GrainFM_next_k(GrainFM* unit, int inNumSamples); void GrainBuf_Ctor(GrainBuf* unit); void GrainBuf_Dtor(GrainBuf* unit); void Warp1_next(Warp1* unit, int inNumSamples); void Warp1_Ctor(Warp1* unit); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////// Granular UGens //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// inline float GRAIN_IN_AT(Unit* unit, int index, int offset) { if (INRATE(index) == calc_FullRate) return IN(index)[offset]; if (INRATE(index) == calc_DemandRate) return DEMANDINPUT_A(index, offset + 1); return IN0(index); } template <bool full_rate> inline float grain_in_at(Unit* unit, int index, int offset) { if (full_rate) return GRAIN_IN_AT(unit, index, offset); if (INRATE(index) == calc_DemandRate) return DEMANDINPUT_A(index, offset + 1); else return IN0(index); } inline double sc_gloop(double in, double hi) { // avoid the divide if possible if (in >= hi) { in -= hi; if (in < hi) return in; } else if (in < 0.) { in += hi; if (in >= 0.) return in; } else return in; return in - hi * floor(in / hi); } #define GRAIN_BUF \ const SndBuf* buf; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ buf = world->mSndBufs + bufnum; \ } \ } else { \ if (bufnum < 0) { \ bufnum = 0; \ } \ buf = world->mSndBufs + bufnum; \ } \ LOCK_SNDBUF_SHARED(buf); \ const float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples __attribute__((__unused__)) = buf->samples; \ uint32 bufFrames = buf->frames; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; #define DECLARE_WINDOW \ double winPos, winInc, w, b1, y1, y2, y0; \ float amp; \ winPos = winInc = w = b1 = y1 = y2 = y0 = amp = 0.; \ SndBuf* window; \ const float* windowData __attribute__((__unused__)) = 0; \ uint32 windowSamples __attribute__((__unused__)) = 0; \ uint32 windowFrames __attribute__((__unused__)) = 0; \ int windowGuardFrame = 0; #define CHECK_BUF \ if (!bufData) { \ unit->mDone = true; \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } #define GET_GRAIN_WIN_RELAXED(WINTYPE) \ do { \ assert(WINTYPE < unit->mWorld->mNumSndBufs); \ window = unit->mWorld->mSndBufs + (int)WINTYPE; \ windowData = window->data; \ windowSamples = window->samples; \ windowFrames = window->frames; \ windowGuardFrame = windowFrames - 1; \ } while (0); static inline bool getGrainWin(Unit* unit, float wintype, SndBuf*& window, const float*& windowData, uint32& windowSamples, uint32& windowFrames, int& windowGuardFrame) { if (wintype >= unit->mWorld->mNumSndBufs) { Print("Envelope buffer out of range!\n"); return false; } assert(wintype < unit->mWorld->mNumSndBufs); if (wintype < 0) return true; // use default hann window window = unit->mWorld->mSndBufs + (int)wintype; windowData = window->data; if (!windowData) return false; windowSamples = window->samples; windowFrames = window->frames; windowGuardFrame = windowFrames - 1; return true; } #define GRAIN_LOOP_BODY_4 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float* table1 = bufData + iphase; \ float* table0 = table1 - 1; \ float* table2 = table1 + 1; \ float* table3 = table1 + 2; \ if (iphase == 0) { \ table0 += bufSamples; \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ table3 -= bufSamples; \ } else { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } \ } \ float fracphase = phase - (double)iphase; \ float a = table0[0]; \ float b = table1[0]; \ float c = table2[0]; \ float d = table3[0]; \ float outval = amp * cubicinterp(fracphase, a, b, c, d) ZXP(out1) += outval; \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; #define GRAIN_LOOP_BODY_2 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float* table1 = bufData + iphase; \ float* table2 = table1 + 1; \ if (iphase > guardFrame) { \ table2 -= bufSamples; \ } \ double fracphase = phase - (double)iphase; \ float b = table1[0]; \ float c = table2[0]; \ float outval = amp * (b + fracphase * (c - b)); \ ZXP(out1) += outval; \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; #define GRAIN_LOOP_BODY_1 \ float amp = y1 * y1; \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float outval = amp * bufData[iphase]; \ ZXP(out1) += outval; \ double y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; #define BUF_GRAIN_AMP \ winPos += winInc; \ int iWinPos = (int)winPos; \ double winFrac = winPos - (double)iWinPos; \ float* winTable1 = windowData + iWinPos; \ float* winTable2 = winTable1 + 1; \ if (winPos > windowGuardFrame) { \ winTable2 -= windowSamples; \ } \ amp = lininterp(winFrac, winTable1[0], winTable2[0]); #define BUF_GRAIN_LOOP_BODY_4 \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float* table1 = bufData + iphase; \ float* table0 = table1 - 1; \ float* table2 = table1 + 1; \ float* table3 = table1 + 2; \ if (iphase == 0) { \ table0 += bufSamples; \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ table3 -= bufSamples; \ } else { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } \ } \ float fracphase = phase - (double)iphase; \ float a = table0[0]; \ float b = table1[0]; \ float c = table2[0]; \ float d = table3[0]; \ float outval = amp * cubicinterp(fracphase, a, b, c, d); \ ZXP(out1) += outval; #define BUF_GRAIN_LOOP_BODY_2 \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float* table1 = bufData + iphase; \ float* table2 = table1 + 1; \ if (iphase > guardFrame) { \ table2 -= bufSamples; \ } \ float fracphase = phase - (double)iphase; \ float b = table1[0]; \ float c = table2[0]; \ float outval = amp * (b + fracphase * (c - b)); \ ZXP(out1) += outval; // amp needs to be calculated by looking up values in window #define BUF_GRAIN_LOOP_BODY_1 \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float outval = amp * bufData[iphase]; \ ZXP(out1) += outval; #define SETUP_OUT \ uint32 numOutputs = unit->mNumOutputs; \ if (numOutputs > bufChannels) { \ unit->mDone = true; \ ClearUnitOutputs(unit, inNumSamples); \ return; \ } \ float* out[16]; \ for (uint32 i = 0; i < numOutputs; ++i) \ out[i] = ZOUT(i); #define CALC_GRAIN_PAN \ float panangle, pan1, pan2; \ float *out1, *out2; \ if (numOutputs > 1) { \ if (numOutputs > 2) { \ pan = sc_wrap(pan * 0.5f, 0.f, 1.f); \ float cpan = numOutputs * pan + 0.5f; \ float ipan = floor(cpan); \ float panfrac = cpan - ipan; \ panangle = panfrac * pi2_f; \ grain->chan = (int)ipan; \ if (grain->chan >= (int)numOutputs) \ grain->chan -= numOutputs; \ } else { \ grain->chan = 0; \ pan = sc_clip(pan * 0.5f + 0.5f, 0.f, 1.f); \ panangle = pan * pi2_f; \ } \ pan1 = grain->pan1 = cos(panangle); \ pan2 = grain->pan2 = sin(panangle); \ } else { \ grain->chan = 0; \ pan1 = grain->pan1 = 1.; \ pan2 = grain->pan2 = 0.; \ } #define GET_GRAIN_INIT_AMP \ if (grain->winType < 0.) { \ w = pi / counter; \ b1 = grain->b1 = 2. * cos(w); \ y1 = sin(w); \ y2 = 0.; \ amp = y1 * y1; \ } else { \ amp = windowData[0]; \ winPos = grain->winPos = 0.f; \ winInc = grain->winInc = (double)windowSamples / counter; \ } #define CALC_NEXT_GRAIN_AMP_INTERNAL \ do { \ y0 = b1 * y1 - y2; \ y2 = y1; \ y1 = y0; \ amp = y1 * y1; \ } while (0) #define CALC_NEXT_GRAIN_AMP_CUSTOM \ do { \ winPos += winInc; \ int iWinPos = (int)winPos; \ double winFrac = winPos - (double)iWinPos; \ const float* winTable1 = windowData + iWinPos; \ const float* winTable2 = winTable1 + 1; \ if (!windowData) \ break; \ if (winPos > windowGuardFrame) \ winTable2 -= windowSamples; \ amp = lininterp(winFrac, winTable1[0], winTable2[0]); \ } while (0); \ if (!windowData) \ break; #define CALC_NEXT_GRAIN_AMP \ if (grain->winType < 0.) { \ CALC_NEXT_GRAIN_AMP_INTERNAL; \ } else { \ CALC_NEXT_GRAIN_AMP_CUSTOM; \ } #define GET_GRAIN_AMP_PARAMS \ if (grain->winType < 0.) { \ b1 = grain->b1; \ y1 = grain->y1; \ y2 = grain->y2; \ amp = grain->curamp; \ } else { \ GET_GRAIN_WIN_RELAXED(grain->winType); \ if (!windowData) \ break; \ winPos = grain->winPos; \ winInc = grain->winInc; \ amp = grain->curamp; \ } #define SAVE_GRAIN_AMP_PARAMS \ grain->y1 = y1; \ grain->y2 = y2; \ grain->winPos = winPos; \ grain->winInc = winInc; \ grain->curamp = amp; \ grain->counter -= nsmps; #define WRAP_CHAN(offset) \ out1 = OUT(grain->chan) + offset; \ if (numOutputs > 1) { \ if ((grain->chan + 1) >= (int)numOutputs) \ out2 = OUT(0) + offset; \ else \ out2 = OUT(grain->chan + 1) + offset; \ } #define GET_PAN_PARAMS \ float pan1 = grain->pan1; \ uint32 chan1 = grain->chan; \ float* out1 = OUT(chan1); \ if (numOutputs > 1) { \ pan2 = grain->pan2; \ uint32 chan2 = chan1 + 1; \ if (chan2 >= numOutputs) \ chan2 = 0; \ out2 = OUT(chan2); \ } //////////////////// InGrain //////////////////// inline void GrainIn_next_play_active(GrainIn* unit, int inNumSamples) { const uint32 numOutputs = unit->mNumOutputs; float* in = IN(2); for (int i = 0; i < unit->mNumActive;) { GrainInG* grain = unit->mGrains + i; DECLARE_WINDOW GET_GRAIN_AMP_PARAMS // begin add // float pan2 = 0.f; float* out2; GET_PAN_PARAMS // end add // int nsmps = sc_min(grain->counter, inNumSamples); for (int j = 0; j < nsmps; ++j) { float outval = amp * in[j]; // begin change / add // out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end change // CALC_NEXT_GRAIN_AMP } SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain else ++i; } } template <bool full_rate> inline void GrainIn_next_start_new(GrainIn* unit, int inNumSamples, int position) { if (unit->mNumActive + 1 >= unit->mMaxGrains) { Print("Too many grains!\n"); return; } float winType = grain_in_at<full_rate>(unit, 4, position); DECLARE_WINDOW bool success = getGrainWin(unit, winType, window, windowData, windowSamples, windowFrames, windowGuardFrame); if (!success) return; GrainInG* grain = unit->mGrains + unit->mNumActive++; float winSize = grain_in_at<full_rate>(unit, 1, position); double counter = winSize * SAMPLERATE; counter = sc_max(4., counter); grain->counter = (int)counter; grain->winType = winType; GET_GRAIN_INIT_AMP const uint32 numOutputs = unit->mNumOutputs; float* in = IN(2); float* in1 = in + position; // begin add // float pan = grain_in_at<full_rate>(unit, 3, position); CALC_GRAIN_PAN WRAP_CHAN(position) int nsmps = sc_min(grain->counter, inNumSamples - position); for (int j = 0; j < nsmps; ++j) { float outval = amp * in1[j]; // begin add / change out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end add / change CALC_NEXT_GRAIN_AMP } SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain } void GrainIn_next_a(GrainIn* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); // begin add // end add GrainIn_next_play_active(unit, inNumSamples); float* trig = IN(0); for (int i = 0; i < inNumSamples; ++i) { if ((unit->curtrig <= 0) && (trig[i] > 0.0)) GrainIn_next_start_new<true>(unit, inNumSamples, i); unit->curtrig = trig[i]; } } void GrainIn_next_k(GrainIn* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); if (unit->mFirst) { unit->mFirst = false; float maxGrains = IN0(5); unit->mMaxGrains = (int)maxGrains; unit->mGrains = (GrainInG*)RTAlloc(unit->mWorld, unit->mMaxGrains * sizeof(GrainInG)); ClearUnitIfMemFailed(unit->mGrains); } GrainIn_next_play_active(unit, inNumSamples); float trig = IN0(0); if ((unit->curtrig <= 0) && (trig > 0.0)) GrainIn_next_start_new<false>(unit, inNumSamples, 0); unit->curtrig = trig; } void GrainIn_Ctor(GrainIn* unit) { if (INRATE(0) == calc_FullRate) SETCALC(GrainIn_next_a); else SETCALC(GrainIn_next_k); unit->mFirst = true; unit->mNumActive = 0; unit->curtrig = 0.f; unit->mGrains = nullptr; GrainIn_next_k(unit, 1); } void GrainIn_Dtor(GrainIn* unit) { RTFree(unit->mWorld, unit->mGrains); } inline void GrainSin_next_play_active(GrainSin* unit, int inNumSamples) { const unsigned int numOutputs = unit->mNumOutputs; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; for (int i = 0; i < unit->mNumActive;) { GrainSinG* grain = unit->mGrains + i; DECLARE_WINDOW GET_GRAIN_AMP_PARAMS // begin add // float pan2 = 0.f; float* out2; GET_PAN_PARAMS // end add // int32 thisfreq = grain->freq; int32 oscphase = grain->oscphase; int nsmps = sc_min(grain->counter, inNumSamples); for (int j = 0; j < nsmps; ++j) { float outval = amp * lookupi1(table0, table1, oscphase, unit->m_lomask); // begin change / add // out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end change // CALC_NEXT_GRAIN_AMP oscphase += thisfreq; } SAVE_GRAIN_AMP_PARAMS grain->oscphase = oscphase; if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain else ++i; } } template <bool full_rate> inline void GrainSin_next_start_new(GrainSin* unit, int inNumSamples, int position) { if (unit->mNumActive + 1 >= unit->mMaxGrains) { Print("Too many grains!\n"); return; } float winType = grain_in_at<full_rate>(unit, 4, position); DECLARE_WINDOW bool success = getGrainWin(unit, winType, window, windowData, windowSamples, windowFrames, windowGuardFrame); if (!success) return; GrainSinG* grain = unit->mGrains + unit->mNumActive++; float freq = grain_in_at<full_rate>(unit, 2, position); float winSize = grain_in_at<full_rate>(unit, 1, position); int32 thisfreq = grain->freq = (int32)(unit->m_cpstoinc * freq); int32 oscphase = 0; double counter = winSize * SAMPLERATE; counter = sc_max(4., counter); grain->counter = (int)counter; grain->winType = winType; GET_GRAIN_INIT_AMP const uint32 numOutputs = unit->mNumOutputs; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; // begin add // float pan = grain_in_at<full_rate>(unit, 3, position); CALC_GRAIN_PAN WRAP_CHAN(position) // end add // int nsmps = sc_min(grain->counter, inNumSamples - position); for (int j = 0; j < nsmps; ++j) { float outval = amp * lookupi1(table0, table1, oscphase, unit->m_lomask); // begin add / change out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end add / change CALC_NEXT_GRAIN_AMP oscphase += thisfreq; } grain->oscphase = oscphase; SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain } void GrainSin_next_a(GrainSin* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); GrainSin_next_play_active(unit, inNumSamples); float* trig = IN(0); for (int i = 0; i < inNumSamples; ++i) { if ((unit->curtrig <= 0) && (trig[i] > 0.0)) GrainSin_next_start_new<true>(unit, inNumSamples, i); unit->curtrig = trig[i]; } } void GrainSin_next_k(GrainSin* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); if (unit->mFirst) { unit->mFirst = false; float maxGrains = IN0(5); unit->mMaxGrains = (int)maxGrains; unit->mGrains = (GrainSinG*)RTAlloc(unit->mWorld, unit->mMaxGrains * sizeof(GrainSinG)); ClearUnitIfMemFailed(unit->mGrains); } GrainSin_next_play_active(unit, inNumSamples); float trig = IN0(0); if ((unit->curtrig <= 0) && (trig > 0.0)) GrainSin_next_start_new<false>(unit, inNumSamples, 0); unit->curtrig = trig; } void GrainSin_Ctor(GrainSin* unit) { if (INRATE(0) == calc_FullRate) SETCALC(GrainSin_next_a); else SETCALC(GrainSin_next_k); int tableSizeSin = ft->mSineSize; unit->m_lomask = (tableSizeSin - 1) << 3; unit->m_radtoinc = tableSizeSin * (rtwopi * 65536.); unit->m_cpstoinc = tableSizeSin * SAMPLEDUR * 65536.; unit->curtrig = 0.f; unit->mNumActive = 0; unit->mFirst = true; unit->mGrains = nullptr; GrainSin_next_k(unit, 1); } void GrainSin_Dtor(GrainSin* unit) { RTFree(unit->mWorld, unit->mGrains); } inline void GrainFM_next_play_active(GrainFM* unit, int inNumSamples) { const uint32 numOutputs = unit->mNumOutputs; // end add float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; for (int i = 0; i < unit->mNumActive;) { GrainFMG* grain = unit->mGrains + i; DECLARE_WINDOW GET_GRAIN_AMP_PARAMS int32 mfreq = grain->mfreq; int32 moscphase = grain->moscphase; int32 coscphase = grain->coscphase; float deviation = grain->deviation; float carbase = grain->carbase; // begin add // float pan2 = 0.f; float* out2; GET_PAN_PARAMS // end add // int nsmps = sc_min(grain->counter, inNumSamples); for (int j = 0; j < nsmps; ++j) { float thismod = lookupi1(table0, table1, moscphase, unit->m_lomask) * deviation; float outval = amp * lookupi1(table0, table1, coscphase, unit->m_lomask); // begin change / add // out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end change // CALC_NEXT_GRAIN_AMP int32 cfreq = (int32)(unit->m_cpstoinc * (carbase + thismod)); // needs to be calced in the loop! coscphase += cfreq; moscphase += mfreq; } // need to save float carbase, int32 mfreq, float deviation grain->coscphase = coscphase; grain->moscphase = moscphase; SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain else ++i; } } template <bool full_rate> inline void GrainFM_next_start_new(GrainFM* unit, int inNumSamples, int position) { if (unit->mNumActive + 1 >= unit->mMaxGrains) { Print("Too many grains!\n"); return; } float winType = grain_in_at<full_rate>(unit, 6, position); DECLARE_WINDOW bool success = getGrainWin(unit, winType, window, windowData, windowSamples, windowFrames, windowGuardFrame); if (!success) return; GrainFMG* grain = unit->mGrains + unit->mNumActive++; float winSize = GRAIN_IN_AT(unit, 1, position); float carfreq = GRAIN_IN_AT(unit, 2, position); float modfreq = GRAIN_IN_AT(unit, 3, position); float index = GRAIN_IN_AT(unit, 4, position); float deviation = grain->deviation = index * modfreq; int32 mfreq = grain->mfreq = (int32)(unit->m_cpstoinc * modfreq); grain->carbase = carfreq; int32 coscphase = 0; int32 moscphase = 0; double counter = winSize * SAMPLERATE; counter = sc_max(4., counter); grain->counter = (int)counter; grain->winType = winType; // GRAIN_IN_AT(unit, 6, i); GET_GRAIN_INIT_AMP const uint32 numOutputs = unit->mNumOutputs; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; // begin add // float pan = GRAIN_IN_AT(unit, 5, position); CALC_GRAIN_PAN WRAP_CHAN(position) // end add // int nsmps = sc_min(grain->counter, inNumSamples - position); for (int j = 0; j < nsmps; ++j) { float thismod = lookupi1(table0, table1, moscphase, unit->m_lomask) * deviation; float outval = amp * lookupi1(table0, table1, coscphase, unit->m_lomask); // begin add / change out1[j] += outval * pan1; if (numOutputs > 1) out2[j] += outval * pan2; // end add / change CALC_NEXT_GRAIN_AMP int32 cfreq = (int32)(unit->m_cpstoinc * (carfreq + thismod)); // needs to be calced in the loop! coscphase += cfreq; moscphase += mfreq; } // need to save float carbase, int32 mfreq, float deviation grain->coscphase = coscphase; grain->moscphase = moscphase; SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[--unit->mNumActive]; // remove grain } void GrainFM_next_a(GrainFM* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); GrainFM_next_play_active(unit, inNumSamples); float* trig = IN(0); for (int i = 0; i < inNumSamples; ++i) { if ((unit->curtrig <= 0) && (trig[i] > 0.0)) GrainFM_next_start_new<true>(unit, inNumSamples, i); unit->curtrig = trig[i]; } } void GrainFM_next_k(GrainFM* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); if (unit->mFirst) { unit->mFirst = false; float maxGrains = IN0(7); unit->mMaxGrains = (int)maxGrains; unit->mGrains = (GrainFMG*)RTAlloc(unit->mWorld, unit->mMaxGrains * sizeof(GrainFMG)); ClearUnitIfMemFailed(unit->mGrains); } GrainFM_next_play_active(unit, inNumSamples); float trig = IN0(0); if ((unit->curtrig <= 0) && (trig > 0.0)) GrainFM_next_start_new<false>(unit, inNumSamples, 0); unit->curtrig = trig; } void GrainFM_Ctor(GrainFM* unit) { if (INRATE(0) == calc_FullRate) SETCALC(GrainFM_next_a); else SETCALC(GrainFM_next_k); int tableSizeSin = ft->mSineSize; unit->m_lomask = (tableSizeSin - 1) << 3; unit->m_radtoinc = tableSizeSin * (rtwopi * 65536.); unit->m_cpstoinc = tableSizeSin * SAMPLEDUR * 65536.; unit->curtrig = 0.f; unit->mNumActive = 0; unit->mFirst = true; unit->mGrains = nullptr; GrainFM_next_k(unit, 1); } void GrainFM_Dtor(GrainFM* unit) { RTFree(unit->mWorld, unit->mGrains); } #define GRAIN_BUF_LOOP_BODY_4_MONO \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase; \ const float* table0 = table1 - 1; \ const float* table2 = table1 + 1; \ const float* table3 = table1 + 2; \ if (iphase == 0) { \ table0 += bufSamples; \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ table3 -= bufSamples; \ } else { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } \ } \ float fracphase = phase - (double)iphase; \ float a = table0[0]; \ float b = table1[0]; \ float c = table2[0]; \ float d = table3[0]; \ float outval = amp * cubicinterp(fracphase, a, b, c, d); \ out1[j] += outval * pan1; #define GRAIN_BUF_LOOP_BODY_4_STEREO \ GRAIN_BUF_LOOP_BODY_4_MONO \ out2[j] += outval * pan2; #define GRAIN_BUF_LOOP_BODY_2_MONO \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase; \ const float* table2 = table1 + 1; \ if (iphase > guardFrame) { \ table2 -= bufSamples; \ } \ float fracphase = phase - (double)iphase; \ float b = table1[0]; \ float c = table2[0]; \ float outval = amp * (b + fracphase * (c - b)); \ out1[j] += outval * pan1; #define GRAIN_BUF_LOOP_BODY_2_STEREO \ GRAIN_BUF_LOOP_BODY_2_MONO \ out2[j] += outval * pan2; #define GRAIN_BUF_LOOP_BODY_1_MONO \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float outval = amp * bufData[iphase]; \ out1[j] += outval * pan1; #define GRAIN_BUF_LOOP_BODY_1_STEREO \ GRAIN_BUF_LOOP_BODY_1_MONO \ out2[j] += outval * pan2; #define GRAIN_BUF_PLAY_GRAIN(WINDOW) \ do { \ if (numOutputs == 1) { \ if (grain->interp >= 4) { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_4_MONO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } else if (grain->interp >= 2) { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_2_MONO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } else { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_1_MONO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } \ } else { \ if (grain->interp >= 4) { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_4_STEREO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } else if (grain->interp >= 2) { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_2_STEREO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } else { \ for (int j = 0; j < nsmps; j++) { \ GRAIN_BUF_LOOP_BODY_1_STEREO \ CALC_NEXT_GRAIN_AMP_##WINDOW; \ phase += rate; \ } \ } \ } \ } while (0) static inline bool GrainBuf_grain_cleanup(GrainBuf* unit, GrainBufG* grain) { if (grain->counter <= 0) { *grain = unit->mGrains[--unit->mNumActive]; // remove grain return true; } else return false; } template <bool IsMono> static inline void GrainBuf_next_play_active(GrainBuf* unit, int inNumSamples) { const uint32 numOutputs = IsMono ? 1 : unit->mNumOutputs; World* world = unit->mWorld; for (int i = 0; i < unit->mNumActive;) { GrainBufG* grain = unit->mGrains + i; int bufnum = grain->bufnum; GRAIN_BUF if (!bufData || (bufChannels != 1)) { grain->counter -= inNumSamples; if (!GrainBuf_grain_cleanup(unit, grain)) ++i; continue; } double loopMax = (double)bufFrames; double rate = grain->rate; double phase = grain->phase; DECLARE_WINDOW GET_GRAIN_AMP_PARAMS // begin add // float pan2 = 0.f; float* out2; GET_PAN_PARAMS // end add // int nsmps = sc_min(grain->counter, inNumSamples); if (grain->winType < 0.) GRAIN_BUF_PLAY_GRAIN(INTERNAL); else GRAIN_BUF_PLAY_GRAIN(CUSTOM); if (GrainBuf_grain_cleanup(unit, grain)) continue; ++i; grain->phase = phase; SAVE_GRAIN_AMP_PARAMS } } template <bool full_rate, bool IsMono> static inline void GrainBuf_next_start_new(GrainBuf* unit, int inNumSamples, int position) { World* world = unit->mWorld; if (unit->mNumActive + 1 >= unit->mMaxGrains) { Print("Too many grains!\n"); return; } float winType = grain_in_at<full_rate>(unit, 7, position); DECLARE_WINDOW bool success = getGrainWin(unit, winType, window, windowData, windowSamples, windowFrames, windowGuardFrame); if (!success) return; GrainBufG* grain = unit->mGrains + unit->mNumActive++; int32 bufnum = grain_in_at<full_rate>(unit, 2, position); grain->bufnum = bufnum; GRAIN_BUF if ((bufChannels != 1) || (!bufData)) { GrainBuf_grain_cleanup(unit, grain); return; } float bufSampleRate = buf->samplerate; float bufRateScale = bufSampleRate * SAMPLEDUR; double loopMax = (double)bufFrames; double rate = grain->rate = grain_in_at<full_rate>(unit, 3, position) * bufRateScale; double phase = grain_in_at<full_rate>(unit, 4, position) * bufFrames; if (!sc_isfinite(phase)) { GrainBuf_grain_cleanup(unit, grain); return; } double counter = grain_in_at<full_rate>(unit, 1, position) * SAMPLERATE; counter = sc_max(4., counter); grain->counter = (int)counter; grain->interp = (int)grain_in_at<full_rate>(unit, 5, position); grain->winType = winType; GET_GRAIN_INIT_AMP const uint32 numOutputs = IsMono ? 1 : unit->mNumOutputs; // begin add // float pan = grain_in_at<full_rate>(unit, 6, position); CALC_GRAIN_PAN WRAP_CHAN(position) // end add // int nsmps = sc_min(grain->counter, inNumSamples - position); if (grain->winType < 0.) GRAIN_BUF_PLAY_GRAIN(INTERNAL); else GRAIN_BUF_PLAY_GRAIN(CUSTOM); grain->phase = phase; SAVE_GRAIN_AMP_PARAMS GrainBuf_grain_cleanup(unit, grain); } template <bool MultiChannel> static void GrainBuf_next_a(GrainBuf* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); GrainBuf_next_play_active<MultiChannel>(unit, inNumSamples); float* trig = IN(0); for (int i = 0; i < inNumSamples; i++) { if ((trig[i] > 0) && (unit->curtrig <= 0)) GrainBuf_next_start_new<true, MultiChannel>(unit, inNumSamples, i); unit->curtrig = trig[i]; } } template <bool MultiChannel> static void GrainBuf_next_k(GrainBuf* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); GrainBuf_next_play_active<MultiChannel>(unit, inNumSamples); float trig = IN0(0); if ((trig > 0) && (unit->curtrig <= 0)) GrainBuf_next_start_new<false, MultiChannel>(unit, inNumSamples, 0); unit->curtrig = trig; } FLATTEN static void GrainBuf_next_k_1(GrainBuf* unit, int inNumSamples) { GrainBuf_next_k<true>(unit, inNumSamples); } FLATTEN static void GrainBuf_next_k_2(GrainBuf* unit, int inNumSamples) { GrainBuf_next_k<false>(unit, inNumSamples); } FLATTEN static void GrainBuf_next_a_1(GrainBuf* unit, int inNumSamples) { GrainBuf_next_a<true>(unit, inNumSamples); } FLATTEN static void GrainBuf_next_a_2(GrainBuf* unit, int inNumSamples) { GrainBuf_next_a<false>(unit, inNumSamples); } void GrainBuf_Ctor(GrainBuf* unit) { unit->mNumActive = 0; unit->curtrig = 0.f; float maxGrains = IN0(8); unit->mMaxGrains = (int)maxGrains; unit->mGrains = (GrainBufG*)RTAlloc(unit->mWorld, unit->mMaxGrains * sizeof(GrainBufG)); ClearUnitIfMemFailed(unit->mGrains); if (unit->mNumOutputs == 1) { if (INRATE(0) == calc_FullRate) SETCALC(GrainBuf_next_a_1); else SETCALC(GrainBuf_next_k_1); } else { if (INRATE(0) == calc_FullRate) SETCALC(GrainBuf_next_a_2); else SETCALC(GrainBuf_next_k_2); } (unit->mCalcFunc)(unit, 1); } void GrainBuf_Dtor(GrainBuf* unit) { RTFree(unit->mWorld, unit->mGrains); } #define BUF_GRAIN_LOOP_BODY_4_N \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase * bufChannels; \ const float* table0 = table1 - bufChannels; \ const float* table2 = table1 + bufChannels; \ const float* table3 = table2 + bufChannels; \ if (iphase == 0) { \ table0 += bufSamples; \ } else if (iphase >= guardFrame) { \ if (iphase == guardFrame) { \ table3 -= bufSamples; \ } else { \ table2 -= bufSamples; \ table3 -= bufSamples; \ } \ } \ float fracphase = phase - (double)iphase; \ float a = table0[n]; \ float b = table1[n]; \ float c = table2[n]; \ float d = table3[n]; \ float outval = amp * cubicinterp(fracphase, a, b, c, d); \ ZXP(out1) += outval; #define BUF_GRAIN_LOOP_BODY_2_N \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ const float* table1 = bufData + iphase * bufChannels; \ const float* table2 = table1 + bufChannels; \ if (iphase > guardFrame) { \ table2 -= bufSamples; \ } \ float fracphase = phase - (double)iphase; \ float b = table1[n]; \ float c = table2[n]; \ float outval = amp * (b + fracphase * (c - b)); \ ZXP(out1) += outval; // amp needs to be calculated by looking up values in window #define BUF_GRAIN_LOOP_BODY_1_N \ phase = sc_gloop(phase, loopMax); \ int32 iphase = (int32)phase; \ float outval = amp * bufData[iphase + n]; \ ZXP(out1) += outval; #define GET_WARP_WIN_RELAXED(WINTYPE) \ do { \ assert(WINTYPE < unit->mWorld->mNumSndBufs); \ window = unit->mWorld->mSndBufs + (int)WINTYPE; \ while (!TRY_ACQUIRE_SNDBUF_SHARED(window)) { \ RELEASE_SNDBUF_SHARED(buf); \ ACQUIRE_SNDBUF_SHARED(buf); \ } \ windowData = window->data; \ if (windowData == NULL) \ RELEASE_SNDBUF_SHARED(window); \ windowSamples = window->samples; \ windowFrames = window->frames; \ windowGuardFrame = windowFrames - 1; \ } while (0); #define GET_WARP_AMP_PARAMS \ if (grain->winType < 0.) { \ b1 = grain->b1; \ y1 = grain->y1; \ y2 = grain->y2; \ amp = grain->curamp; \ } else { \ GET_WARP_WIN_RELAXED(grain->winType); \ if (!windowData) \ break; \ winPos = grain->winPos; \ winInc = grain->winInc; \ amp = grain->curamp; \ } void Warp1_next(Warp1* unit, int inNumSamples) { ClearUnitOutputs(unit, inNumSamples); GET_BUF SETUP_OUT CHECK_BUF for (uint32 n = 0; n < numOutputs; n++) { int nextGrain = unit->mNextGrain[n]; for (int i = 0; i < unit->mNumActive[n];) { WarpWinGrain* grain = unit->mGrains[n] + i; double loopMax = (double)bufFrames; double rate = grain->rate; double phase = grain->phase; DECLARE_WINDOW GET_GRAIN_AMP_PARAMS float* out1 = out[n]; int nsmps = sc_min(grain->counter, inNumSamples); if (grain->interp >= 4) { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_4_N CALC_NEXT_GRAIN_AMP phase += rate; } } else if (grain->interp >= 2) { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_2_N CALC_NEXT_GRAIN_AMP phase += rate; } } else { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_1_N CALC_NEXT_GRAIN_AMP phase += rate; } } grain->phase = phase; SAVE_GRAIN_AMP_PARAMS if (grain->counter <= 0) *grain = unit->mGrains[n][--unit->mNumActive[n]]; // remove grain else ++i; } for (int i = 0; i < inNumSamples; ++i) { --nextGrain; if (nextGrain == 0) { // start a grain if (unit->mNumActive[n] + 1 >= kMaxGrains) break; // uint32 bufnum = (uint32)GRAIN_IN_AT(unit, 0, i); // if (bufnum >= numBufs) break; float bufSampleRate = buf->samplerate; float bufRateScale = bufSampleRate * SAMPLEDUR; double loopMax = (double)bufFrames; WarpWinGrain* grain = unit->mGrains[n] + unit->mNumActive[n]++; // grain->bufnum = bufnum; float overlaps = GRAIN_IN_AT(unit, 5, i); float counter = GRAIN_IN_AT(unit, 3, i) * SAMPLERATE; double winrandamt = unit->mParent->mRGen->frand2() * (double)GRAIN_IN_AT(unit, 6, i); counter = sc_max(4., floor(counter + (counter * winrandamt))); grain->counter = (int)counter; nextGrain = (int)(counter / overlaps); unit->mNextGrain[n] = nextGrain; float rate = grain->rate = GRAIN_IN_AT(unit, 2, i) * bufRateScale; float phase = GRAIN_IN_AT(unit, 1, i) * (float)bufFrames; grain->interp = (int)GRAIN_IN_AT(unit, 7, i); float winType = grain->winType = (int)GRAIN_IN_AT(unit, 4, i); // the buffer that holds the grain shape DECLARE_WINDOW if (winType >= unit->mWorld->mNumSndBufs) { Print("Envelope buffer out of range!\n"); break; } GET_GRAIN_WIN_RELAXED(winType) if (windowData || (winType < 0.)) { GET_GRAIN_INIT_AMP float* out1 = out[n] + i; int nsmps = sc_min(grain->counter, inNumSamples - i); if (grain->interp >= 4) { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_4_N CALC_NEXT_GRAIN_AMP phase += rate; } } else if (grain->interp >= 2) { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_2_N CALC_NEXT_GRAIN_AMP phase += rate; } } else { for (int j = 0; j < nsmps; ++j) { BUF_GRAIN_LOOP_BODY_1_N CALC_NEXT_GRAIN_AMP phase += rate; } } grain->phase = phase; SAVE_GRAIN_AMP_PARAMS // end change if (grain->counter <= 0) *grain = unit->mGrains[n][--unit->mNumActive[n]]; // remove grain } } } unit->mNextGrain[n] = nextGrain; } } void Warp1_Ctor(Warp1* unit) { SETCALC(Warp1_next); for (int i = 0; i < 16; i++) { unit->mNumActive[i] = 0; unit->mNextGrain[i] = 1; } ClearUnitOutputs(unit, 1); unit->m_fbufnum = -1e9f; } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Grain) { ft = inTable; DefineDtorCantAliasUnit(GrainIn); DefineDtorCantAliasUnit(GrainSin); DefineDtorCantAliasUnit(GrainFM); DefineDtorCantAliasUnit(GrainBuf); DefineSimpleCantAliasUnit(Warp1); }
79,266
C++
.cpp
1,218
57.345649
120
0.315045
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
29,946
TriggerUGens.cpp
supercollider_supercollider/server/plugins/TriggerUGens.cpp
/* 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_PlugIn.h" #include <algorithm> /* for std::min and std::max */ #include <boost/align/is_aligned.hpp> #include "simd_peakmeter.hpp" #ifdef NOVA_SIMD # include "simd_memory.hpp" # include "function_attributes.h" #endif static InterfaceTable* ft; ////////////////////////////////////////////////////////////////////////////////////////////////// struct Trig1 : public Unit { float m_prevtrig; long mCounter; }; struct Trig : public Unit { float mLevel; float m_prevtrig; long mCounter; }; struct SendTrig : public Unit { float m_prevtrig; }; struct SendReply : public Unit { float m_prevtrig; int m_valueSize; int m_valueOffset; float* m_values; int m_cmdNameSize; char* m_cmdName; }; struct Poll : public Unit { int m_samplesRemain, m_intervalSamples; float m_trig; float m_lastPoll; char* m_id_string; bool m_mayprint; }; struct ToggleFF : public Unit { float mLevel; float m_prevtrig; }; struct SetResetFF : public Unit { float mLevel; float m_prevtrig, m_prevreset; }; struct Latch : public Unit { float mLevel; float m_prevtrig; }; struct Gate : public Unit { float mLevel; }; struct Schmidt : public Unit { float mLevel; }; struct PulseDivider : public Unit { float mLevel; float m_prevtrig; long mCounter; }; struct PulseCount : public Unit { float mLevel; float m_prevtrig, m_prevreset; }; struct Stepper : public Unit { float mLevel; float m_prevtrig, m_prevreset; }; struct TDelay : public Unit { long mCounter; float m_prevtrig; }; struct ZeroCrossing : public Unit { float mLevel, m_prevfrac, m_previn; int32 mCounter; }; struct Timer : public Unit { float mLevel, m_prevfrac, m_previn; int32 mCounter; }; struct Sweep : public Unit { double mLevel; float m_previn; }; struct Phasor : public Unit { double mLevel; float m_previn; }; struct Peak : public Unit { float mLevel; float m_prevtrig; }; struct RunningMin : public Unit { float mLevel; float m_prevtrig; }; struct RunningMax : public Unit { float mLevel; float m_prevtrig; }; struct PeakFollower : public Unit { float mLevel; float mDecay; }; struct MostChange : public Unit { float mPrevA, mPrevB; int mRecent; }; struct LeastChange : public Unit { float mPrevA, mPrevB; int mRecent; }; struct LastValue : public Unit { float mPrev; float mCurr; }; struct Done : public Unit { Unit* m_src; }; struct FreeSelf : public Unit { float m_prevtrig; }; struct PauseSelf : public Unit { float m_prevtrig; }; struct Pause : public Unit { int m_state; }; struct Free : public Unit { float m_prevtrig; }; struct FreeSelfWhenDone : public Unit { Unit* m_src; }; struct PauseSelfWhenDone : public Unit { Unit* m_src; }; extern "C" { void Trig1_Ctor(Trig1* unit); void Trig1_next(Trig1* unit, int inNumSamples); void Trig1_next_k(Trig1* unit, int inNumSamples); void Trig_Ctor(Trig* unit); void Trig_next(Trig* unit, int inNumSamples); void Trig_next_k(Trig* unit, int inNumSamples); void SendTrig_Ctor(SendTrig* unit); void SendTrig_next(SendTrig* unit, int inNumSamples); void SendTrig_next_aka(SendTrig* unit, int inNumSamples); void SendReply_Ctor(SendReply* unit); void SendReply_next(SendReply* unit, int inNumSamples); void SendReply_next_aka(SendReply* unit, int inNumSamples); void Poll_Ctor(Poll* unit); void Poll_next_aa(Poll* unit, int inNumSamples); void Poll_next_ak(Poll* unit, int inNumSamples); void Poll_next_kk(Poll* unit, int inNumSamples); void SetResetFF_Ctor(SetResetFF* unit); void SetResetFF_next_a(SetResetFF* unit, int inNumSamples); void SetResetFF_next_k(SetResetFF* unit, int inNumSamples); void ToggleFF_Ctor(ToggleFF* unit); void ToggleFF_next(ToggleFF* unit, int inNumSamples); void Latch_Ctor(Latch* unit); void Latch_next_ak(Latch* unit, int inNumSamples); void Latch_next_aa(Latch* unit, int inNumSamples); void Gate_Ctor(Gate* unit); void Gate_next_ak(Gate* unit, int inNumSamples); void Gate_next_aa(Gate* unit, int inNumSamples); void Schmidt_Ctor(Schmidt* unit); void Schmidt_next(Schmidt* unit, int inNumSamples); void PulseDivider_Ctor(PulseDivider* unit); void PulseDivider_next(PulseDivider* unit, int inNumSamples); void PulseCount_Ctor(PulseCount* unit); void PulseCount_next_a(PulseCount* unit, int inNumSamples); void PulseCount_next_k(PulseCount* unit, int inNumSamples); void PulseCount_next_0(PulseCount* unit, int inNumSamples); void Stepper_Ctor(Stepper* unit); void Stepper_next_aa(Stepper* unit, int inNumSamples); void Stepper_next_ak(Stepper* unit, int inNumSamples); void Stepper_next_a0(Stepper* unit, int inNumSamples); void TDelay_Ctor(TDelay* unit); void TDelay_next(TDelay* unit, int inNumSamples); void ZeroCrossing_Ctor(ZeroCrossing* unit); void ZeroCrossing_next_a(ZeroCrossing* unit, int inNumSamples); void Timer_Ctor(Timer* unit); void Timer_next_a(Timer* unit, int inNumSamples); void Sweep_Ctor(Sweep* unit); void Sweep_next_0k(Sweep* unit, int inNumSamples); void Sweep_next_0a(Sweep* unit, int inNumSamples); void Sweep_next_kk(Sweep* unit, int inNumSamples); void Sweep_next_ka(Sweep* unit, int inNumSamples); void Sweep_next_ak(Sweep* unit, int inNumSamples); void Sweep_next_aa(Sweep* unit, int inNumSamples); void Phasor_Ctor(Phasor* unit); void Phasor_next_kk(Phasor* unit, int inNumSamples); void Phasor_next_ak(Phasor* unit, int inNumSamples); void Phasor_next_aa(Phasor* unit, int inNumSamples); void Peak_Ctor(Peak* unit); void Peak_next_ak(Peak* unit, int inNumSamples); void Peak_next_ai(Peak* unit, int inNumSamples); void Peak_next_aa(Peak* unit, int inNumSamples); void Peak_next_ak_k(Peak* unit, int inNumSamples); void Peak_next_ai_k(Peak* unit, int inNumSamples); void Peak_next_aa_k(Peak* unit, int inNumSamples); void RunningMin_Ctor(RunningMin* unit); void RunningMin_next_ak(RunningMin* unit, int inNumSamples); void RunningMin_next_ai(RunningMin* unit, int inNumSamples); void RunningMin_next_aa(RunningMin* unit, int inNumSamples); void RunningMax_Ctor(RunningMax* unit); void RunningMax_next_ak(RunningMax* unit, int inNumSamples); void RunningMax_next_ai(RunningMax* unit, int inNumSamples); void RunningMax_next_aa(RunningMax* unit, int inNumSamples); void PeakFollower_Ctor(PeakFollower* unit); void PeakFollower_next(PeakFollower* unit, int inNumSamples); void PeakFollower_next_ai(PeakFollower* unit, int inNumSamples); void MostChange_Ctor(MostChange* unit); void MostChange_next_ak(MostChange* unit, int inNumSamples); void MostChange_next_ka(MostChange* unit, int inNumSamples); void MostChange_next_aa(MostChange* unit, int inNumSamples); void LeastChange_Ctor(LeastChange* unit); void LeastChange_next_ak(LeastChange* unit, int inNumSamples); void LeastChange_next_ka(LeastChange* unit, int inNumSamples); void LeastChange_next_aa(LeastChange* unit, int inNumSamples); void LastValue_Ctor(LastValue* unit); void LastValue_next_ak(LastValue* unit, int inNumSamples); void LastValue_next_kk(LastValue* unit, int inNumSamples); void Done_Ctor(Done* unit); void Done_next(Done* unit, int inNumSamples); void FreeSelf_Ctor(FreeSelf* unit); void FreeSelf_next(FreeSelf* unit, int inNumSamples); void FreeSelfWhenDone_Ctor(FreeSelfWhenDone* unit); void FreeSelfWhenDone_next(FreeSelfWhenDone* unit, int inNumSamples); void PauseSelf_Ctor(PauseSelf* unit); void PauseSelf_next(PauseSelf* unit, int inNumSamples); void Pause_Ctor(Pause* unit); void Pause_next(Pause* unit, int inNumSamples); void Free_Ctor(Free* unit); void Free_next(Free* unit, int inNumSamples); void PauseSelfWhenDone_Ctor(PauseSelfWhenDone* unit); void PauseSelfWhenDone_next(PauseSelfWhenDone* unit, int inNumSamples); } //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD FLATTEN void Trig1_next_nova(Trig1* unit, int inNumSamples); FLATTEN void Trig1_next_k_nova(Trig1* unit, int inNumSamples); #endif void Trig1_Ctor(Trig1* unit) { if (unit->mCalcRate == calc_FullRate && INRATE(0) != calc_FullRate) { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Trig1_next_k_nova); else #endif SETCALC(Trig1_next_k); } else { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Trig1_next_nova); else #endif SETCALC(Trig1_next); } unit->mCounter = 0; unit->m_prevtrig = 0.f; Trig1_next(unit, 1); unit->mCounter = 0; unit->m_prevtrig = 0.f; } void Trig1_next(Trig1* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; unsigned long counter = unit->mCounter; LOOP1( inNumSamples, float curtrig = ZXP(trig); float zout; if (counter > 0) { zout = --counter ? 1.f : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; zout = 1.f; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); unit->m_prevtrig = prevtrig; unit->mCounter = counter; } void Trig1_next_k(Trig1* unit, int inNumSamples) { float* out = ZOUT(0); float curtrig = ZIN0(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; unsigned long counter = unit->mCounter; LOOP1( inNumSamples, float zout; if (counter > 0) { zout = --counter ? 1.f : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; zout = 1.f; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); unit->m_prevtrig = prevtrig; unit->mCounter = counter; } #ifdef NOVA_SIMD void Trig1_next_nova(Trig1* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; unsigned long counter = unit->mCounter; if (counter > inNumSamples) { nova::setvec_simd(OUT(0), 1.f, inNumSamples); counter -= inNumSamples; assert(counter > 0); prevtrig = IN(0)[inNumSamples - 1]; } else { LOOP1( inNumSamples, float curtrig = ZXP(trig); float zout; if (counter > 0) { zout = --counter ? 1.f : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; zout = 1.f; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); } unit->m_prevtrig = prevtrig; unit->mCounter = counter; } void Trig1_next_k_nova(Trig1* unit, int inNumSamples) { float* out = ZOUT(0); float curtrig = ZIN0(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; unsigned long counter = unit->mCounter; if (counter > inNumSamples) { nova::setvec_simd(OUT(0), 1.f, inNumSamples); counter -= inNumSamples; assert(counter > 0); prevtrig = curtrig; } else if (counter == 0 && (curtrig <= 0.f || prevtrig > 0.f)) { nova::zerovec_simd(OUT(0), inNumSamples); prevtrig = curtrig; } else { LOOP1( inNumSamples, float zout; if (counter > 0) { zout = --counter ? 1.f : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; zout = 1.f; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); } unit->m_prevtrig = prevtrig; unit->mCounter = counter; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD void Trig_next_nova(Trig* unit, int inNumSamples); void Trig_next_k_nova(Trig* unit, int inNumSamples); #endif void Trig_Ctor(Trig* unit) { if (unit->mCalcRate == calc_FullRate && INRATE(0) != calc_FullRate) { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Trig_next_k_nova); else #endif SETCALC(Trig_next_k); } else { #ifdef NOVA_SIMD if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Trig_next_nova); else #endif SETCALC(Trig_next); } unit->mCounter = 0; unit->m_prevtrig = 0.f; unit->mLevel = 0.f; Trig_next(unit, 1); unit->mCounter = 0; unit->m_prevtrig = 0.f; unit->mLevel = 0.f; } void Trig_next(Trig* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; float level = unit->mLevel; unsigned long counter = unit->mCounter; LOOP1( inNumSamples, float curtrig = ZXP(trig); float zout; if (counter > 0) { zout = --counter ? level : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; level = curtrig; zout = level; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); unit->m_prevtrig = prevtrig; unit->mCounter = counter; unit->mLevel = level; } void Trig_next_k(Trig* unit, int inNumSamples) { float* out = ZOUT(0); float curtrig = ZIN0(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; float level = unit->mLevel; unsigned long counter = unit->mCounter; LOOP1( inNumSamples, float zout; if (counter > 0) { zout = --counter ? level : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; level = curtrig; zout = level; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); unit->m_prevtrig = prevtrig; unit->mCounter = counter; unit->mLevel = level; } #ifdef NOVA_SIMD void Trig_next_nova(Trig* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; float level = unit->mLevel; unsigned long counter = unit->mCounter; if (counter > inNumSamples) { nova::setvec_simd(OUT(0), level, inNumSamples); counter -= inNumSamples; assert(counter > 0); prevtrig = IN(0)[inNumSamples - 1]; } else { LOOP1( inNumSamples, float curtrig = ZXP(trig); float zout; if (counter > 0) { zout = --counter ? level : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; level = curtrig; zout = level; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); } unit->m_prevtrig = prevtrig; unit->mCounter = counter; unit->mLevel = level; } void Trig_next_k_nova(Trig* unit, int inNumSamples) { float* out = ZOUT(0); float curtrig = ZIN0(0); float dur = ZIN0(1); float sr = unit->mRate->mSampleRate; float prevtrig = unit->m_prevtrig; float level = unit->mLevel; unsigned long counter = unit->mCounter; if (counter > inNumSamples) { nova::setvec_simd(OUT(0), level, inNumSamples); counter -= inNumSamples; assert(counter > 0); prevtrig = curtrig; } else if (counter == 0 && (curtrig <= 0.f || prevtrig > 0.f)) { nova::zerovec_simd(OUT(0), inNumSamples); prevtrig = curtrig; } else { LOOP1( inNumSamples, float zout; if (counter > 0) { zout = --counter ? level : 0.f; } else { if (curtrig > 0.f && prevtrig <= 0.f) { counter = (long)(dur * sr + .5f); if (counter < 1) counter = 1; level = curtrig; zout = level; } else { zout = 0.f; } } prevtrig = curtrig; ZXP(out) = zout;); } unit->m_prevtrig = prevtrig; unit->mCounter = counter; unit->mLevel = level; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// void SendTrig_Ctor(SendTrig* unit) { if (INRATE(2) == calc_FullRate) { SETCALC(SendTrig_next_aka); } else { SETCALC(SendTrig_next); } unit->m_prevtrig = 0.f; } void SendTrig_next(SendTrig* unit, int inNumSamples) { float* trig = ZIN(0); float prevtrig = unit->m_prevtrig; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (curtrig > 0.f && prevtrig <= 0.f) { SendTrigger(&unit->mParent->mNode, (int)ZIN0(1), ZIN0(2)); } prevtrig = curtrig;); unit->m_prevtrig = prevtrig; } void SendTrig_next_aka(SendTrig* unit, int inNumSamples) { float* trig = ZIN(0); int id = (int)ZIN0(1); float* value = ZIN(2); float prevtrig = unit->m_prevtrig; LOOP1( inNumSamples, float curtrig = ZXP(trig); float curval = ZXP(value); if (curtrig > 0.f && prevtrig <= 0.f) { SendTrigger(&unit->mParent->mNode, id, curval); } prevtrig = curtrig;); unit->m_prevtrig = prevtrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// static void Unit_next_nop(SendReply* unit, int inNumSamples) {} void SendReply_Ctor(SendReply* unit) { const int kVarOffset = 3; unit->m_prevtrig = 0.f; unit->m_cmdNameSize = IN0(2); unit->m_valueSize = unit->mNumInputs - unit->m_cmdNameSize - kVarOffset; unit->m_valueOffset = kVarOffset + unit->m_cmdNameSize; // allocations const int cmdNameAllocSize = (unit->m_cmdNameSize + 1) * sizeof(char); const int valuesAllocSize = unit->m_valueSize * sizeof(float); char* chunk = (char*)RTAlloc(unit->mWorld, cmdNameAllocSize + valuesAllocSize); ClearUnitIfMemFailed(chunk); unit->m_cmdName = chunk; unit->m_values = (float*)(chunk + cmdNameAllocSize); for (int i = 0; i < (int)unit->m_cmdNameSize; i++) unit->m_cmdName[i] = (char)IN0(kVarOffset + i); // terminate string unit->m_cmdName[unit->m_cmdNameSize] = 0; if (INRATE(0) == calc_FullRate) SETCALC(SendReply_next_aka); else SETCALC(SendReply_next); } void SendReply_Dtor(SendReply* unit) { RTFree(unit->mWorld, unit->m_cmdName); } void SendReply_next(SendReply* unit, int inNumSamples) { float* trig = IN(0); float prevtrig = unit->m_prevtrig; float* values = unit->m_values; int valueSize = unit->m_valueSize; int valueOffset = unit->m_valueOffset; for (int j = 0; j < inNumSamples; j++) { float curtrig = trig[j]; if (curtrig > 0.f && prevtrig <= 0.f) { for (int i = 0; i < valueSize; i++) values[i] = IN(i + valueOffset)[0]; SendNodeReply(&unit->mParent->mNode, (int)ZIN0(1), unit->m_cmdName, unit->m_valueSize, values); } prevtrig = curtrig; } unit->m_prevtrig = prevtrig; } void SendReply_next_aka(SendReply* unit, int inNumSamples) { float* trig = IN(0); float prevtrig = unit->m_prevtrig; float* values = unit->m_values; int valueSize = unit->m_valueSize; int valueOffset = unit->m_valueOffset; for (int j = 0; j < inNumSamples; j++) { float curtrig = trig[j]; if (curtrig > 0.f && prevtrig <= 0.f) { for (int i = 0; i < valueSize; i++) { int offset = INRATE(i + valueOffset) != calc_FullRate ? 0 : j; values[i] = IN(i + valueOffset)[offset]; } SendNodeReply(&unit->mParent->mNode, (int)ZIN0(1), unit->m_cmdName, unit->m_valueSize, values); } prevtrig = curtrig; } unit->m_prevtrig = prevtrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Poll_Ctor(Poll* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Poll_next_aa); } else { SETCALC(Poll_next_ak); } } else { SETCALC(Poll_next_kk); } const int idSize = (int)IN0(3); // number of chars in the id string unit->m_id_string = (char*)RTAlloc(unit->mWorld, (idSize + 1) * sizeof(char)); ClearUnitIfMemFailed(unit->m_id_string); for (int i = 0; i < idSize; i++) unit->m_id_string[i] = (char)IN0(4 + i); unit->m_id_string[idSize] = '\0'; unit->m_mayprint = unit->mWorld->mVerbosity >= -1; unit->m_trig = 0.f; // ready for trigger in first sample } void Poll_Dtor(Poll* unit) { RTFree(unit->mWorld, unit->m_id_string); } void Poll_next_aa(Poll* unit, int inNumSamples) { float* in = IN(1); float* trig = IN(0); float lasttrig = unit->m_trig; for (int i = 0; i < inNumSamples; i++) { if ((lasttrig <= 0.0) && (trig[i] > 0.0)) { if (unit->m_mayprint) Print("%s: %g\n", unit->m_id_string, in[i]); if (IN0(2) >= 0.0) SendTrigger(&unit->mParent->mNode, (int)IN0(2), in[i]); } lasttrig = trig[i]; } unit->m_trig = lasttrig; } void Poll_next_kk(Poll* unit, int inNumSamples) { float in = IN0(1); float trig = IN0(0); if ((unit->m_trig <= 0.0) && (trig > 0.0)) { if (unit->m_mayprint) Print("%s: %g\n", unit->m_id_string, in); if (IN0(2) >= 0.0) SendTrigger(&unit->mParent->mNode, (int)IN0(2), in); } unit->m_trig = trig; } void Poll_next_ak(Poll* unit, int inNumSamples) { float in = IN0(1); float* trig = IN(0); float lasttrig = unit->m_trig; for (int i = 0; i < inNumSamples; i++) { if ((lasttrig <= 0.0) && (trig[i] > 0.0)) { if (unit->m_mayprint) { Print("%s: %g\n", unit->m_id_string, in); } if (IN0(2) >= 0.0) SendTrigger(&unit->mParent->mNode, (int)IN0(2), in); } lasttrig = trig[i]; } unit->m_trig = lasttrig; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void SetResetFF_Ctor(SetResetFF* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(SetResetFF_next_a); } else { SETCALC(SetResetFF_next_k); } unit->m_prevtrig = 0.f; unit->m_prevreset = 0.f; unit->mLevel = 0.f; SetResetFF_next_k(unit, 1); } void SetResetFF_next_a(SetResetFF* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float* reset = ZIN(1); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; LOOP1(inNumSamples, float curtrig = ZXP(trig); float curreset = ZXP(reset); if (prevreset <= 0.f && curreset > 0.f) level = 0.f; else if (prevtrig <= 0.f && curtrig > 0.f) level = 1.f; ZXP(out) = level; prevtrig = curtrig; prevreset = curreset;); unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; unit->mLevel = level; } void SetResetFF_next_k(SetResetFF* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float curreset = ZIN0(1); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; float curtrig = ZXP(trig); if (prevreset <= 0.f && curreset > 0.f) level = 0.f; else if (prevtrig <= 0.f && curtrig > 0.f) level = 1.f; ZXP(out) = level; prevtrig = curtrig; LOOP(inNumSamples - 1, curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) level = 1.f; ZXP(out) = level; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->m_prevreset = curreset; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void ToggleFF_Ctor(ToggleFF* unit) { SETCALC(ToggleFF_next); unit->m_prevtrig = 0.f; unit->mLevel = 0.f; ZOUT0(0) = 0.f; } void ToggleFF_next(ToggleFF* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1(inNumSamples, float curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) level = 1.f - level; ZXP(out) = level; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD void Latch_next_ak_nova(Latch* unit, int inNumSamples) { float level = unit->mLevel; float curtrig = ZIN0(1); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = ZIN0(0); nova::setvec_simd(OUT(0), level, inNumSamples); unit->m_prevtrig = curtrig; unit->mLevel = level; } void Latch_next_ak_nova_64(Latch* unit, int inNumSamples) { float level = unit->mLevel; float curtrig = ZIN0(1); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = ZIN0(0); nova::setvec_simd<64>(OUT(0), level); unit->m_prevtrig = curtrig; unit->mLevel = level; } #endif void Latch_Ctor(Latch* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(Latch_next_aa); } else { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(Latch_next_ak_nova_64); if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Latch_next_ak_nova); else #endif SETCALC(Latch_next_ak); } unit->m_prevtrig = 0.f; unit->mLevel = 0.f; ZOUT0(0) = ZIN0(1) > 0.f ? ZIN0(0) : 0.f; } void Latch_next_ak(Latch* unit, int inNumSamples) { float* out = ZOUT(0); float level = unit->mLevel; float curtrig = ZIN0(1); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = ZIN0(0); LOOP1(inNumSamples, ZXP(out) = level;); unit->m_prevtrig = curtrig; unit->mLevel = level; } void Latch_next_aa(Latch* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) level = ZXP(in); else { PZ(in); } ZXP(out) = level; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef NOVA_SIMD FLATTEN void Gate_next_ak_nova(Gate* unit, int inNumSamples) { float* trig = ZIN(1); float level = unit->mLevel; float curtrig = ZXP(trig); if (curtrig > 0.f) { nova::copyvec_simd(OUT(0), IN(0), inNumSamples); unit->mLevel = IN(0)[inNumSamples - 1]; } else nova::setvec_simd(OUT(0), level, inNumSamples); } FLATTEN void Gate_next_ak_nova_64(Gate* unit, int inNumSamples) { float* trig = ZIN(1); float level = unit->mLevel; float curtrig = ZXP(trig); if (curtrig > 0.f) { nova::copyvec_simd<64>(OUT(0), IN(0)); unit->mLevel = IN(0)[inNumSamples - 1]; } else nova::setvec_simd<64>(OUT(0), level); } #endif void Gate_Ctor(Gate* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(Gate_next_aa); } else { #ifdef NOVA_SIMD if (BUFLENGTH == 64) SETCALC(Gate_next_ak_nova_64); if (boost::alignment::is_aligned(BUFLENGTH, 16)) SETCALC(Gate_next_ak_nova); else #endif SETCALC(Gate_next_ak); } unit->mLevel = 0.f; Gate_next_ak(unit, 1); } void Gate_next_ak(Gate* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float level = unit->mLevel; float curtrig = ZXP(trig); if (curtrig > 0.f) { LOOP1(inNumSamples, level = ZXP(in); ZXP(out) = level;); unit->mLevel = level; } else { LOOP1(inNumSamples, ZXP(out) = level;); } } void Gate_next_aa(Gate* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (curtrig > 0.f) level = ZXP(in); else { PZ(in); } ZXP(out) = level;); unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Schmidt_Ctor(Schmidt* unit) { SETCALC(Schmidt_next); unit->mLevel = 0.f; Schmidt_next(unit, 1); } void Schmidt_next(Schmidt* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lo = ZIN0(1); float hi = ZIN0(2); float level = unit->mLevel; LOOP1( inNumSamples, float zin = ZXP(in); if (level == 1.) { if (zin < lo) level = 0.f; } else { if (zin > hi) level = 1.f; } ZXP(out) = level;); unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PulseDivider_Ctor(PulseDivider* unit) { SETCALC(PulseDivider_next); unit->m_prevtrig = 0.f; unit->mLevel = 0.f; unit->mCounter = (long)floor(ZIN0(2) + 0.5); PulseDivider_next(unit, 1); } void PulseDivider_next(PulseDivider* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); long div = (long)ZIN0(1); float prevtrig = unit->m_prevtrig; long counter = unit->mCounter; LOOP1( inNumSamples, float z; float curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) { counter++; if (counter >= div) { counter = 0; z = 1.f; } else { z = 0.f; } } else { z = 0.f; } ZXP(out) = z; prevtrig = curtrig;); unit->mCounter = counter; unit->m_prevtrig = prevtrig; } ////////////////////////////////////////////////////////////////////////////////////////// void PulseCount_Ctor(PulseCount* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(PulseCount_next_a); } else if (INRATE(1) == calc_BufRate) { SETCALC(PulseCount_next_k); } else { SETCALC(PulseCount_next_0); } unit->m_prevtrig = 0.f; unit->m_prevreset = 0.f; unit->mLevel = 0.f; PulseCount_next_k(unit, 1); } void PulseCount_next_a(PulseCount* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float* reset = ZIN(1); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); float curreset = ZXP(reset); if (prevreset <= 0.f && curreset > 0.f) level = 0.f; else if (prevtrig <= 0.f && curtrig > 0.f) { level += 1.f; } ZXP(out) = level; prevtrig = curtrig; prevreset = curreset;); unit->mLevel = level; unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void PulseCount_next_k(PulseCount* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float curreset = ZIN0(1); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (prevreset <= 0.f && curreset > 0.f) level = 0.f; else if (prevtrig <= 0.f && curtrig > 0.f) { level += 1.f; } ZXP(out) = level; prevtrig = curtrig; prevreset = curreset;); unit->mLevel = level; unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void PulseCount_next_0(PulseCount* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) { level += 1.f; } ZXP(out) = level; prevtrig = curtrig;); unit->mLevel = level; unit->m_prevtrig = prevtrig; } ////////////////////////////////////////////////////////////////////////////////////////// void Stepper_Ctor(Stepper* unit) { if (unit->mCalcRate == calc_FullRate && INRATE(0) == calc_FullRate && INRATE(1) == calc_ScalarRate) { SETCALC(Stepper_next_a0); } else if (unit->mCalcRate == calc_FullRate && INRATE(0) == calc_FullRate && INRATE(1) != calc_FullRate) { SETCALC(Stepper_next_ak); } else { SETCALC(Stepper_next_aa); } int32 resetval = (int32)ZIN0(5); unit->m_prevtrig = 0.f; unit->m_prevreset = 0.f; unit->mLevel = (float)resetval; Stepper_next_ak(unit, 1); } void Stepper_next_aa(Stepper* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float* reset = ZIN(1); int32 zmin = (int32)ZIN0(2); int32 zmax = (int32)ZIN0(3); int32 step = (int32)ZIN0(4); int32 resetval = (int32)ZIN0(5); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); float curreset = ZXP(reset); if (prevreset <= 0.f && curreset > 0.f) { level = (float)sc_wrap(resetval, zmin, zmax); } else if (prevtrig <= 0.f && curtrig > 0.f) { level = (float)sc_wrap((int32)level + step, zmin, zmax); } ZXP(out) = level; prevtrig = curtrig; prevreset = curreset;); unit->mLevel = level; unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void Stepper_next_ak(Stepper* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float curreset = ZIN0(1); int32 zmin = (int32)ZIN0(2); int32 zmax = (int32)ZIN0(3); int32 step = (int32)ZIN0(4); int32 resetval = (int32)ZIN0(5); float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (prevreset <= 0.f && curreset > 0.f) { level = (float)sc_wrap(resetval, zmin, zmax); } else if (prevtrig <= 0.f && curtrig > 0.f) { level = (float)sc_wrap((int32)level + step, zmin, zmax); } ZXP(out) = level; prevtrig = curtrig; prevreset = curreset;); unit->mLevel = level; unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void Stepper_next_a0(Stepper* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); int32 zmin = (int32)ZIN0(2); int32 zmax = (int32)ZIN0(3); int32 step = (int32)ZIN0(4); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1( inNumSamples, float curtrig = ZXP(trig); if (prevtrig <= 0.f && curtrig > 0.f) { level = (float)sc_wrap((int32)level + step, zmin, zmax); } ZXP(out) = level; prevtrig = curtrig;); unit->mLevel = level; unit->m_prevtrig = prevtrig; } ////////////////////////////////////////////////////////////////////////////////////////// void TDelay_Ctor(TDelay* unit) { SETCALC(TDelay_next); unit->m_prevtrig = 0.f; unit->mCounter = 0; TDelay_next(unit, 1); } void TDelay_next(TDelay* unit, int inNumSamples) { float* out = ZOUT(0); float* trig = ZIN(0); float dur = ZIN0(1); float prevtrig = unit->m_prevtrig; long counter = unit->mCounter; LOOP1( inNumSamples, float curtrig = ZXP(trig); float zout; if (counter > 1) { counter--; zout = 0.f; } else if (counter <= 0) { if (prevtrig <= 0.f && curtrig > 0.f) { counter = (long)(dur * unit->mRate->mSampleRate + .5f); if (counter < 1) counter = 1; } zout = 0.f; } else { counter = 0; zout = 1.f; } ZXP(out) = zout; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mCounter = counter; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void ZeroCrossing_Ctor(ZeroCrossing* unit) { SETCALC(ZeroCrossing_next_a); unit->m_prevfrac = 0.f; unit->m_previn = ZIN0(0); ZOUT0(0) = unit->mLevel = 0.f; unit->mCounter = 0; } void ZeroCrossing_next_a(ZeroCrossing* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float previn = unit->m_previn; float prevfrac = unit->m_prevfrac; float level = unit->mLevel; long counter = unit->mCounter; LOOP1( inNumSamples, counter++; float curin = ZXP(in); if (counter > 4 && previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = unit->mRate->mSampleRate / (frac + counter - prevfrac); prevfrac = frac; counter = 0; } ZXP(out) = level; previn = curin;); unit->m_previn = previn; unit->m_prevfrac = prevfrac; unit->mLevel = level; unit->mCounter = counter; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Timer_Ctor(Timer* unit) { SETCALC(Timer_next_a); unit->m_prevfrac = 0.f; unit->m_previn = ZIN0(0); ZOUT0(0) = unit->mLevel = 0.f; unit->mCounter = 0; } void Timer_next_a(Timer* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float previn = unit->m_previn; float prevfrac = unit->m_prevfrac; float level = unit->mLevel; long counter = unit->mCounter; LOOP1( inNumSamples, counter++; float curin = ZXP(in); if (previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = unit->mRate->mSampleDur * (frac + counter - prevfrac); prevfrac = frac; counter = 0; } ZXP(out) = level; previn = curin;); unit->m_previn = previn; unit->m_prevfrac = prevfrac; unit->mLevel = level; unit->mCounter = counter; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Sweep_Ctor(Sweep* unit) { if (INRATE(0) == calc_ScalarRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Sweep_next_0a); } else { SETCALC(Sweep_next_0k); } } else if (INRATE(0) == calc_BufRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Sweep_next_ka); } else { SETCALC(Sweep_next_kk); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(Sweep_next_aa); } else { SETCALC(Sweep_next_ak); } } unit->m_previn = ZIN0(0); ZOUT0(0) = unit->mLevel = 0.f; } void Sweep_next_0k(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); double rate = ZIN0(1) * SAMPLEDUR; double level = unit->mLevel; LOOP1(inNumSamples, level += rate; ZXP(out) = level;); unit->mLevel = level; } void Sweep_next_0a(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); float* rate = ZIN(1); double level = unit->mLevel; float sampledur = SAMPLEDUR; LOOP1(inNumSamples, float zrate = ZXP(rate) * sampledur; level += zrate; ZXP(out) = level;); unit->mLevel = level; } void Sweep_next_kk(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); float curin = ZIN0(0); double rate = ZIN0(1) * SAMPLEDUR; float previn = unit->m_previn; double level = unit->mLevel; if (previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = frac * rate; } LOOP1(inNumSamples, level += rate; ZXP(out) = level;); unit->m_previn = curin; unit->mLevel = level; } void Sweep_next_ka(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); float curin = ZIN0(0); float* rate = ZIN(1); float previn = unit->m_previn; double level = unit->mLevel; float sampledur = SAMPLEDUR; if (previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = frac * rate[ZOFF] * sampledur; } LOOP1(inNumSamples, float zrate = ZXP(rate) * sampledur; level += zrate; ZXP(out) = level;); unit->m_previn = curin; unit->mLevel = level; } void Sweep_next_ak(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double rate = ZIN0(1) * SAMPLEDUR; float previn = unit->m_previn; double level = unit->mLevel; LOOP1( inNumSamples, float curin = ZXP(in); if (previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = frac * rate; } else { level += rate; } ZXP(out) = level; previn = curin;); unit->m_previn = previn; unit->mLevel = level; } void Sweep_next_aa(Sweep* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* rate = ZIN(1); float previn = unit->m_previn; double level = unit->mLevel; float sampledur = SAMPLEDUR; LOOP1( inNumSamples, float curin = ZXP(in); float zrate = ZXP(rate) * sampledur; if (previn <= 0.f && curin > 0.f) { float frac = -previn / (curin - previn); level = frac * zrate; } else { level += zrate; } ZXP(out) = level; previn = curin;); unit->m_previn = previn; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Phasor_Ctor(Phasor* unit) { if (unit->mCalcRate == calc_FullRate) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Phasor_next_aa); } else { SETCALC(Phasor_next_ak); } } else { SETCALC(Phasor_next_kk); } } else { SETCALC(Phasor_next_ak); } unit->m_previn = ZIN0(0); ZOUT0(0) = unit->mLevel = ZIN0(2); } void Phasor_next_kk(Phasor* unit, int inNumSamples) { float* out = ZOUT(0); float in = ZIN0(0); double rate = ZIN0(1); double start = ZIN0(2); double end = ZIN0(3); float resetPos = ZIN0(4); float previn = unit->m_previn; double level = unit->mLevel; if (previn <= 0.f && in > 0.f) { level = resetPos; } LOOP1(inNumSamples, level = sc_wrap(level, start, end); ZXP(out) = level; level += rate;); unit->m_previn = in; unit->mLevel = level; } void Phasor_next_ak(Phasor* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double rate = ZIN0(1); double start = ZIN0(2); double end = ZIN0(3); float resetPos = ZIN0(4); float previn = unit->m_previn; double level = unit->mLevel; LOOP1( inNumSamples, float curin = ZXP(in); if (previn <= 0.f && curin > 0.f) { float frac = 1.f - previn / (curin - previn); level = resetPos + frac * rate; } ZXP(out) = level; level += rate; level = sc_wrap(level, start, end); previn = curin;); unit->m_previn = previn; unit->mLevel = level; } void Phasor_next_aa(Phasor* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* rate = ZIN(1); double start = ZIN0(2); double end = ZIN0(3); float resetPos = ZIN0(4); float previn = unit->m_previn; double level = unit->mLevel; LOOP1( inNumSamples, float curin = ZXP(in); double zrate = ZXP(rate); if (previn <= 0.f && curin > 0.f) { float frac = 1.f - previn / (curin - previn); level = resetPos + frac * zrate; } ZXP(out) = level; level += zrate; level = sc_wrap(level, start, end); previn = curin;); unit->m_previn = previn; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Peak_next_ak_unroll(Peak* unit, int inNumSamples); void Peak_next_ai_unroll(Peak* unit, int inNumSamples); #ifdef NOVA_SIMD FLATTEN void Peak_next_ak_k_nova(Peak* unit, int inNumSamples); FLATTEN void Peak_next_ai_k_nova(Peak* unit, int inNumSamples); #endif void Peak_Ctor(Peak* unit) { if (BUFLENGTH == 1 && INRATE(0) == calc_FullRate) { /* audio-rate input with control-rate output */ if (INRATE(1) == calc_FullRate) { SETCALC(Peak_next_aa_k); } else if (INRATE(1) == calc_ScalarRate) { #ifdef NOVA_SIMD if (INBUFLENGTH(0) & 7) SETCALC(Peak_next_ai_k); else SETCALC(Peak_next_ai_k_nova); #else SETCALC(Peak_next_ai_k); #endif } else { #ifdef NOVA_SIMD if (INBUFLENGTH(0) & 7) SETCALC(Peak_next_ak_k); else SETCALC(Peak_next_ak_k_nova); #else SETCALC(Peak_next_ak_k); #endif } } else { if (INRATE(1) == calc_FullRate) { SETCALC(Peak_next_aa); } else if (INRATE(1) == calc_ScalarRate) { if (BUFLENGTH & 15) SETCALC(Peak_next_ai); else SETCALC(Peak_next_ai_unroll); } else { if (BUFLENGTH & 15) SETCALC(Peak_next_ak); else SETCALC(Peak_next_ak_unroll); } } unit->m_prevtrig = 0.f; ZOUT0(0) = unit->mLevel = ZIN0(0); } void Peak_next_ak(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float curtrig = ZIN0(1); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = std::abs(ZXP(in)); level = std::max(inlevel, level); ZXP(out) = level;); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = inlevel; unit->m_prevtrig = curtrig; unit->mLevel = level; } void Peak_next_ai(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = std::abs(ZXP(in)); level = std::max(inlevel, level); ZXP(out) = level;); unit->mLevel = level; } void Peak_next_aa(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1(inNumSamples, float curtrig = ZXP(trig); float inlevel = std::abs(ZXP(in)); level = std::max(inlevel, level); ZXP(out) = level; if (prevtrig <= 0.f && curtrig > 0.f) level = inlevel; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mLevel = level; } static inline float Peak_unroll_body(Peak* unit, int inNumSamples, float& level) { float* out = OUT(0); float* in = IN(0); float inlevel; using namespace std; for (int i = 0; i != inNumSamples; i += 8, out += 8, in += 8) { float level0 = max(abs(in[0]), level); float level1 = max(abs(in[1]), level0); float level2 = max(abs(in[2]), level1); float level3 = max(abs(in[3]), level2); float level4 = max(abs(in[4]), level3); float level5 = max(abs(in[5]), level4); float level6 = max(abs(in[6]), level5); inlevel = abs(in[7]); float level7 = max(inlevel, level6); out[0] = level0; out[1] = level1; out[2] = level2; out[3] = level3; out[4] = level4; out[5] = level5; out[6] = level6; out[7] = level7; level = level7; } return inlevel; /* input level of the last sample */ } void Peak_next_ak_unroll(Peak* unit, int inNumSamples) { float curtrig = ZIN0(1); float level = unit->mLevel; float inlevel = Peak_unroll_body(unit, inNumSamples, level); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = inlevel; unit->m_prevtrig = curtrig; unit->mLevel = level; } void Peak_next_ai_unroll(Peak* unit, int inNumSamples) { float level = unit->mLevel; Peak_unroll_body(unit, inNumSamples, level); unit->mLevel = level; } void Peak_next_ak_k(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float curtrig = ZIN0(1); float level; inNumSamples = INBUFLENGTH(0); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { level = std::abs(ZXP(in)); inNumSamples -= 1; } else level = unit->mLevel; LOOP1(inNumSamples, level = std::max(std::abs(ZXP(in)), level);); ZXP(out) = level; unit->m_prevtrig = curtrig; unit->mLevel = level; } void Peak_next_ai_k(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float level = unit->mLevel; inNumSamples = INBUFLENGTH(0); LOOP1(inNumSamples, level = std::max(std::abs(ZXP(in)), level);); ZXP(out) = level; unit->mLevel = level; } void Peak_next_aa_k(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; float out_level; bool triggered = false; inNumSamples = INBUFLENGTH(0); LOOP1( inNumSamples, float curtrig = ZXP(trig); float inlevel = std::abs(ZXP(in)); level = std::max(inlevel, level); if (prevtrig <= 0.f && curtrig > 0.f) { triggered = true; out_level = level; level = inlevel; } prevtrig = curtrig;); if (triggered) ZXP(out) = out_level; else ZXP(out) = level; unit->m_prevtrig = prevtrig; unit->mLevel = level; } #ifdef NOVA_SIMD void Peak_next_ak_k_nova(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = IN(0); float curtrig = ZIN0(1); float level = unit->mLevel; float inlevel; inNumSamples = INBUFLENGTH(0); inlevel = nova::peak_vec_simd(in, &level, inNumSamples); ZXP(out) = level; if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = inlevel; unit->m_prevtrig = curtrig; unit->mLevel = level; } void Peak_next_ai_k_nova(Peak* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float level = unit->mLevel; float inlevel; inNumSamples = INBUFLENGTH(0); inlevel = nova::peak_vec_simd(in, &level, inNumSamples); ZXP(out) = level; unit->mLevel = level; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////// void RunningMin_Ctor(RunningMin* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(RunningMin_next_aa); } else if (INRATE(1) == calc_ScalarRate) { SETCALC(RunningMin_next_ai); } else { SETCALC(RunningMin_next_ak); } unit->m_prevtrig = 0.f; ZOUT0(0) = unit->mLevel = ZIN0(0); } void RunningMin_next_ak(RunningMin* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float curtrig = ZIN0(1); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = ZXP(in); if (inlevel < level) level = inlevel; ZXP(out) = level;); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = inlevel; unit->m_prevtrig = curtrig; unit->mLevel = level; } void RunningMin_next_ai(RunningMin* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = ZXP(in); if (inlevel < level) level = inlevel; ZXP(out) = level;); unit->mLevel = level; } void RunningMin_next_aa(RunningMin* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1(inNumSamples, float curtrig = ZXP(trig); float inlevel = ZXP(in); if (inlevel < level) level = inlevel; ZXP(out) = level; if (prevtrig <= 0.f && curtrig > 0.f) level = inlevel; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void RunningMax_Ctor(RunningMax* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(RunningMax_next_aa); } else if (INRATE(1) == calc_ScalarRate) { SETCALC(RunningMax_next_ai); } else { SETCALC(RunningMax_next_ak); } unit->m_prevtrig = 0.f; ZOUT0(0) = unit->mLevel = ZIN0(0); } void RunningMax_next_ak(RunningMax* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float curtrig = ZIN0(1); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = ZXP(in); if (inlevel > level) level = inlevel; ZXP(out) = level;); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) level = inlevel; unit->m_prevtrig = curtrig; unit->mLevel = level; } void RunningMax_next_ai(RunningMax* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float level = unit->mLevel; float inlevel; LOOP1(inNumSamples, inlevel = ZXP(in); if (inlevel > level) level = inlevel; ZXP(out) = level;); unit->mLevel = level; } void RunningMax_next_aa(RunningMax* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* trig = ZIN(1); float prevtrig = unit->m_prevtrig; float level = unit->mLevel; LOOP1(inNumSamples, float curtrig = ZXP(trig); float inlevel = ZXP(in); if (inlevel > level) level = inlevel; ZXP(out) = level; if (prevtrig <= 0.f && curtrig > 0.f) level = inlevel; prevtrig = curtrig;); unit->m_prevtrig = prevtrig; unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void PeakFollower_Ctor(PeakFollower* unit) { if (INRATE(1) == calc_ScalarRate) { SETCALC(PeakFollower_next_ai); } else { SETCALC(PeakFollower_next); } unit->mDecay = ZIN0(1); ZOUT0(0) = unit->mLevel = ZIN0(0); } void PeakFollower_next(PeakFollower* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float decay = ZIN0(1); float level = unit->mLevel; if (decay == unit->mDecay) { LOOP1( inNumSamples, float inlevel = std::abs(ZXP(in)); if (inlevel >= level) { level = inlevel; } else { level = inlevel + decay * (level - inlevel); } ZXP(out) = level;); } else { float decay_slope = CALCSLOPE(decay, unit->mDecay); if (decay >= 0.f && unit->mDecay >= 0.f) { LOOP1( inNumSamples, float inlevel = std::abs(ZXP(in)); if (inlevel >= level) { level = inlevel; } else { level = inlevel + decay * (level - inlevel); decay += decay_slope; }; ZXP(out) = level;); } else if (decay <= 0.f && unit->mDecay <= 0.f) { LOOP1( inNumSamples, float inlevel = std::abs(ZXP(in)); if (inlevel >= level) { level = inlevel; } else { level = inlevel + decay * (level + inlevel); decay += decay_slope; }; ZXP(out) = level;); } else { LOOP1( inNumSamples, float inlevel = std::abs(ZXP(in)); if (inlevel >= level) { level = inlevel; } else { level = (1.f - std::abs(decay)) * inlevel + decay * level; decay += decay_slope; }; ZXP(out) = level;); }; } unit->mLevel = level; unit->mDecay = decay; } void PeakFollower_next_ai(PeakFollower* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float decay = ZIN0(1); float level = unit->mLevel; LOOP1( inNumSamples, float inlevel = std::abs(ZXP(in)); if (inlevel >= level) { level = inlevel; } else { level = inlevel + decay * (level - inlevel); } ZXP(out) = level;); unit->mLevel = level; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void MostChange_Ctor(MostChange* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(MostChange_next_aa); } else { SETCALC(MostChange_next_ak); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(MostChange_next_ka); } else { SETCALC(MostChange_next_aa); } } unit->mPrevA = 0.f; unit->mPrevB = 0.f; unit->mRecent = 1; MostChange_next_aa(unit, 1); } void MostChange_next_ak(MostChange* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xa = ZXP(a); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff > 0.f) { recent = 0; ZXP(out) = xa; } else if (diff < 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } void MostChange_next_aa(MostChange* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xa = ZXP(a); float xb = ZXP(b); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff > 0.f) { recent = 0; ZXP(out) = xa; } else if (diff < 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } void MostChange_next_ka(MostChange* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xb = ZXP(b); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff > 0.f) { recent = 0; ZXP(out) = xa; } else if (diff < 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LeastChange_Ctor(LeastChange* unit) { if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(LeastChange_next_aa); } else { SETCALC(LeastChange_next_ak); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(LeastChange_next_ka); } else { SETCALC(LeastChange_next_aa); } } unit->mPrevA = 0.f; unit->mPrevB = 0.f; unit->mRecent = 0; LeastChange_next_aa(unit, 1); } void LeastChange_next_ak(LeastChange* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float xb = ZIN0(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xa = ZXP(a); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff < 0.f) { recent = 0; ZXP(out) = xa; } else if (diff > 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } void LeastChange_next_aa(LeastChange* unit, int inNumSamples) { float* out = ZOUT(0); float* a = ZIN(0); float* b = ZIN(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xa = ZXP(a); float xb = ZXP(b); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff < 0.f) { recent = 0; ZXP(out) = xa; } else if (diff > 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } void LeastChange_next_ka(LeastChange* unit, int inNumSamples) { float* out = ZOUT(0); float xa = ZIN0(0); float* b = ZIN(1); float prevA = unit->mPrevA; float prevB = unit->mPrevB; int recent = unit->mRecent; LOOP1( inNumSamples, float xb = ZXP(b); float diff = std::abs(xa - prevA) - std::abs(xb - prevB); if (diff < 0.f) { recent = 0; ZXP(out) = xa; } else if (diff > 0.f) { recent = 1; ZXP(out) = xb; } else { ZXP(out) = recent ? xb : xa; } prevA = xa; prevB = xb;); unit->mPrevA = prevA; unit->mPrevB = prevB; unit->mRecent = recent; } //////////////////// void LastValue_Ctor(LastValue* unit) { if (INRATE(0) == calc_FullRate) { SETCALC(LastValue_next_ak); } else { SETCALC(LastValue_next_kk); } unit->mPrev = ZIN0(0); unit->mCurr = ZIN0(0); LastValue_next_kk(unit, 1); } void LastValue_next_kk(LastValue* unit, int inNumSamples) { float* out = ZOUT(0); float inval = ZIN0(0); float delta = ZIN0(1); float diff = std::abs(inval - unit->mCurr); if (diff >= delta) { unit->mPrev = unit->mCurr; unit->mCurr = inval; } float level = unit->mPrev; LOOP1(inNumSamples, ZXP(out) = level;); } void LastValue_next_ak(LastValue* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float delta = ZIN0(1); float prev = unit->mPrev; float curr = unit->mCurr; LOOP1( inNumSamples, float inval = ZXP(in); float diff = std::abs(inval - curr); if (diff >= delta) { prev = curr; curr = inval; } ZXP(out) = prev); unit->mPrev = prev; unit->mCurr = curr; } ////////////////////////////////////////////////////////////////////////////////////////// void Done_Ctor(Done* unit) { SETCALC(Done_next); unit->m_src = unit->mInput[0]->mFromUnit; Done_next(unit, 1); } void Done_next(Done* unit, int inNumSamples) { float* out = OUT(0); Unit* src = unit->m_src; if (src) *out = src->mDone ? 1.f : 0.f; else *out = 0.f; } ////////////////////////////////////////////////////////////////////////////////////////// void FreeSelf_Ctor(FreeSelf* unit) { SETCALC(FreeSelf_next); unit->m_prevtrig = 0.f; FreeSelf_next(unit, 1); unit->m_prevtrig = 0.f; } void FreeSelf_next(FreeSelf* unit, int inNumSamples) { float in = ZIN0(0); if (in > 0.f && unit->m_prevtrig <= 0.f) { NodeEnd(&unit->mParent->mNode); } unit->m_prevtrig = in; } ////////////////////////////////////////////////////////////////////////////////////////// void PauseSelf_Ctor(PauseSelf* unit) { SETCALC(PauseSelf_next); unit->m_prevtrig = 0.f; PauseSelf_next(unit, 1); unit->m_prevtrig = 0.f; } void PauseSelf_next(PauseSelf* unit, int inNumSamples) { float in = ZIN0(0); if (in > 0.f && unit->m_prevtrig <= 0.f) { NodeRun(&unit->mParent->mNode, 0); } unit->m_prevtrig = in; } ////////////////////////////////////////////////////////////////////////////////////////// void Pause_Ctor(Pause* unit) { SETCALC(Pause_next); unit->m_state = 1; ZOUT0(0) = ZIN0(0); } void Pause_next(Pause* unit, int inNumSamples) { float in = ZIN0(0); int state = in == 0.f ? 0 : 1; if (state != unit->m_state) { unit->m_state = state; int id = (int)ZIN0(1); Node* node = SC_GetNode(unit->mWorld, id); if (node) { NodeRun(node, state); } } ZOUT0(0) = in; } ////////////////////////////////////////////////////////////////////////////////////////// void Free_Ctor(Free* unit) { SETCALC(Free_next); unit->m_prevtrig = 0.f; ZOUT0(0) = ZIN0(0); } void Free_next(Free* unit, int inNumSamples) { float trig = ZIN0(0); if (trig > 0.f && unit->m_prevtrig <= 0) { int id = (int)ZIN0(1); Node* node = SC_GetNode(unit->mWorld, id); if (node) { NodeEnd(node); } } unit->m_prevtrig = trig; ZOUT0(0) = trig; } ////////////////////////////////////////////////////////////////////////////////////////// void FreeSelfWhenDone_Ctor(FreeSelfWhenDone* unit) { unit->m_src = unit->mInput[0]->mFromUnit; if (unit->m_src) { SETCALC(FreeSelfWhenDone_next); FreeSelfWhenDone_next(unit, 1); } else { SETCALC(ClearUnitOutputs); ClearUnitOutputs(unit, 1); } } void FreeSelfWhenDone_next(FreeSelfWhenDone* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); Unit* src = unit->m_src; if (src->mDone) { NodeEnd(&unit->mParent->mNode); SETCALC(ClearUnitOutputs); } *out = *in; } ////////////////////////////////////////////////////////////////////////////////////////// void PauseSelfWhenDone_Ctor(PauseSelfWhenDone* unit) { unit->m_src = unit->mInput[0]->mFromUnit; if (unit->m_src) { SETCALC(PauseSelfWhenDone_next); PauseSelfWhenDone_next(unit, 1); } else { SETCALC(ClearUnitOutputs); ClearUnitOutputs(unit, 1); } } void PauseSelfWhenDone_next(PauseSelfWhenDone* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); Unit* src = unit->m_src; if (src->mDone) { NodeRun(&unit->mParent->mNode, 0); SETCALC(ClearUnitOutputs); } *out = *in; } //////////////////////////////////////////////////////////////////////////////////////////////////////// struct SendPeakRMS : public Unit { // rate, level lag, replyid, channel count, [channels, ], cmd name size, [cmdname, ] static const int rateIndex = 0; static const int levelLagIndex = 1; static const int replyIdIndex = 2; static const int channelCountIndex = 3; static const int signalStartIndex = 4; SendPeakRMS(void) { SendPeakRMS* unit = this; mChannelCount = (unsigned int)IN0(channelCountIndex); size_t channelDataAllocSize = mChannelCount * 3 * sizeof(float); int cmdSizeIndex = signalStartIndex + mChannelCount; size_t cmdNameSize = IN0(cmdSizeIndex); size_t cmdNameAllocSize = (cmdNameSize + 1) * sizeof(char); void* allocData = RTAlloc(unit->mWorld, channelDataAllocSize + cmdNameAllocSize); ClearUnitIfMemFailed(allocData); memset(allocData, 0, channelDataAllocSize); mChannelData = (float*)allocData; char* cmdName = (char*)(allocData) + channelDataAllocSize; size_t cmdNameIndex = cmdSizeIndex + 1; for (int i = 0; i < cmdNameSize; i++) cmdName[i] = (char)IN0(cmdNameIndex + i); cmdName[cmdNameSize] = 0; if ((FULLBUFLENGTH & 15) == 0) { if (mCalcRate == calc_FullRate) SETCALC(SendPeakRMS::perform_a<true>); else SETCALC(SendPeakRMS::perform_k<true>); } else { if (mCalcRate == calc_FullRate) SETCALC(SendPeakRMS::perform_a<false>); else SETCALC(SendPeakRMS::perform_k<false>); } float replyRate = IN0(rateIndex); mAudioSamplesPerTick = FULLRATE / replyRate; mControlSamplesPerTick = BUFRATE / replyRate; mPhaseRemain = (mCalcRate == calc_FullRate) ? mAudioSamplesPerTick : mControlSamplesPerTick; float32 lag = ZIN0(levelLagIndex); mB1 = (lag != 0.f) ? exp(log001 / (lag * replyRate)) : 0.f; } ~SendPeakRMS(void) { SendPeakRMS* unit = this; RTFree(unit->mWorld, mChannelData); } unsigned int mChannelCount; float* mChannelData; float mB1; int mAudioSamplesPerTick; int mControlSamplesPerTick; int mPhaseRemain; void performLevelLag(float& out, float y0, float& y1) { if (y0 >= y1) out = y1 = y0; else out = y1 = y0 + mB1 * (y1 - y0); } char* getCmdName(void) { void* buffer = mChannelData; return (char*)(buffer) + mChannelCount * 3 * sizeof(float); } void sendReply(void) { SendPeakRMS* unit = this; float* reply = (float*)alloca(mChannelCount * 2 * sizeof(float)); for (int i = 0; i != mChannelCount; ++i) { float& maxLevel = reply[2 * i]; float& rms = reply[2 * i + 1]; performLevelLag(maxLevel, mChannelData[2 * i], mChannelData[2 * mChannelCount + i]); if (INRATE(signalStartIndex + i) == calc_FullRate) rms = std::sqrt(mChannelData[2 * i + 1] / (float)mAudioSamplesPerTick); else rms = std::sqrt(mChannelData[2 * i + 1] / (float)mControlSamplesPerTick); } SendNodeReply(&unit->mParent->mNode, (int)ZIN0(replyIdIndex), getCmdName(), mChannelCount * 2, reply); memset(mChannelData, 0, mChannelCount * 2 * sizeof(float)); } template <bool simd> void analyzeFullBlock(void) { SendPeakRMS* unit = this; for (int i = 0; i != mChannelCount; ++i) { float* in = IN(signalStartIndex + i); int numSamples = INBUFLENGTH(signalStartIndex + i); float& level = mChannelData[2 * i]; float& sqrsum = mChannelData[2 * i + 1]; if (numSamples == 1) nova::peak_rms_vec(in, &level, &sqrsum, 1); else { if (simd) nova::peak_rms_vec_simd(in, &level, &sqrsum, numSamples); else nova::peak_rms_vec(in, &level, &sqrsum, numSamples); } } } void analyzePartialBlock(int firstSample, int samplesToAnalyze) { SendPeakRMS* unit = this; for (int i = 0; i != mChannelCount; ++i) { float* in = IN(signalStartIndex + i) + firstSample; int numSamples = INBUFLENGTH(signalStartIndex + i); float& level = mChannelData[2 * i]; float& sqrsum = mChannelData[2 * i + 1]; if (numSamples == 1) { if (firstSample == 0) nova::peak_rms_vec(in, &level, &sqrsum, 1); } else { if (!(samplesToAnalyze & 15) && !(firstSample & 3)) // check for unrolling and alignment nova::peak_rms_vec_simd(in, &level, &sqrsum, samplesToAnalyze); else nova::peak_rms_vec(in, &level, &sqrsum, samplesToAnalyze); } } } template <bool simd> inline void next_k(int inNumSamples) { mPhaseRemain -= 1; if (mPhaseRemain <= 0) { mPhaseRemain += mControlSamplesPerTick; sendReply(); } analyzeFullBlock<simd>(); } template <bool simd> inline void next_a(int inNumSamples) { if (mPhaseRemain >= inNumSamples) { mPhaseRemain -= inNumSamples; analyzeFullBlock<simd>(); } else { if (mPhaseRemain == 0) { sendReply(); mPhaseRemain = mAudioSamplesPerTick; } int startSample = 0; int samplesToAnalyze = std::min(mPhaseRemain, inNumSamples); int remain = inNumSamples; do { analyzePartialBlock(startSample, samplesToAnalyze); startSample += samplesToAnalyze; mPhaseRemain -= samplesToAnalyze; if (mPhaseRemain == 0) { sendReply(); mPhaseRemain = mAudioSamplesPerTick; } remain -= samplesToAnalyze; samplesToAnalyze = std::min(remain, mPhaseRemain); } while (remain); } } template <bool simd> static void perform_k(Unit* unit, int inNumSamples) { static_cast<SendPeakRMS*>(unit)->next_k<simd>(inNumSamples); } template <bool simd> static void perform_a(Unit* unit, int inNumSamples) { static_cast<SendPeakRMS*>(unit)->next_a<simd>(inNumSamples); } }; static void SendPeakRMS_Ctor(SendPeakRMS* unit) { new (unit) SendPeakRMS(); } static void SendPeakRMS_Dtor(SendPeakRMS* unit) { unit->~SendPeakRMS(); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Trigger) { ft = inTable; DefineSimpleUnit(Trig1); DefineSimpleUnit(Trig); DefineSimpleUnit(SendTrig); DefineDtorUnit(SendReply); DefineDtorUnit(Poll); DefineSimpleUnit(ToggleFF); DefineSimpleUnit(SetResetFF); DefineSimpleUnit(Latch); DefineSimpleUnit(Gate); DefineSimpleUnit(Schmidt); DefineSimpleUnit(PulseDivider); DefineSimpleUnit(PulseCount); DefineSimpleUnit(Stepper); DefineSimpleUnit(TDelay); DefineSimpleUnit(ZeroCrossing); DefineSimpleUnit(Timer); DefineSimpleUnit(Sweep); DefineSimpleUnit(Phasor); DefineSimpleUnit(Peak); DefineSimpleUnit(RunningMin); DefineSimpleUnit(RunningMax); DefineSimpleUnit(PeakFollower); DefineSimpleUnit(MostChange); DefineSimpleUnit(LeastChange); DefineSimpleUnit(LastValue); DefineSimpleUnit(Done); DefineSimpleUnit(Pause); DefineSimpleUnit(FreeSelf); DefineSimpleUnit(PauseSelf); DefineSimpleUnit(Free); DefineSimpleUnit(FreeSelfWhenDone); DefineSimpleUnit(PauseSelfWhenDone); DefineDtorUnit(SendPeakRMS); }
76,066
C++
.cpp
2,165
28.671132
120
0.567661
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
29,947
KeyTrack.cpp
supercollider_supercollider/server/plugins/KeyTrack.cpp
/* 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 */ // Nick Collins 20 Feb 2006 // revision of algorithm 22 Nov 2007 // Key tracker using weights of FFT bins. #include "ML.h" #include "FFT_UGens.h" // hard coded FFT size #define N 4096 #define NOVER2 2048 // CONVERT TO m_frameperiod to cope with different sampling rates? #define FRAMEPERIOD 0.046439909297052 // weighting parameters // 4096 FFT at 44100 SR static float g_weights44100[720] = { 0.89160997732426, 0.10839002267574, 0.39160997732426, 0.10839002267574, 0.2249433106576, 0.10839002267574, 0.14160997732426, 0.10839002267574, 0.091609977324263, 0.10839002267574, 0.05827664399093, 0.10839002267574, 0.58784929938181, 0.41215070061819, 0.087849299381813, 0.41215070061819, 0.25451596604848, 0.078817367284855, 0.087849299381813, 0.16215070061819, 0.18784929938181, 0.012150700618187, 0.087849299381812, 0.078817367284855, 0.26602607158423, 0.73397392841577, 0.26602607158423, 0.23397392841577, 0.26602607158423, 0.067307261749107, 0.016026071584227, 0.23397392841577, 0.066026071584226, 0.13397392841577, 0.099359404917559, 0.067307261749107, 0.9250662388251, 0.074933761174898, 0.4250662388251, 0.074933761174898, 0.25839957215844, 0.074933761174898, 0.1750662388251, 0.074933761174898, 0.1250662388251, 0.074933761174898, 0.091732905491768, 0.074933761174898, 0.56383187935789, 0.43616812064211, 0.063831879357891, 0.43616812064211, 0.23049854602456, 0.10283478730877, 0.063831879357891, 0.18616812064211, 0.16383187935789, 0.03616812064211, 0.063831879357892, 0.10283478730877, 0.18111740708786, 0.81888259291214, 0.18111740708786, 0.31888259291214, 0.18111740708786, 0.15221592624547, 0.18111740708786, 0.068882592912141, 0.18111740708786, 0.018882592912141, 0.014450740421193, 0.15221592624547, 0.77564554804057, 0.22435445195943, 0.27564554804057, 0.22435445195943, 0.1089788813739, 0.22435445195943, 0.02564554804057, 0.22435445195943, 0.17564554804057, 0.024354451959429, 0.1089788813739, 0.057687785292764, 0.34606307757871, 0.65393692242129, 0.34606307757871, 0.15393692242129, 0.012729744245378, 0.32060358908796, 0.096063077578711, 0.15393692242129, 0.14606307757871, 0.053936922421289, 0.012729744245378, 0.15393692242129, 0.89093630414068, 0.10906369585932, 0.39093630414068, 0.10906369585932, 0.22426963747401, 0.10906369585932, 0.14093630414068, 0.10906369585932, 0.090936304140679, 0.10906369585932, 0.057602970807346, 0.10906369585932, 0.40874628442826, 0.59125371557174, 0.40874628442826, 0.091253715571737, 0.075412951094929, 0.2579203822384, 0.15874628442826, 0.091253715571737, 0.0087462844282626, 0.19125371557174, 0.075412951094929, 0.091253715571738, 0.89788375407457, 0.10211624592543, 0.39788375407457, 0.10211624592543, 0.23121708740791, 0.10211624592543, 0.14788375407457, 0.10211624592543, 0.097883754074573, 0.10211624592543, 0.06455042074124, 0.10211624592543, 0.35664375687383, 0.64335624312617, 0.35664375687383, 0.14335624312617, 0.023310423540502, 0.31002290979283, 0.10664375687383, 0.14335624312617, 0.15664375687384, 0.043356243126163, 0.023310423540502, 0.14335624312616, 0.78321995464853, 0.21678004535147, 0.28321995464853, 0.21678004535147, 0.11655328798186, 0.21678004535147, 0.033219954648526, 0.21678004535147, 0.18321995464853, 0.016780045351474, 0.11655328798186, 0.050113378684807, 0.17569859876363, 0.82430140123637, 0.17569859876363, 0.32430140123637, 0.17569859876362, 0.15763473456971, 0.17569859876363, 0.074301401236374, 0.17569859876363, 0.024301401236373, 0.0090319320969575, 0.15763473456971, 0.53205214316846, 0.46794785683154, 0.032052143168455, 0.46794785683154, 0.19871880983512, 0.13461452349821, 0.032052143168455, 0.21794785683154, 0.13205214316846, 0.067947856831543, 0.032052143168454, 0.13461452349821, 0.8501324776502, 0.1498675223498, 0.3501324776502, 0.1498675223498, 0.18346581098354, 0.1498675223498, 0.1001324776502, 0.1498675223498, 0.050132477650203, 0.1498675223498, 0.01679914431687, 0.1498675223498, 0.12766375871578, 0.87233624128422, 0.12766375871578, 0.37233624128422, 0.12766375871578, 0.20566957461755, 0.12766375871578, 0.12233624128422, 0.12766375871578, 0.072336241284219, 0.12766375871578, 0.039002907950883, 0.36223481417572, 0.63776518582428, 0.36223481417572, 0.13776518582428, 0.028901480842386, 0.30443185249095, 0.11223481417572, 0.13776518582428, 0.16223481417572, 0.037765185824279, 0.028901480842386, 0.13776518582428, 0.55129109608114, 0.44870890391886, 0.05129109608114, 0.44870890391886, 0.21795776274781, 0.11537557058553, 0.05129109608114, 0.19870890391886, 0.15129109608114, 0.048708903918859, 0.051291096081139, 0.11537557058553, 0.69212615515742, 0.30787384484258, 0.19212615515742, 0.30787384484258, 0.025459488490756, 0.30787384484258, 0.19212615515742, 0.057873844842579, 0.092126155157422, 0.10787384484258, 0.025459488490756, 0.14120717817591, 0.78187260828136, 0.21812739171864, 0.28187260828136, 0.21812739171864, 0.11520594161469, 0.21812739171864, 0.031872608281361, 0.21812739171864, 0.18187260828136, 0.018127391718639, 0.11520594161469, 0.051460725051972, 0.81749256885653, 0.18250743114347, 0.31749256885653, 0.18250743114347, 0.15082590218986, 0.18250743114348, 0.067492568856526, 0.18250743114347, 0.017492568856525, 0.18250743114347, 0.15082590218986, 0.015840764476809, 0.79576750814915, 0.20423249185085, 0.29576750814915, 0.20423249185085, 0.12910084148248, 0.20423249185085, 0.045767508149147, 0.20423249185085, 0.19576750814915, 0.0042324918508541, 0.12910084148248, 0.037565825184186, 0.71328751374767, 0.28671248625233, 0.21328751374767, 0.28671248625233, 0.046620847081009, 0.28671248625232, 0.21328751374767, 0.036712486252327, 0.11328751374767, 0.086712486252327, 0.046620847081009, 0.12004581958566, 0.56643990929705, 0.43356009070295, 0.066439909297053, 0.43356009070295, 0.23310657596372, 0.10022675736961, 0.066439909297053, 0.18356009070295, 0.16643990929705, 0.033560090702949, 0.066439909297053, 0.10022675736961, 0.35139719752725, 0.64860280247275, 0.35139719752725, 0.14860280247275, 0.018063864193915, 0.31526946913942, 0.10139719752725, 0.14860280247275, 0.15139719752725, 0.048602802472746, 0.018063864193915, 0.14860280247275, 0.06410428633691, 0.93589571366309, 0.06410428633691, 0.43589571366309, 0.064104286336909, 0.26922904699642, 0.06410428633691, 0.18589571366309, 0.064104286336914, 0.13589571366309, 0.064104286336909, 0.10256238032976, 0.70026495530041, 0.29973504469959, 0.20026495530041, 0.29973504469959, 0.03359828863374, 0.29973504469959, 0.20026495530041, 0.049735044699592, 0.10026495530041, 0.099735044699594, 0.03359828863374, 0.13306837803293, 0.25532751743156, 0.74467248256844, 0.25532751743156, 0.24467248256844, 0.25532751743157, 0.078005815901766, 0.0053275174315637, 0.24467248256844, 0.055327517431562, 0.14467248256844, 0.088660850764901, 0.078005815901766, 0.72446962835144, 0.27553037164856, 0.22446962835144, 0.27553037164856, 0.057802961684772, 0.27553037164856, 0.22446962835144, 0.025530371648557, 0.12446962835144, 0.075530371648557, 0.057802961684772, 0.1088637049819, 0.10258219216228, 0.89741780783772, 0.10258219216228, 0.39741780783772, 0.10258219216228, 0.23075114117105, 0.10258219216228, 0.14741780783772, 0.10258219216228, 0.097417807837718, 0.10258219216228, 0.064084474504388, 0.38425231031485, 0.61574768968515, 0.38425231031485, 0.11574768968515, 0.050918976981516, 0.28241435635182, 0.13425231031485, 0.11574768968515, 0.18425231031485, 0.015747689685151, 0.050918976981516, 0.11574768968515, 0.56374521656272, 0.43625478343728, 0.063745216562722, 0.43625478343728, 0.23041188322939, 0.10292145010394, 0.063745216562722, 0.18625478343728, 0.16374521656272, 0.036254783437278, 0.063745216562722, 0.10292145010394, 0.63498513771305, 0.36501486228695, 0.13498513771305, 0.36501486228695, 0.30165180437972, 0.031681528953617, 0.13498513771305, 0.11501486228695, 0.034985137713051, 0.16501486228695, 0.13498513771305, 0.031681528953617, 0.5915350162983, 0.4084649837017, 0.091535016298302, 0.4084649837017, 0.25820168296497, 0.075131650368367, 0.091535016298302, 0.1584649837017, 0.1915350162983, 0.0084649837017025, 0.091535016298299, 0.075131650368367, 0.42657502749535, 0.57342497250465, 0.42657502749535, 0.073424972504654, 0.093241694162018, 0.24009163917132, 0.17657502749535, 0.073424972504654, 0.026575027495346, 0.17342497250465, 0.093241694162018, 0.073424972504649, 0.13287981859411, 0.86712018140589, 0.13287981859411, 0.36712018140589, 0.13287981859411, 0.20045351473923, 0.13287981859411, 0.11712018140589, 0.1328798185941, 0.067120181405897, 0.13287981859411, 0.033786848072561, 0.7027943950545, 0.2972056049455, 0.2027943950545, 0.2972056049455, 0.03612772838783, 0.2972056049455, 0.2027943950545, 0.047205604945496, 0.10279439505451, 0.097205604945492, 0.03612772838783, 0.13053893827884, 0.12820857267382, 0.87179142732618, 0.12820857267382, 0.37179142732618, 0.12820857267382, 0.20512476065952, 0.12820857267382, 0.12179142732618, 0.12820857267383, 0.071791427326173, 0.12820857267382, 0.038458093992849, 0.40052991060082, 0.59947008939918, 0.40052991060082, 0.099470089399183, 0.067196577267481, 0.26613675606585, 0.15052991060082, 0.099470089399183, 0.0005299106008124, 0.19947008939919, 0.067196577267481, 0.099470089399186, 0.51065503486313, 0.48934496513687, 0.010655034863127, 0.48934496513687, 0.1773217015298, 0.15601163180353, 0.010655034863127, 0.23934496513687, 0.11065503486312, 0.089344965136877, 0.010655034863134, 0.15601163180353, 0.44893925670289, 0.55106074329711, 0.44893925670289, 0.051060743297114, 0.11560592336954, 0.21772740996379, 0.19893925670289, 0.051060743297114, 0.048939256702886, 0.15106074329711, 0.11560592336954, 0.051060743297124, 0.20516438432456, 0.79483561567544, 0.20516438432456, 0.29483561567544, 0.20516438432456, 0.12816894900878, 0.20516438432456, 0.044835615675439, 0.0051643843245643, 0.19483561567544, 0.03849771765789, 0.12816894900878, 0.7685046206297, 0.2314953793703, 0.2685046206297, 0.2314953793703, 0.10183795396303, 0.2314953793703, 0.018504620629699, 0.2314953793703, 0.1685046206297, 0.031495379370301, 0.10183795396303, 0.064828712703635, 0.12749043312544, 0.87250956687456, 0.12749043312544, 0.37250956687456, 0.12749043312544, 0.20584290020789, 0.12749043312544, 0.12250956687456, 0.12749043312544, 0.072509566874555, 0.12749043312544, 0.039176233541222, 0.2699702754261, 0.7300297245739, 0.2699702754261, 0.2300297245739, 0.2699702754261, 0.063363057907234, 0.019970275426104, 0.2300297245739, 0.069970275426101, 0.1300297245739, 0.10330360875943, 0.063363057907234, 0.1830700325966, 0.8169299674034, 0.1830700325966, 0.3169299674034, 0.1830700325966, 0.15026330073673, 0.1830700325966, 0.066929967403397, 0.18307003259659, 0.016929967403405, 0.016403365929932, 0.15026330073673, 0.85315005499069, 0.14684994500931, 0.35315005499069, 0.14684994500931, 0.18648338832404, 0.1468499450093, 0.10315005499069, 0.14684994500931, 0.053150054990692, 0.14684994500931, 0.019816721657368, 0.1468499450093, 0.26575963718821, 0.73424036281179, 0.26575963718821, 0.23424036281179, 0.26575963718821, 0.067573696145123, 0.015759637188211, 0.23424036281179, 0.065759637188205, 0.13424036281179, 0.099092970521544, 0.067573696145123, 0.40558879010901, 0.59441120989099, 0.40558879010901, 0.094411209890993, 0.07225545677566, 0.26107787655767, 0.15558879010901, 0.094411209890993, 0.0055887901090159, 0.19441120989098, 0.07225545677566, 0.094411209891007, 0.25641714534767, 0.74358285465233, 0.25641714534767, 0.24358285465233, 0.25641714534767, 0.07691618798566, 0.0064171453476689, 0.24358285465233, 0.056417145347666, 0.14358285465233, 0.089750478681007, 0.07691618798566, 0.80105982120163, 0.19894017879837, 0.30105982120163, 0.19894017879837, 0.13439315453496, 0.19894017879837, 0.051059821201633, 0.19894017879837, 0.0010598212016248, 0.19894017879838, 0.13439315453496, 0.032273512131705, 0.021310069726255, 0.97868993027375, 0.021310069726255, 0.47868993027375, 0.021310069726269, 0.31202326360706, 0.021310069726255, 0.22868993027375, 0.021310069726246, 0.17868993027375, 0.021310069726269, 0.1453565969404, 0.89787851340579, 0.10212148659421, 0.39787851340579, 0.10212148659421, 0.23121184673912, 0.10212148659421, 0.14787851340579, 0.10212148659421, 0.097878513405794, 0.10212148659421, 0.064545180072457, 0.10212148659421, 0.41032876864912, 0.58967123135088, 0.41032876864912, 0.089671231350877, 0.07699543531578, 0.25633789801755, 0.16032876864912, 0.089671231350877, 0.010328768649129, 0.18967123135087, 0.07699543531578, 0.089671231350887, 0.5370092412594, 0.4629907587406, 0.037009241259398, 0.4629907587406, 0.20367590792606, 0.12965742540727, 0.037009241259398, 0.2129907587406, 0.1370092412594, 0.062990758740602, 0.037009241259398, 0.12965742540727, 0.25498086625089, 0.74501913374911, 0.25498086625089, 0.24501913374911, 0.25498086625089, 0.078352467082444, 0.0049808662508894, 0.24501913374911, 0.054980866250889, 0.14501913374911, 0.088314199584223, 0.078352467082444, 0.53994055085221, 0.46005944914779, 0.039940550852208, 0.46005944914779, 0.20660721751887, 0.12672611581447, 0.039940550852208, 0.21005944914779, 0.1399405508522, 0.060059449147798, 0.039940550852198, 0.12672611581447, 0.36614006519321, 0.63385993480679, 0.36614006519321, 0.13385993480679, 0.032806731859864, 0.30052660147347, 0.11614006519321, 0.13385993480679, 0.16614006519319, 0.03385993480681, 0.032806731859864, 0.1338599348068, 0.70630010998138, 0.29369989001862, 0.20630010998138, 0.29369989001862, 0.039633443314737, 0.2936998900186, 0.20630010998138, 0.043699890018615, 0.10630010998138, 0.093699890018615, 0.039633443314737, 0.12703322335193 }; static int g_bins44100[720] = { 5, 6, 10, 11, 15, 16, 20, 21, 25, 26, 30, 31, 5, 6, 10, 11, 16, 17, 21, 22, 27, 28, 32, 33, 5, 6, 11, 12, 17, 18, 22, 23, 28, 29, 34, 35, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 36, 37, 6, 7, 12, 13, 19, 20, 25, 26, 32, 33, 38, 39, 6, 7, 13, 14, 20, 21, 27, 28, 34, 35, 40, 41, 7, 8, 14, 15, 21, 22, 28, 29, 36, 37, 43, 44, 7, 8, 15, 16, 22, 23, 30, 31, 38, 39, 45, 46, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 49, 8, 9, 17, 18, 25, 26, 34, 35, 42, 43, 51, 52, 9, 10, 18, 19, 27, 28, 36, 37, 45, 46, 54, 55, 9, 10, 19, 20, 28, 29, 38, 39, 48, 49, 57, 58, 10, 11, 20, 21, 30, 31, 40, 41, 51, 52, 61, 62, 10, 11, 21, 22, 32, 33, 43, 44, 54, 55, 64, 65, 11, 12, 22, 23, 34, 35, 45, 46, 57, 58, 68, 69, 12, 13, 24, 25, 36, 37, 48, 49, 60, 61, 72, 73, 12, 13, 25, 26, 38, 39, 51, 52, 64, 65, 77, 78, 13, 14, 27, 28, 40, 41, 54, 55, 68, 69, 81, 82, 14, 15, 28, 29, 43, 44, 57, 58, 72, 73, 86, 87, 15, 16, 30, 31, 45, 46, 61, 62, 76, 77, 91, 92, 16, 17, 32, 33, 48, 49, 64, 65, 81, 82, 97, 98, 17, 18, 34, 35, 51, 52, 68, 69, 85, 86, 103, 104, 18, 19, 36, 37, 54, 55, 72, 73, 91, 92, 109, 110, 19, 20, 38, 39, 57, 58, 77, 78, 96, 97, 115, 116, 20, 21, 40, 41, 61, 62, 81, 82, 102, 103, 122, 123, 21, 22, 43, 44, 64, 65, 86, 87, 108, 109, 129, 130, 22, 23, 45, 46, 68, 69, 91, 92, 114, 115, 137, 138, 24, 25, 48, 49, 72, 73, 97, 98, 121, 122, 145, 146, 25, 26, 51, 52, 77, 78, 102, 103, 128, 129, 154, 155, 27, 28, 54, 55, 81, 82, 109, 110, 136, 137, 163, 164, 28, 29, 57, 58, 86, 87, 115, 116, 144, 145, 173, 174, 30, 31, 61, 62, 91, 92, 122, 123, 153, 154, 183, 184, 32, 33, 64, 65, 97, 98, 129, 130, 162, 163, 194, 195, 34, 35, 68, 69, 103, 104, 137, 138, 171, 172, 206, 207, 36, 37, 72, 73, 109, 110, 145, 146, 182, 183, 218, 219, 38, 39, 77, 78, 115, 116, 154, 155, 192, 193, 231, 232, 40, 41, 81, 82, 122, 123, 163, 164, 204, 205, 245, 246, 43, 44, 86, 87, 129, 130, 173, 174, 216, 217, 259, 260, 45, 46, 91, 92, 137, 138, 183, 184, 229, 230, 275, 276, 48, 49, 97, 98, 145, 146, 194, 195, 242, 243, 291, 292, 51, 52, 102, 103, 154, 155, 205, 206, 257, 258, 308, 309, 54, 55, 109, 110, 163, 164, 218, 219, 272, 273, 327, 328, 57, 58, 115, 116, 173, 174, 231, 232, 288, 289, 346, 347, 61, 62, 122, 123, 183, 184, 244, 245, 306, 307, 367, 368, 64, 65, 129, 130, 194, 195, 259, 260, 324, 325, 389, 390, 68, 69, 137, 138, 206, 207, 274, 275, 343, 344, 412, 413, 72, 73, 145, 146, 218, 219, 291, 292, 364, 365, 436, 437, 77, 78, 154, 155, 231, 232, 308, 309, 385, 386, 462, 463, 81, 82, 163, 164, 245, 246, 326, 327, 408, 409, 490, 491, 86, 87, 173, 174, 259, 260, 346, 347, 432, 433, 519, 520, 91, 92, 183, 184, 275, 276, 366, 367, 458, 459, 550, 551, 97, 98, 194, 195, 291, 292, 388, 389, 485, 486, 583, 584, 102, 103, 205, 206, 308, 309, 411, 412, 514, 515, 617, 618, 109, 110, 218, 219, 327, 328, 436, 437, 545, 546, 654, 655, 115, 116, 231, 232, 346, 347, 462, 463, 577, 578, 693, 694, 122, 123, 244, 245, 367, 368, 489, 490, 612, 613, 734, 735, 129, 130, 259, 260, 389, 390, 518, 519, 648, 649, 778, 779, 137, 138, 274, 275, 412, 413, 549, 550, 687, 688, 824, 825, 145, 146, 291, 292, 436, 437, 582, 583, 728, 729, 873, 874, 154, 155, 308, 309, 462, 463, 617, 618, 771, 772, 925, 926 }; // 4096 FFT at 48000 SR static float g_weights48000[720] = { 0.30666666666667, 0.69333333333333, 0.30666666666667, 0.19333333333333, 0.30666666666667, 0.026666666666667, 0.056666666666667, 0.19333333333333, 0.10666666666667, 0.093333333333333, 0.14, 0.026666666666667, 0.027586543807041, 0.97241345619296, 0.027586543807041, 0.47241345619296, 0.02758654380704, 0.30574678952629, 0.027586543807041, 0.22241345619296, 0.027586543807041, 0.17241345619296, 0.02758654380704, 0.13908012285963, 0.73191145326801, 0.26808854673199, 0.23191145326801, 0.26808854673199, 0.065244786601342, 0.26808854673199, 0.23191145326801, 0.018088546731992, 0.13191145326801, 0.068088546731992, 0.065244786601342, 0.10142188006533, 0.41865460692056, 0.58134539307944, 0.41865460692056, 0.081345393079437, 0.08532127358723, 0.2480120597461, 0.16865460692056, 0.081345393079437, 0.018654606920562, 0.18134539307944, 0.08532127358723, 0.081345393079437, 0.086770539160062, 0.91322946083994, 0.086770539160062, 0.41322946083994, 0.086770539160063, 0.24656279417327, 0.086770539160062, 0.16322946083994, 0.086770539160062, 0.11322946083994, 0.086770539160063, 0.079896127506604, 0.73515161776197, 0.26484838223803, 0.23515161776197, 0.26484838223803, 0.068484951095304, 0.26484838223803, 0.23515161776197, 0.014848382238029, 0.13515161776197, 0.064848382238029, 0.068484951095304, 0.098181715571363, 0.36262434726227, 0.63737565273773, 0.36262434726227, 0.13737565273773, 0.02929101392894, 0.30404231940439, 0.11262434726227, 0.13737565273773, 0.16262434726227, 0.037375652737727, 0.02929101392894, 0.13737565273773, 0.96794545252544, 0.032054547474559, 0.46794545252544, 0.032054547474559, 0.30127878585877, 0.03205454747456, 0.21794545252544, 0.032054547474559, 0.16794545252544, 0.03205454747456, 0.13461211919211, 0.03205454747456, 0.54979772942925, 0.45020227057075, 0.049797729429249, 0.45020227057075, 0.21646439609592, 0.11686893723742, 0.049797729429249, 0.20020227057075, 0.14979772942925, 0.05020227057075, 0.049797729429249, 0.11686893723742, 0.10678564881847, 0.89321435118153, 0.10678564881847, 0.39321435118153, 0.10678564881847, 0.22654768451487, 0.10678564881847, 0.14321435118153, 0.10678564881847, 0.093214351181534, 0.10678564881847, 0.059881017848201, 0.63743069905602, 0.36256930094398, 0.13743069905602, 0.36256930094398, 0.30409736572268, 0.029235967610653, 0.13743069905602, 0.11256930094398, 0.037430699056014, 0.16256930094399, 0.13743069905601, 0.029235967610653, 0.14016645162784, 0.85983354837216, 0.14016645162784, 0.35983354837216, 0.14016645162784, 0.1931668817055, 0.14016645162784, 0.10983354837216, 0.14016645162784, 0.059833548372163, 0.14016645162784, 0.02650021503883, 0.61333333333333, 0.38666666666667, 0.11333333333333, 0.38666666666667, 0.28, 0.053333333333333, 0.11333333333333, 0.13666666666667, 0.013333333333334, 0.18666666666667, 0.11333333333333, 0.053333333333333, 0.055173087614081, 0.94482691238592, 0.055173087614081, 0.44482691238592, 0.055173087614081, 0.27816024571925, 0.055173087614081, 0.19482691238592, 0.055173087614082, 0.14482691238592, 0.055173087614081, 0.11149357905259, 0.46382290653602, 0.53617709346398, 0.46382290653602, 0.036177093463982, 0.13048957320268, 0.20284376013065, 0.21382290653602, 0.036177093463982, 0.063822906536019, 0.13617709346398, 0.13048957320268, 0.036177093463982, 0.83730921384113, 0.16269078615887, 0.33730921384113, 0.16269078615887, 0.17064254717446, 0.16269078615887, 0.087309213841126, 0.16269078615887, 0.037309213841124, 0.16269078615888, 0.0039758805077928, 0.16269078615887, 0.17354107832012, 0.82645892167988, 0.17354107832012, 0.32645892167988, 0.17354107832013, 0.15979225501321, 0.17354107832012, 0.076458921679876, 0.17354107832012, 0.026458921679875, 0.0068744116534584, 0.15979225501321, 0.47030323552394, 0.52969676447606, 0.47030323552394, 0.029696764476057, 0.13696990219061, 0.19636343114272, 0.22030323552394, 0.029696764476057, 0.070303235523944, 0.12969676447606, 0.13696990219061, 0.029696764476057, 0.72524869452455, 0.27475130547545, 0.22524869452455, 0.27475130547545, 0.058582027857881, 0.27475130547545, 0.22524869452455, 0.024751305475453, 0.12524869452455, 0.074751305475453, 0.058582027857881, 0.10808463880879, 0.93589090505088, 0.064109094949119, 0.43589090505088, 0.064109094949119, 0.26922423838421, 0.06410909494912, 0.18589090505088, 0.064109094949119, 0.13589090505088, 0.06410909494912, 0.10255757171755, 0.06410909494912, 0.0995954588585, 0.9004045411415, 0.0995954588585, 0.4004045411415, 0.0995954588585, 0.23373787447483, 0.0995954588585, 0.1504045411415, 0.099595458858502, 0.1004045411415, 0.0995954588585, 0.067071207808167, 0.21357129763693, 0.78642870236307, 0.21357129763693, 0.28642870236307, 0.21357129763693, 0.1197620356964, 0.21357129763693, 0.036428702363068, 0.013571297636932, 0.18642870236307, 0.046904630970265, 0.1197620356964, 0.27486139811203, 0.72513860188797, 0.27486139811203, 0.22513860188797, 0.27486139811203, 0.058471935221306, 0.02486139811203, 0.22513860188797, 0.074861398112029, 0.12513860188797, 0.10819473144536, 0.058471935221306, 0.28033290325568, 0.71966709674432, 0.28033290325568, 0.21966709674432, 0.28033290325568, 0.053000430077657, 0.030332903255676, 0.21966709674432, 0.080332903255675, 0.11966709674433, 0.11366623658901, 0.053000430077657, 0.22666666666667, 0.77333333333333, 0.22666666666667, 0.27333333333333, 0.22666666666667, 0.10666666666667, 0.22666666666667, 0.023333333333333, 0.026666666666668, 0.17333333333333, 0.06, 0.10666666666667, 0.11034617522816, 0.88965382477184, 0.11034617522816, 0.38965382477184, 0.11034617522816, 0.22298715810517, 0.11034617522816, 0.13965382477184, 0.11034617522816, 0.089653824771835, 0.11034617522816, 0.056320491438505, 0.92764581307204, 0.072354186927964, 0.42764581307204, 0.072354186927964, 0.26097914640537, 0.072354186927965, 0.17764581307204, 0.072354186927964, 0.12764581307204, 0.072354186927961, 0.094312479738702, 0.072354186927965, 0.67461842768225, 0.32538157231775, 0.17461842768225, 0.32538157231775, 0.0079517610155856, 0.32538157231775, 0.17461842768225, 0.075381572317749, 0.074618427682248, 0.12538157231775, 0.0079517610155856, 0.15871490565108, 0.34708215664025, 0.65291784335975, 0.34708215664025, 0.15291784335975, 0.013748823306917, 0.31958451002642, 0.097082156640248, 0.15291784335975, 0.14708215664025, 0.052917843359751, 0.013748823306917, 0.15291784335975, 0.94060647104789, 0.059393528952114, 0.44060647104789, 0.059393528952114, 0.27393980438122, 0.059393528952114, 0.19060647104789, 0.059393528952114, 0.14060647104789, 0.059393528952111, 0.10727313771455, 0.059393528952114, 0.45049738904909, 0.54950261095091, 0.45049738904909, 0.049502610950906, 0.11716405571576, 0.21616927761757, 0.20049738904909, 0.049502610950906, 0.050497389049093, 0.14950261095091, 0.11716405571576, 0.049502610950905, 0.87178181010177, 0.12821818989823, 0.37178181010177, 0.12821818989823, 0.2051151434351, 0.12821818989823, 0.12178181010177, 0.12821818989823, 0.071781810101766, 0.12821818989823, 0.038448476768437, 0.12821818989823, 0.199190917717, 0.800809082283, 0.199190917717, 0.300809082283, 0.199190917717, 0.13414241561633, 0.199190917717, 0.050809082282999, 0.199190917717, 0.00080908228299563, 0.032524251050333, 0.13414241561633, 0.42714259527386, 0.57285740472614, 0.42714259527386, 0.072857404726136, 0.093809261940531, 0.2395240713928, 0.17714259527386, 0.072857404726136, 0.027142595273864, 0.17285740472614, 0.093809261940531, 0.072857404726136, 0.54972279622406, 0.45027720377594, 0.04972279622406, 0.45027720377594, 0.21638946289073, 0.1169438704426, 0.04972279622406, 0.20027720377594, 0.14972279622406, 0.050277203775937, 0.049722796224065, 0.1169438704426, 0.56066580651135, 0.43933419348865, 0.060665806511352, 0.43933419348865, 0.22733247317802, 0.10600086015531, 0.060665806511352, 0.18933419348865, 0.16066580651135, 0.039334193488651, 0.060665806511352, 0.10600086015531, 0.45333333333333, 0.54666666666667, 0.45333333333333, 0.046666666666667, 0.12, 0.21333333333333, 0.20333333333333, 0.046666666666667, 0.053333333333336, 0.14666666666666, 0.12, 0.046666666666667, 0.22069235045632, 0.77930764954368, 0.22069235045632, 0.27930764954368, 0.22069235045632, 0.11264098287701, 0.22069235045632, 0.029307649543675, 0.020692350456329, 0.17930764954367, 0.054025683789656, 0.11264098287701, 0.85529162614407, 0.14470837385593, 0.35529162614407, 0.14470837385593, 0.1886249594774, 0.14470837385593, 0.10529162614407, 0.14470837385593, 0.055291626144077, 0.14470837385592, 0.021958292810737, 0.14470837385593, 0.3492368553645, 0.6507631446355, 0.3492368553645, 0.1507631446355, 0.015903522031171, 0.31742981130216, 0.099236855364502, 0.1507631446355, 0.1492368553645, 0.050763144635505, 0.015903522031171, 0.1507631446355, 0.6941643132805, 0.3058356867195, 0.1941643132805, 0.3058356867195, 0.027497646613834, 0.3058356867195, 0.1941643132805, 0.055835686719504, 0.094164313280498, 0.1058356867195, 0.027497646613834, 0.13916902005283, 0.88121294209577, 0.11878705790423, 0.38121294209577, 0.11878705790423, 0.21454627542911, 0.11878705790423, 0.13121294209577, 0.11878705790423, 0.081212942095777, 0.11878705790422, 0.047879608762438, 0.11878705790423, 0.90099477809819, 0.099005221901812, 0.40099477809819, 0.099005221901812, 0.23432811143152, 0.09900522190181, 0.15099477809819, 0.099005221901812, 0.10099477809819, 0.099005221901814, 0.067661444764857, 0.09900522190181, 0.74356362020353, 0.25643637979647, 0.24356362020353, 0.25643637979647, 0.076896953536874, 0.25643637979646, 0.24356362020353, 0.0064363797964688, 0.14356362020353, 0.056436379796469, 0.076896953536874, 0.089769713129793, 0.398381835434, 0.601618164566, 0.398381835434, 0.101618164566, 0.065048502100666, 0.26828483123267, 0.148381835434, 0.101618164566, 0.19838183543401, 0.0016181645659913, 0.065048502100666, 0.101618164566, 0.85428519054773, 0.14571480945227, 0.35428519054773, 0.14571480945227, 0.18761852388106, 0.14571480945227, 0.10428519054773, 0.14571480945227, 0.054285190547728, 0.14571480945227, 0.020951857214394, 0.14571480945227, 0.09944559244812, 0.90055440755188, 0.09944559244812, 0.40055440755188, 0.09944559244813, 0.2338877408852, 0.09944559244812, 0.15055440755188, 0.099445592448126, 0.10055440755187, 0.09944559244813, 0.067221074218537, 0.1213316130227, 0.8786683869773, 0.1213316130227, 0.3786683869773, 0.1213316130227, 0.21200172031063, 0.1213316130227, 0.1286683869773, 0.1213316130227, 0.078668386977301, 0.1213316130227, 0.045335053643962, 0.90666666666667, 0.093333333333334, 0.40666666666667, 0.093333333333334, 0.24, 0.093333333333334, 0.15666666666667, 0.093333333333334, 0.10666666666667, 0.093333333333328, 0.073333333333333, 0.093333333333334, 0.44138470091265, 0.55861529908735, 0.44138470091265, 0.05861529908735, 0.10805136757931, 0.22528196575402, 0.19138470091265, 0.05861529908735, 0.041384700912658, 0.15861529908734, 0.10805136757931, 0.058615299087355, 0.71058325228817, 0.28941674771183, 0.21058325228817, 0.28941674771183, 0.043916585621503, 0.28941674771183, 0.21058325228817, 0.039416747711826, 0.11058325228817, 0.089416747711834, 0.043916585621503, 0.12275008104516, 0.698473710729, 0.301526289271, 0.198473710729, 0.301526289271, 0.031807044062343, 0.30152628927099, 0.198473710729, 0.051526289270996, 0.09847371072899, 0.10152628927101, 0.031807044062343, 0.13485962260432, 0.38832862656099, 0.61167137343901, 0.38832862656099, 0.11167137343901, 0.054995293227667, 0.27833804010567, 0.13832862656099, 0.11167137343901, 0.188328626561, 0.011671373439003, 0.054995293227667, 0.111671373439, 0.76242588419157, 0.23757411580843, 0.26242588419157, 0.23757411580843, 0.095759217524896, 0.23757411580844, 0.012425884191572, 0.23757411580843, 0.16242588419157, 0.037574115808434, 0.095759217524896, 0.070907449141771, 0.80198955619638, 0.19801044380362, 0.30198955619638, 0.19801044380362, 0.13532288952971, 0.19801044380362, 0.051989556196375, 0.19801044380362, 0.0019895561963722, 0.19801044380363, 0.13532288952971, 0.031343777136954, 0.48712724040706, 0.51287275959294, 0.48712724040706, 0.012872759592938, 0.15379390707375, 0.17953942625959, 0.23712724040706, 0.012872759592938, 0.087127240407062, 0.11287275959294, 0.15379390707375, 0.012872759592919, 0.796763670868, 0.203236329132, 0.296763670868, 0.203236329132, 0.13009700420133, 0.203236329132, 0.046763670868003, 0.203236329132, 0.19676367086802, 0.0032363291319825, 0.13009700420133, 0.036569662465335, 0.70857038109546, 0.29142961890454, 0.20857038109546, 0.29142961890454, 0.041903714428789, 0.29142961890454, 0.20857038109546, 0.041429618904544, 0.10857038109546, 0.091429618904544, 0.041903714428789, 0.12476295223788, 0.19889118489624, 0.80110881510376, 0.19889118489624, 0.30110881510376, 0.19889118489626, 0.13444214843707, 0.19889118489624, 0.05110881510376, 0.19889118489625, 0.0011088151037484, 0.032224518229593, 0.13444214843707, 0.24266322604541, 0.75733677395459, 0.24266322604541, 0.25733677395459, 0.24266322604541, 0.090670107287925, 0.24266322604541, 0.0073367739545915, 0.042663226045397, 0.1573367739546, 0.075996559378742, 0.090670107287925 }; static int g_bins48000[720] = { 4, 5, 9, 10, 14, 15, 18, 19, 23, 24, 28, 29, 4, 5, 9, 10, 14, 15, 19, 20, 24, 25, 29, 30, 5, 6, 10, 11, 15, 16, 21, 22, 26, 27, 31, 32, 5, 6, 11, 12, 16, 17, 22, 23, 27, 28, 33, 34, 5, 6, 11, 12, 17, 18, 23, 24, 29, 30, 35, 36, 6, 7, 12, 13, 18, 19, 25, 26, 31, 32, 37, 38, 6, 7, 13, 14, 19, 20, 26, 27, 33, 34, 39, 40, 7, 8, 14, 15, 21, 22, 28, 29, 35, 36, 42, 43, 7, 8, 14, 15, 22, 23, 29, 30, 37, 38, 44, 45, 7, 8, 15, 16, 23, 24, 31, 32, 39, 40, 47, 48, 8, 9, 16, 17, 25, 26, 33, 34, 41, 42, 50, 51, 8, 9, 17, 18, 26, 27, 35, 36, 44, 45, 53, 54, 9, 10, 18, 19, 28, 29, 37, 38, 46, 47, 56, 57, 9, 10, 19, 20, 29, 30, 39, 40, 49, 50, 59, 60, 10, 11, 21, 22, 31, 32, 42, 43, 52, 53, 63, 64, 11, 12, 22, 23, 33, 34, 44, 45, 55, 56, 66, 67, 11, 12, 23, 24, 35, 36, 47, 48, 59, 60, 70, 71, 12, 13, 25, 26, 37, 38, 50, 51, 62, 63, 75, 76, 13, 14, 26, 27, 39, 40, 53, 54, 66, 67, 79, 80, 14, 15, 28, 29, 42, 43, 56, 57, 70, 71, 84, 85, 14, 15, 29, 30, 44, 45, 59, 60, 74, 75, 89, 90, 15, 16, 31, 32, 47, 48, 63, 64, 78, 79, 94, 95, 16, 17, 33, 34, 50, 51, 66, 67, 83, 84, 100, 101, 17, 18, 35, 36, 53, 54, 70, 71, 88, 89, 106, 107, 18, 19, 37, 38, 56, 57, 75, 76, 93, 94, 112, 113, 19, 20, 39, 40, 59, 60, 79, 80, 99, 100, 119, 120, 21, 22, 42, 43, 63, 64, 84, 85, 105, 106, 126, 127, 22, 23, 44, 45, 66, 67, 89, 90, 111, 112, 133, 134, 23, 24, 47, 48, 70, 71, 94, 95, 118, 119, 141, 142, 25, 26, 50, 51, 75, 76, 100, 101, 125, 126, 150, 151, 26, 27, 53, 54, 79, 80, 106, 107, 132, 133, 159, 160, 28, 29, 56, 57, 84, 85, 112, 113, 140, 141, 168, 169, 29, 30, 59, 60, 89, 90, 119, 120, 149, 150, 178, 179, 31, 32, 63, 64, 94, 95, 126, 127, 157, 158, 189, 190, 33, 34, 66, 67, 100, 101, 133, 134, 167, 168, 200, 201, 35, 36, 70, 71, 106, 107, 141, 142, 177, 178, 212, 213, 37, 38, 75, 76, 112, 113, 150, 151, 187, 188, 225, 226, 39, 40, 79, 80, 119, 120, 159, 160, 198, 199, 238, 239, 42, 43, 84, 85, 126, 127, 168, 169, 210, 211, 252, 253, 44, 45, 89, 90, 133, 134, 178, 179, 223, 224, 267, 268, 47, 48, 94, 95, 141, 142, 189, 190, 236, 237, 283, 284, 50, 51, 100, 101, 150, 151, 200, 201, 250, 251, 300, 301, 53, 54, 106, 107, 159, 160, 212, 213, 265, 266, 318, 319, 56, 57, 112, 113, 168, 169, 225, 226, 281, 282, 337, 338, 59, 60, 119, 120, 178, 179, 238, 239, 298, 299, 357, 358, 63, 64, 126, 127, 189, 190, 252, 253, 315, 316, 378, 379, 66, 67, 133, 134, 200, 201, 267, 268, 334, 335, 401, 402, 70, 71, 141, 142, 212, 213, 283, 284, 354, 355, 425, 426, 75, 76, 150, 151, 225, 226, 300, 301, 375, 376, 450, 451, 79, 80, 159, 160, 238, 239, 318, 319, 397, 398, 477, 478, 84, 85, 168, 169, 252, 253, 337, 338, 421, 422, 505, 506, 89, 90, 178, 179, 267, 268, 357, 358, 446, 447, 535, 536, 94, 95, 189, 190, 283, 284, 378, 379, 473, 474, 567, 568, 100, 101, 200, 201, 300, 301, 400, 401, 501, 502, 601, 602, 106, 107, 212, 213, 318, 319, 424, 425, 530, 531, 637, 638, 112, 113, 225, 226, 337, 338, 450, 451, 562, 563, 675, 676, 119, 120, 238, 239, 357, 358, 476, 477, 596, 597, 715, 716, 126, 127, 252, 253, 378, 379, 505, 506, 631, 632, 757, 758, 133, 134, 267, 268, 401, 402, 535, 536, 669, 670, 802, 803, 141, 142, 283, 284, 425, 426, 567, 568, 708, 709, 850, 851 }; // Krumhansl Kessler profiles (normalised) // double g_kkminor[12] = { 0.14221523253202, 0.060211188496967, 0.079083352055718, 0.12087171422152, 0.05841383958661, // 0.079308020669512, 0.057065827903842, 0.10671759155246, 0.089418108290272, 0.060435857110762, 0.075039317007414, // 0.071219950572905 }; double g_kkmajor[12] = { 0.15195022732711, 0.053362048336923, 0.083273510409189, // 0.055754965302704, 0.10480976310122, 0.097870303900455, 0.060301507537688, 0.12419239052405, 0.057190715482173, // 0.087580760947595, 0.054797798516391, 0.068916008614501 }; // following Izmirli; see MIREX2006 static double g_diatonicmajor[12] = { 5.0, 0.0, 3.5, 0.0, 4.5, 4.0, 0.0, 4.5, 0.0, 3.5, 0.0, 4.0 }; static double g_diatonicminor[12] = { 5.0, 0.0, 3.5, 4.5, 0.0, 4.0, 0.0, 4.5, 3.5, 0.0, 0.0, 4.0 }; static int g_minor[7] = { 0, 2, 3, 5, 7, 8, 11 }; static int g_major[7] = { 0, 2, 4, 5, 7, 9, 11 }; // other functions static void KeyTrack_calculatekey(KeyTrack*, uint32); void KeyTrack_Ctor(KeyTrack* unit) { unit->m_srate = unit->mWorld->mFullRate.mSampleRate; // if sample rate is 88200 or 96000, assume taking double size FFT to start with if (unit->m_srate > (44100.0 * 1.5)) unit->m_srate = unit->m_srate * 0.5; if (((int)(unit->m_srate + 0.01)) == 44100) { unit->m_weights = g_weights44100; unit->m_bins = g_bins44100; unit->m_frameperiod = 0.046439909297052; } else // else 48000; potentially dangerous if it isn't! Fortunately, shouldn't write any data to unknown memory { unit->m_weights = g_weights48000; unit->m_bins = g_bins48000; unit->m_frameperiod = 0.042666666666667; } // only need space for half! unit->m_FFTBuf = (float*)RTAlloc(unit->mWorld, NOVER2 * sizeof(float)); ClearUnitIfMemFailed(unit->m_FFTBuf); // zero chroma Clear(12, unit->m_chroma); Clear(24, unit->m_key); Clear(24, unit->m_histogram); // for(j=0;j<60;++j) { // unit->m_leaknote[j]=0.0; // } // for(j=0;j<360;++j) { // unit->m_prevphase[j]=0.0; // } // triggers // unit->m_triggerid=(int)ZIN0(1); unit->m_currentKey = 0; // unit->m_frame=0; OUT0(0) = 0.f; unit->mCalcFunc = (UnitCalcFunc)&KeyTrack_next; } void KeyTrack_Dtor(KeyTrack* unit) { RTFree(unit->mWorld, unit->m_FFTBuf); } void KeyTrack_next(KeyTrack* unit, int wrongNumSamples) { // int numSamples = unit->mWorld->mFullRate.mBufLength; // float *output = ZOUT(0); float fbufnum = ZIN0(0) + 0.001; // next FFT bufffer ready, update // assuming at this point that buffer precalculated for any resampling if (fbufnum > -0.01f) { // && ( ZIN0(3)<0.5) // unit->m_frame= unit->m_frame+1; KeyTrack_calculatekey(unit, (uint32)fbufnum); } // always output current best key float outval = unit->m_currentKey; // control rate output ZOUT0(0) = outval; } // calculation function once FFT data ready void KeyTrack_calculatekey(KeyTrack* unit, uint32 ibufnum) { World* world = unit->mWorld; SndBuf* buf; if (ibufnum >= world->mNumSndBufs) { int localBufNum = ibufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { buf = world->mSndBufs; if (unit->mWorld->mVerbosity > -1) { Print("KeyTrack error: Buffer number overrun: %i\n", ibufnum); } } } else { buf = world->mSndBufs + ibufnum; } LOCK_SNDBUF(buf); // assumed in this representation ToComplexApx(buf); const float* data = buf->data; // memcpy(unit->m_FFTBuf, data, NOVER2); // to hold powers float* fftbuf = unit->m_FFTBuf; // get powers for bins // don't need to calculate past half Nyquist, because no indices involved of harmonics above 10000 Hz or so (see // index data at top of file) for (int i = 0; i < NOVER2; i += 2) { // i>>1 is i/2 fftbuf[i >> 1] = ((data[i] * data[i]) + (data[i + 1] * data[i + 1])); } float* chroma = unit->m_chroma; float sum; int indexbase, index; // experimental; added leaky integration on each note; also, only add to sum if harmonic, ie not a transient float* weights = unit->m_weights; int* bins = unit->m_bins; float chromaleak = ZIN0(2); // zero for new round (should add leaky integrator here! for (int i = 0; i < 12; ++i) chroma[i] *= chromaleak; for (int i = 0; i < 60; ++i) { int chromaindex = (i + 9) % 12; // starts at A1 up to G#6 sum = 0.0; indexbase = 12 * i; // 6 partials, 2 of each // transient sum, setting up last values too for (int j = 0; j < 12; ++j) { // 12 if 144 data points index = indexbase + j; // experimental transient detection code, not reliable // int binindex= unit->m_bins[index]-1; // SCPolar binnow= p->bin[binindex].ToPolarApx(); // float phaseadvance= (binindex+1)*(TWOPI*0.5); //k * (512/44100) * (44100/1024) //convert bin number to // frequency float power= binnow.mag * binnow.mag; //(p->bin[binindex].real)*(p->bin[binindex].real) + // (p->bin[binindex].imag)*(p->bin[binindex].imag); //(p->bin[binindex].mag); power *= power; // int phaseindex= indexbase+j; // float phasenow= binnow.phase; //0.0; //(p->bin[binindex].phase); // float prevphase = fmod(unit->m_prevphase[index]+phaseadvance,TWOPI); // float a,b,tmp; // a=phasenow; b=prevphase; // b=phasenow; a=prevphase; // if(b<a) {b= b+TWOPI;} // float phasechange = sc_min(b-a,a+TWOPI-b); //more complicated, need mod 2pi and to know lower and upper // phasesum+= phasechange; // unit->m_prevphase[index]= phasenow; //((p->bin[index-1].mag) * (p->bin[index-1].mag)) // printf("comparison %f %f \n",fftbuf[g_bins2[index]], power); // sum+= (unit->m_weights[index])* power; sum += (weights[index]) * (fftbuf[bins[index]]); } // transient test here too? // if(phasesum>(5*PI)){sum=0.0;} // if((i>5) && (i<15)) // printf("test phasesum %f \n", phasesum); // unit->m_leaknote[i] = (0.8*unit->m_leaknote[i]) + sum; chroma[chromaindex] += sum; // unit->m_leaknote[i]; //sum; } float* key = unit->m_key; // major for (int i = 0; i < 12; ++i) { sum = 0.0; for (int j = 0; j < 7; ++j) { indexbase = g_major[j]; index = (i + indexbase) % 12; // sum+=(chroma[index]*g_kkmajor[indexbase]); sum += (chroma[index] * g_diatonicmajor[indexbase]); } key[i] = sum; // 10*log10(sum+1); } // minor for (int i = 0; i < 12; ++i) { sum = 0.0; for (int j = 0; j < 7; ++j) { indexbase = g_minor[j]; index = (i + indexbase) % 12; // sum+=(chroma[index]*g_kkminor[indexbase]); sum += (chroma[index] * g_diatonicminor[indexbase]); } key[12 + i] = sum; } float keyleak = ZIN0(1); // fade parameter to 0.01 for histogram in seconds, convert to FFT frames // keyleak in seconds, convert to drop time in FFT hop frames (FRAMEPERIOD) keyleak = sc_max(0.001f, keyleak / unit->m_frameperiod); // FRAMEPERIOD; // now number of frames, actual leak param is decay exponent to reach 0.01 in x seconds, ie 0.01 = leakparam ** // (x/ffthopsize) 0.01 is -40dB keyleak = pow(0.01f, (1.f / keyleak)); float* histogram = unit->m_histogram; int bestkey = 0; float bestscore = 0.0; for (int i = 0; i < 24; ++i) { histogram[i] = (keyleak * histogram[i]) + key[i]; if (histogram[i] > bestscore) { bestscore = histogram[i]; bestkey = i; } // printf("%f ",histogram[i]); } // should find secondbest and only swap if win by a margin // printf(" best %d \n\n",bestkey); // what is winning currently? find max in histogram unit->m_currentKey = bestkey; // about 5 times per second // if((unit->m_triggerid) && ((unit->m_frame%2==0))) SendTrigger(&unit->mParent->mNode, unit->m_triggerid, bestkey); }
71,602
C++
.cpp
1,151
36.293658
120
0.442636
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
29,948
PV_UGens.cpp
supercollider_supercollider/server/plugins/PV_UGens.cpp
/* 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 "FFT_UGens.h" #define TWOPI 6.28318530717952646f struct PV_OutOfPlace : Unit { int m_numbins; float* m_tempbuf; }; struct PV_MagSmear : PV_OutOfPlace {}; struct PV_MagShift : PV_OutOfPlace {}; struct PV_BinShift : PV_OutOfPlace {}; struct PV_PhaseShift : Unit { float m_phase_integral; }; struct PV_Diffuser : Unit { int m_numbins; float m_prevtrig, *m_shift; bool m_triggered; }; struct PV_MagFreeze : Unit { int m_numbins; float *m_mags, m_dc, m_nyq; }; struct PV_RandWipe : Unit { int *m_ordering, m_numbins; float m_prevtrig; bool m_triggered; }; struct PV_RandComb : Unit { int *m_ordering, m_numbins; float m_prevtrig; bool m_triggered; }; struct PV_BinScramble : Unit { int *m_from, *m_to, m_numbins; float m_prevtrig; float* m_tempbuf; bool m_triggered; }; struct PV_Conj : PV_Unit {}; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void PV_PhaseShift_Ctor(PV_PhaseShift* unit); void PV_PhaseShift_next(PV_PhaseShift* unit, int inNumSamples); void PV_PhaseShift90_Ctor(PV_Unit* unit); void PV_PhaseShift90_next(PV_Unit* unit, int inNumSamples); void PV_PhaseShift270_Ctor(PV_Unit* unit); void PV_PhaseShift270_next(PV_Unit* unit, int inNumSamples); void PV_MagClip_Ctor(PV_Unit* unit); void PV_MagClip_next(PV_Unit* unit, int inNumSamples); void PV_MagAbove_Ctor(PV_Unit* unit); void PV_MagAbove_next(PV_Unit* unit, int inNumSamples); void PV_MagBelow_Ctor(PV_Unit* unit); void PV_MagBelow_next(PV_Unit* unit, int inNumSamples); void PV_Min_Ctor(PV_Unit* unit); void PV_Min_next(PV_Unit* unit, int inNumSamples); void PV_Max_Ctor(PV_Unit* unit); void PV_Max_next(PV_Unit* unit, int inNumSamples); void PV_Mul_Ctor(PV_Unit* unit); void PV_Mul_next(PV_Unit* unit, int inNumSamples); void PV_Div_Ctor(PV_Unit* unit); void PV_Div_next(PV_Unit* unit, int inNumSamples); void PV_Add_Ctor(PV_Unit* unit); void PV_Add_next(PV_Unit* unit, int inNumSamples); void PV_RectComb_Ctor(PV_Unit* unit); void PV_RectComb_next(PV_Unit* unit, int inNumSamples); void PV_RectComb2_Ctor(PV_Unit* unit); void PV_RectComb2_next(PV_Unit* unit, int inNumSamples); void PV_MagSquared_Ctor(PV_Unit* unit); void PV_MagSquared_next(PV_Unit* unit, int inNumSamples); void PV_MagMul_Ctor(PV_Unit* unit); void PV_MagMul_next(PV_Unit* unit, int inNumSamples); void PV_MagDiv_Ctor(PV_Unit* unit); void PV_MagDiv_next(PV_Unit* unit, int inNumSamples); void PV_Copy_Ctor(PV_Unit* unit); void PV_Copy_next(PV_Unit* unit, int inNumSamples); void PV_CopyPhase_Ctor(PV_Unit* unit); void PV_CopyPhase_next(PV_Unit* unit, int inNumSamples); void PV_MagSmear_Ctor(PV_MagSmear* unit); void PV_MagSmear_Dtor(PV_MagSmear* unit); void PV_MagSmear_next(PV_MagSmear* unit, int inNumSamples); void PV_BinShift_Ctor(PV_BinShift* unit); void PV_BinShift_Dtor(PV_BinShift* unit); void PV_BinShift_next(PV_BinShift* unit, int inNumSamples); void PV_MagShift_Ctor(PV_MagShift* unit); void PV_MagShift_Dtor(PV_MagShift* unit); void PV_MagShift_next(PV_MagShift* unit, int inNumSamples); void PV_MagNoise_Ctor(PV_Unit* unit); void PV_MagNoise_next(PV_Unit* unit, int inNumSamples); void PV_BrickWall_Ctor(PV_Unit* unit); void PV_BrickWall_next(PV_Unit* unit, int inNumSamples); void PV_BinWipe_Ctor(PV_Unit* unit); void PV_BinWipe_next(PV_Unit* unit, int inNumSamples); void PV_LocalMax_Ctor(PV_Unit* unit); void PV_LocalMax_next(PV_Unit* unit, int inNumSamples); void PV_RandComb_Ctor(PV_RandComb* unit); void PV_RandComb_Dtor(PV_RandComb* unit); void PV_RandComb_next(PV_RandComb* unit, int inNumSamples); void PV_RandWipe_Ctor(PV_RandWipe* unit); void PV_RandWipe_Dtor(PV_RandWipe* unit); void PV_RandWipe_next(PV_RandWipe* unit, int inNumSamples); void PV_Diffuser_Ctor(PV_Diffuser* unit); void PV_Diffuser_Dtor(PV_Diffuser* unit); void PV_Diffuser_next(PV_Diffuser* unit, int inNumSamples); void PV_MagFreeze_Ctor(PV_MagFreeze* unit); void PV_MagFreeze_Dtor(PV_MagFreeze* unit); void PV_MagFreeze_next(PV_MagFreeze* unit, int inNumSamples); void PV_BinScramble_Ctor(PV_BinScramble* unit); void PV_BinScramble_Dtor(PV_BinScramble* unit); void PV_BinScramble_next(PV_BinScramble* unit, int inNumSamples); void PV_Conj_Ctor(PV_Unit* unit); void PV_Conj_next(PV_Unit* unit, int inNumSamples); /* spectral feature extractors? : bin freq bin magnitude bin phase bin laden ;-} average magnitude over a range of bins max magnitude over a range of bins max magnitude bin freq */ } ////////////////////////////////////////////////////////////////////////////////////////////////// // SCPolarBuf* ToPolarApx(SndBuf *buf); /* SCPolarBuf* ToPolarApx(SndBuf *buf) { if (buf->coord == coord_Complex) { SCComplexBuf* p = (SCComplexBuf*)buf->data; int numbins = buf->samples - 2 >> 1; for (int i=0; i<numbins; ++i) { p->bin[i].ToPolarApxInPlace(); } buf->coord = coord_Polar; } return (SCPolarBuf*)buf->data; } */ // SCComplexBuf* ToComplexApx(SndBuf *buf); /* SCComplexBuf* ToComplexApx(SndBuf *buf) { if (buf->coord == coord_Polar) { SCPolarBuf* p = (SCPolarBuf*)buf->data; int numbins = buf->samples - 2 >> 1; for (int i=0; i<numbins; ++i) { p->bin[i].ToComplexApxInPlace(); } buf->coord = coord_Complex; } return (SCComplexBuf*)buf->data; } */ ///////////////////////////////////////////////////////////////////////////////////////////// void PV_MagAbove_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float thresh = ZIN0(1); if (std::abs(p->dc) < thresh) p->dc = 0.f; if (std::abs(p->nyq) < thresh) p->nyq = 0.f; for (int i = 0; i < numbins; ++i) { float mag = p->bin[i].mag; if (mag < thresh) p->bin[i].mag = 0.f; } } void PV_MagAbove_Ctor(PV_Unit* unit) { SETCALC(PV_MagAbove_next); ZOUT0(0) = ZIN0(0); } void PV_MagBelow_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float thresh = ZIN0(1); if (std::abs(p->dc) > thresh) p->dc = 0.f; if (std::abs(p->nyq) > thresh) p->nyq = 0.f; for (int i = 0; i < numbins; ++i) { float mag = p->bin[i].mag; if (mag > thresh) p->bin[i].mag = 0.f; } } void PV_MagBelow_Ctor(PV_Unit* unit) { SETCALC(PV_MagBelow_next); ZOUT0(0) = ZIN0(0); } void PV_MagClip_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float thresh = ZIN0(1); if (std::abs(p->dc) > thresh) p->dc = p->dc < 0.f ? -thresh : thresh; if (std::abs(p->nyq) > thresh) p->nyq = p->nyq < 0.f ? -thresh : thresh; for (int i = 0; i < numbins; ++i) { float mag = p->bin[i].mag; if (mag > thresh) p->bin[i].mag = thresh; } } void PV_MagClip_Ctor(PV_Unit* unit) { SETCALC(PV_MagClip_next); ZOUT0(0) = ZIN0(0); } void PV_LocalMax_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float thresh = ZIN0(1); float dc, nyq, mag; // DC is only compared with the one above it dc = std::abs(p->dc); mag = p->bin[0].mag; if (dc < thresh || dc < mag) p->dc = 0.f; // 0th bin compared against DC and 1th if (mag < thresh || mag < dc || mag < p->bin[1].mag) p->bin[0].mag = 0.f; // All the middling bins for (int i = 1; i < numbins - 1; ++i) { float mag = p->bin[i].mag; if (mag < thresh || mag < p->bin[i - 1].mag || mag < p->bin[i + 1].mag) { p->bin[i].mag = 0.f; } } // Penultimate is compared against the one below and the nyq nyq = std::abs(p->nyq); mag = p->bin[numbins - 1].mag; if (mag < thresh || mag < nyq || mag < p->bin[numbins - 2].mag) p->bin[numbins - 1].mag = 0.f; // Nyquist compared against penultimate if (nyq < thresh || nyq < mag) p->nyq = 0.f; } void PV_LocalMax_Ctor(PV_Unit* unit) { SETCALC(PV_LocalMax_next); ZOUT0(0) = ZIN0(0); } void PV_MagSmear_next(PV_MagSmear* unit, int inNumSamples) { PV_GET_BUF MAKE_TEMP_BUF SCPolarBuf* p = ToPolarApx(buf); SCPolarBuf* q = (SCPolarBuf*)unit->m_tempbuf; int width = (int)ZIN0(1); width = sc_clip(width, 0, numbins - 1); float scale = 1.f / (2 * width + 1); q->dc = p->dc; q->nyq = p->nyq; for (int j = 0; j < numbins; j++) { float sum = 0.0; for (int pos = j - width; pos <= j + width; pos++) { if (pos >= 0 && pos < numbins) { sum += p->bin[pos].mag; } } q->bin[j].Set(sum * scale, p->bin[j].phase); } for (int i = 0; i < numbins; i++) { p->bin[i] = q->bin[i]; } } void PV_MagSmear_Ctor(PV_MagSmear* unit) { SETCALC(PV_MagSmear_next); ZOUT0(0) = ZIN0(0); unit->m_tempbuf = nullptr; } void PV_MagSmear_Dtor(PV_MagSmear* unit) { RTFree(unit->mWorld, unit->m_tempbuf); } void PV_BinShift_next(PV_BinShift* unit, int inNumSamples) { PV_GET_BUF MAKE_TEMP_BUF // get shift and stretch params float stretch = ZIN0(1); float shift = ZIN0(2); float interp = ZIN0(3); SCComplexBuf* p = ToComplexApx(buf); SCComplexBuf* q = (SCComplexBuf*)unit->m_tempbuf; // initialize output buf to zeroes for (int i = 0; i < numbins; ++i) { q->bin[i] = 0.f; } float fpos; int i; q->dc = p->dc; q->nyq = p->nyq; if (interp > 0) { for (i = 0, fpos = shift; i < numbins; ++i, fpos += stretch) { int32 fpos0 = (int32)std::floor(fpos); int32 fpos1 = fpos0 + 1; float beta = fpos - std::floor(fpos); float alpha = 1.0f - beta; if (fpos0 >= 0 && fpos0 < numbins) { q->bin[fpos0] += alpha * p->bin[i]; } if (fpos1 >= 0 && fpos1 < numbins) { q->bin[fpos1] += beta * p->bin[i]; } } } else { for (i = 0, fpos = shift; i < numbins; ++i, fpos += stretch) { int32 pos = (int32)(fpos + 0.5); if (pos >= 0 && pos < numbins) { q->bin[pos] += p->bin[i]; } } } memcpy(p->bin, q->bin, numbins * sizeof(SCComplex)); } void PV_BinShift_Ctor(PV_BinShift* unit) { SETCALC(PV_BinShift_next); ZOUT0(0) = ZIN0(0); unit->m_tempbuf = nullptr; } void PV_BinShift_Dtor(PV_BinShift* unit) { RTFree(unit->mWorld, unit->m_tempbuf); } void PV_MagShift_next(PV_MagShift* unit, int inNumSamples) { PV_GET_BUF MAKE_TEMP_BUF // get shift and stretch params float stretch = ZIN0(1); float shift = ZIN0(2); SCPolarBuf* p = ToPolarApx(buf); SCPolarBuf* q = (SCPolarBuf*)unit->m_tempbuf; // initialize output buf to zeroes for (int i = 0; i < numbins; ++i) { q->bin[i].mag = 0.f; q->bin[i].phase = p->bin[i].phase; } float fpos; int i; q->dc = p->dc; q->nyq = p->nyq; for (i = 0, fpos = shift; i < numbins; ++i, fpos += stretch) { int32 pos = (int32)(fpos + 0.5); if (pos >= 0 && pos < numbins) { q->bin[pos].mag += p->bin[i].mag; } } memcpy(p->bin, q->bin, numbins * sizeof(SCComplex)); } void PV_MagShift_Ctor(PV_MagShift* unit) { SETCALC(PV_MagShift_next); ZOUT0(0) = ZIN0(0); unit->m_tempbuf = nullptr; } void PV_MagShift_Dtor(PV_MagShift* unit) { RTFree(unit->mWorld, unit->m_tempbuf); } void PV_MagNoise_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF RGET if (buf->coord == coord_Complex) { SCComplexBuf* p = (SCComplexBuf*)buf->data; for (int i = 0; i < numbins; ++i) { float r = frand2(s1, s2, s3); p->bin[i].real *= r; p->bin[i].imag *= r; } p->dc *= frand2(s1, s2, s3); p->nyq *= frand2(s1, s2, s3); } else { SCPolarBuf* p = (SCPolarBuf*)buf->data; for (int i = 0; i < numbins; ++i) { float r = frand2(s1, s2, s3); p->bin[i].mag *= r; } p->dc *= frand2(s1, s2, s3); p->nyq *= frand2(s1, s2, s3); } RPUT } void PV_MagNoise_Ctor(PV_Unit* unit) { SETCALC(PV_MagNoise_next); ZOUT0(0) = ZIN0(0); } void PV_PhaseShift_next(PV_PhaseShift* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); float shift = ZIN0(1); int integrate = ZIN0(2); float ashift = shift; if (integrate > 0) { ashift += unit->m_phase_integral; unit->m_phase_integral = fmod(ashift, TWOPI); } for (int i = 0; i < numbins; ++i) { p->bin[i].phase += ashift; } } void PV_PhaseShift_Ctor(PV_PhaseShift* unit) { SETCALC(PV_PhaseShift_next); ZOUT0(0) = ZIN0(0); unit->m_phase_integral = 0; } void PV_PhaseShift90_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCComplexBuf* p = ToComplexApx(buf); for (int i = 0; i < numbins; ++i) { float temp = p->bin[i].real; p->bin[i].real = -p->bin[i].imag; p->bin[i].imag = temp; } } void PV_PhaseShift90_Ctor(PV_Unit* unit) { SETCALC(PV_PhaseShift90_next); ZOUT0(0) = ZIN0(0); } void PV_PhaseShift270_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCComplexBuf* p = ToComplexApx(buf); for (int i = 0; i < numbins; ++i) { float temp = p->bin[i].real; p->bin[i].real = p->bin[i].imag; p->bin[i].imag = -temp; } } void PV_PhaseShift270_Ctor(PV_Unit* unit) { SETCALC(PV_PhaseShift270_next); ZOUT0(0) = ZIN0(0); } void PV_MagSquared_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCPolarBuf* p = ToPolarApx(buf); p->dc = p->dc * p->dc; p->nyq = p->nyq * p->nyq; for (int i = 0; i < numbins; ++i) { float mag = p->bin[i].mag; p->bin[i].mag = mag * mag; } } void PV_MagSquared_Ctor(PV_Unit* unit) { SETCALC(PV_MagSquared_next); ZOUT0(0) = ZIN0(0); } void PV_BrickWall_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCComplexBuf* p = (SCComplexBuf*)buf->data; int wipe = (int)(ZIN0(1) * numbins); if (wipe > 0) { wipe = sc_min(wipe, numbins); p->dc = 0.f; for (int i = 0; i < wipe; ++i) { p->bin[i] = 0.f; } if (wipe == numbins) p->nyq = 0.f; } else if (wipe < 0) { wipe = sc_max(wipe, -numbins); if (wipe == -numbins) p->dc = 0.f; for (int i = numbins + wipe; i < numbins; ++i) { p->bin[i] = 0.f; } p->nyq = 0.f; } } void PV_BrickWall_Ctor(PV_Unit* unit) { SETCALC(PV_BrickWall_next); ZOUT0(0) = ZIN0(0); } void PV_BinWipe_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCComplexBuf* p = (SCComplexBuf*)buf1->data; SCComplexBuf* q = (SCComplexBuf*)buf2->data; int wipe = (int)(ZIN0(2) * numbins); if (wipe > 0) { wipe = sc_min(wipe, numbins); p->dc = q->dc; for (int i = 0; i < wipe; ++i) { p->bin[i] = q->bin[i]; } if (wipe == numbins) p->nyq = q->nyq; } else if (wipe < 0) { wipe = sc_max(wipe, -numbins); if (wipe == -numbins) p->dc = q->dc; for (int i = numbins + wipe; i < numbins; ++i) { p->bin[i] = q->bin[i]; } p->nyq = q->nyq; } } void PV_BinWipe_Ctor(PV_Unit* unit) { SETCALC(PV_BinWipe_next); ZOUT0(0) = ZIN0(0); } void PV_MagMul_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCPolarBuf* p = ToPolarApx(buf1); SCPolarBuf* q = ToPolarApx(buf2); p->dc *= q->dc; p->nyq *= q->nyq; for (int i = 0; i < numbins; ++i) { p->bin[i].mag *= q->bin[i].mag; } } void PV_MagMul_Ctor(PV_Unit* unit) { SETCALC(PV_MagMul_next); ZOUT0(0) = ZIN0(0); } void PV_MagDiv_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCPolarBuf* p = ToPolarApx(buf1); SCPolarBuf* q = ToPolarApx(buf2); float zeroed = ZIN0(2); p->dc /= sc_max(q->dc, zeroed); p->nyq /= sc_max(q->nyq, zeroed); for (int i = 0; i < numbins; ++i) { p->bin[i].mag /= sc_max(q->bin[i].mag, zeroed); } } void PV_MagDiv_Ctor(PV_Unit* unit) { SETCALC(PV_MagDiv_next); ZOUT0(0) = ZIN0(0); } void PV_Copy_next(PV_Unit* unit, int inNumSamples) { float fbufnum1 = ZIN0(0); float fbufnum2 = ZIN0(1); if (fbufnum1 < 0.f || fbufnum2 < 0.f) { ZOUT0(0) = -1.f; return; } ZOUT0(0) = fbufnum2; uint32 ibufnum1 = (int)fbufnum1; uint32 ibufnum2 = (int)fbufnum2; World* world = unit->mWorld; SndBuf* buf1; SndBuf* buf2; if (ibufnum1 >= world->mNumSndBufs) { int localBufNum = ibufnum1 - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf1 = parent->mLocalSndBufs + localBufNum; } else { buf1 = world->mSndBufs; } } else { buf1 = world->mSndBufs + ibufnum1; } if (ibufnum2 >= world->mNumSndBufs) { int localBufNum = ibufnum2 - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localBufNum) { buf2 = parent->mLocalSndBufs + localBufNum; } else { buf2 = world->mSndBufs; } } else { buf2 = world->mSndBufs + ibufnum2; } if (buf1->samples != buf2->samples) return; // copy to buf2 LOCK_SNDBUF2_SHARED_EXCLUSIVE(buf1, buf2); buf2->coord = buf1->coord; memcpy(buf2->data, buf1->data, buf1->samples * sizeof(float)); } void PV_Copy_Ctor(PV_Unit* unit) { SETCALC(PV_Copy_next); ZOUT0(0) = ZIN0(1); } void PV_CopyPhase_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCPolarBuf* p = ToPolarApx(buf1); SCPolarBuf* q = ToPolarApx(buf2); if ((p->dc > 0.f) == (q->dc < 0.f)) p->dc = -p->dc; if ((p->nyq > 0.f) == (q->nyq < 0.f)) p->nyq = -p->nyq; for (int i = 0; i < numbins; ++i) { p->bin[i].phase = q->bin[i].phase; } } void PV_CopyPhase_Ctor(PV_Unit* unit) { SETCALC(PV_CopyPhase_next); ZOUT0(0) = ZIN0(0); } void PV_Mul_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCComplexBuf* p = ToComplexApx(buf1); SCComplexBuf* q = ToComplexApx(buf2); float preal, realmul, imagmul; p->dc *= q->dc; p->nyq *= q->nyq; for (int i = 0; i < numbins; ++i) { preal = p->bin[i].real; // Complex multiply using only 3 multiplications rather than 4. // http://mathworld.wolfram.com/ComplexMultiplication.html realmul = (preal * q->bin[i].real); imagmul = (p->bin[i].imag * q->bin[i].imag); p->bin[i].real = realmul - imagmul; p->bin[i].imag = (preal + p->bin[i].imag) * (q->bin[i].real + q->bin[i].imag) - realmul - imagmul; } } void PV_Mul_Ctor(PV_Unit* unit) { SETCALC(PV_Mul_next); ZOUT0(0) = ZIN0(0); } void PV_Div_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCComplexBuf* p = ToComplexApx(buf1); SCComplexBuf* q = ToComplexApx(buf2); p->dc /= q->dc; p->nyq /= q->nyq; for (int i = 0; i < numbins; ++i) { // See http://gcc.gnu.org/ml/fortran/2004-05/msg00029.html // Note that hypot has danger of overflow (see URL above), // however FFT values typically stay within a small range, // so I'm considering this OK for now. float hypot = q->bin[i].real * q->bin[i].real + q->bin[i].imag * q->bin[i].imag; float preal = p->bin[i].real; p->bin[i].real = (preal * q->bin[i].real + p->bin[i].imag * q->bin[i].imag) / hypot; p->bin[i].imag = (p->bin[i].imag * q->bin[i].real - preal * q->bin[i].imag) / hypot; } } void PV_Div_Ctor(PV_Unit* unit) { SETCALC(PV_Div_next); ZOUT0(0) = ZIN0(0); } void PV_Add_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCComplexBuf* p = ToComplexApx(buf1); SCComplexBuf* q = ToComplexApx(buf2); p->dc += q->dc; p->nyq += q->nyq; for (int i = 0; i < numbins; ++i) { p->bin[i].real += q->bin[i].real; p->bin[i].imag += q->bin[i].imag; } } void PV_Add_Ctor(PV_Unit* unit) { SETCALC(PV_Add_next); ZOUT0(0) = ZIN0(0); } void PV_Max_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCPolarBuf* p = ToPolarApx(buf1); SCPolarBuf* q = ToPolarApx(buf2); if (std::abs(q->dc) > std::abs(p->dc)) p->dc = q->dc; if (std::abs(q->nyq) > std::abs(p->nyq)) p->nyq = q->nyq; for (int i = 0; i < numbins; ++i) { if (q->bin[i].mag > p->bin[i].mag) { p->bin[i] = q->bin[i]; } } } void PV_Max_Ctor(PV_Unit* unit) { SETCALC(PV_Max_next); ZOUT0(0) = ZIN0(0); } void PV_Min_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 SCPolarBuf* p = ToPolarApx(buf1); SCPolarBuf* q = ToPolarApx(buf2); if (std::abs(q->dc) < std::abs(p->dc)) p->dc = q->dc; if (std::abs(q->nyq) < std::abs(p->nyq)) p->nyq = q->nyq; for (int i = 0; i < numbins; ++i) { if (q->bin[i].mag < p->bin[i].mag) { p->bin[i] = q->bin[i]; } } } void PV_Min_Ctor(PV_Unit* unit) { SETCALC(PV_Min_next); ZOUT0(0) = ZIN0(0); } void PV_RectComb_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF float numTeeth = ZIN0(1); float phase = ZIN0(2); float width = ZIN0(3); float freq = numTeeth / (numbins + 1); SCComplexBuf* p = (SCComplexBuf*)buf->data; if (phase > width) p->dc = 0.f; phase += freq; if (phase >= 1.f) phase -= 1.f; else if (phase < 0.f) phase += 1.f; for (int i = 0; i < numbins; ++i) { if (phase > width) p->bin[i] = 0.f; phase += freq; if (phase >= 1.f) phase -= 1.f; else if (phase < 0.f) phase += 1.f; } if (phase > width) p->nyq = 0.f; } void PV_RectComb_Ctor(PV_Unit* unit) { SETCALC(PV_RectComb_next); ZOUT0(0) = ZIN0(0); } void PV_RectComb2_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF2 float numTeeth = ZIN0(2); float phase = ZIN0(3); float width = ZIN0(4); float freq = numTeeth / (numbins + 1); SCComplexBuf* p = (SCComplexBuf*)buf1->data; SCComplexBuf* q = (SCComplexBuf*)buf2->data; if (phase > width) p->dc = q->dc; phase += freq; if (phase >= 1.f) phase -= 1.f; else if (phase < 0.f) phase += 1.f; for (int i = 0; i < numbins; ++i) { if (phase > width) p->bin[i] = q->bin[i]; phase += freq; if (phase >= 1.f) phase -= 1.f; else if (phase < 0.f) phase += 1.f; } if (phase > width) p->nyq = q->nyq; } void PV_RectComb2_Ctor(PV_Unit* unit) { SETCALC(PV_RectComb2_next); ZOUT0(0) = ZIN0(0); } static void PV_RandComb_choose(PV_RandComb* unit) { int numbins = unit->m_numbins; for (int i = 0; i < numbins; ++i) { unit->m_ordering[i] = i; } RGET for (int i = 0; i < numbins; ++i) { int32 j = (int32)(frand(s1, s2, s3) * (numbins - i)); int32 temp = unit->m_ordering[i]; unit->m_ordering[i] = unit->m_ordering[j]; unit->m_ordering[j] = temp; } RPUT } void PV_RandComb_next(PV_RandComb* unit, int inNumSamples) { float trig = ZIN0(2); if (trig > 0.f && unit->m_prevtrig <= 0.f) unit->m_triggered = true; unit->m_prevtrig = trig; PV_GET_BUF if (!unit->m_ordering) { unit->m_ordering = (int*)RTAlloc(unit->mWorld, numbins * sizeof(int)); ClearFFTUnitIfMemFailed(unit->m_ordering); unit->m_numbins = numbins; PV_RandComb_choose(unit); } else { if (numbins != unit->m_numbins) return; if (unit->m_triggered) { unit->m_triggered = false; PV_RandComb_choose(unit); } } int n = (int)(ZIN0(1) * numbins); n = sc_clip(n, 0, numbins); SCComplexBuf* p = (SCComplexBuf*)buf->data; int* ordering = unit->m_ordering; for (int i = 0; i < n; ++i) { p->bin[ordering[i]] = 0.f; } if (n == numbins) { // including dc and nyq in the above shuffle would add too much complexity. but at full "wipe" we should get // silence. p->dc = 0.f; p->nyq = 0.f; } } void PV_RandComb_Ctor(PV_RandComb* unit) { SETCALC(PV_RandComb_next); ZOUT0(0) = ZIN0(0); unit->m_ordering = nullptr; unit->m_prevtrig = 0.f; unit->m_triggered = false; } void PV_RandComb_Dtor(PV_RandComb* unit) { RTFree(unit->mWorld, unit->m_ordering); } ////////////////////// static void PV_RandWipe_choose(PV_RandWipe* unit) { int numbins = unit->m_numbins; for (int i = 0; i < numbins; ++i) { unit->m_ordering[i] = i; } RGET for (int i = 0; i < numbins; ++i) { int32 j = (int32)(frand(s1, s2, s3) * (numbins - i)); int32 temp = unit->m_ordering[i]; unit->m_ordering[i] = unit->m_ordering[j]; unit->m_ordering[j] = temp; } RPUT } void PV_RandWipe_next(PV_RandWipe* unit, int inNumSamples) { float trig = ZIN0(3); if (trig > 0.f && unit->m_prevtrig <= 0.f) unit->m_triggered = true; unit->m_prevtrig = trig; PV_GET_BUF2 if (!unit->m_ordering) { unit->m_ordering = (int*)RTAlloc(unit->mWorld, numbins * sizeof(int)); ClearFFTUnitIfMemFailed(unit->m_ordering); unit->m_numbins = numbins; PV_RandWipe_choose(unit); } else { if (numbins != unit->m_numbins) return; if (unit->m_triggered) { unit->m_triggered = false; PV_RandWipe_choose(unit); } } int n = (int)(ZIN0(2) * numbins); n = sc_clip(n, 0, numbins); SCComplexBuf* p = (SCComplexBuf*)buf1->data; SCComplexBuf* q = (SCComplexBuf*)buf2->data; int* ordering = unit->m_ordering; for (int i = 0; i < n; ++i) { p->bin[ordering[i]] = q->bin[ordering[i]]; } } void PV_RandWipe_Ctor(PV_RandWipe* unit) { SETCALC(PV_RandWipe_next); ZOUT0(0) = ZIN0(0); unit->m_ordering = nullptr; unit->m_prevtrig = 0.f; unit->m_triggered = false; } void PV_RandWipe_Dtor(PV_RandWipe* unit) { RTFree(unit->mWorld, unit->m_ordering); } ////////////////////// static void PV_Diffuser_choose(PV_Diffuser* unit) { RGET for (int i = 0; i < unit->m_numbins; ++i) { unit->m_shift[i] = frand(s1, s2, s3) * twopi; } RPUT } void PV_Diffuser_next(PV_Diffuser* unit, int inNumSamples) { float trig = ZIN0(1); if (trig > 0.f && unit->m_prevtrig <= 0.f) unit->m_triggered = true; unit->m_prevtrig = trig; PV_GET_BUF if (!unit->m_shift) { unit->m_shift = (float*)RTAlloc(unit->mWorld, numbins * sizeof(float)); ClearFFTUnitIfMemFailed(unit->m_shift); unit->m_numbins = numbins; PV_Diffuser_choose(unit); } else { if (numbins != unit->m_numbins) return; if (unit->m_triggered) { unit->m_triggered = false; PV_Diffuser_choose(unit); } } int n = (int)(ZIN0(1) * numbins); n = sc_clip(n, 0, numbins); SCPolarBuf* p = ToPolarApx(buf); float* shift = unit->m_shift; for (int i = 0; i < n; ++i) { p->bin[i].phase += shift[i]; } } void PV_Diffuser_Ctor(PV_Diffuser* unit) { SETCALC(PV_Diffuser_next); ZOUT0(0) = ZIN0(0); unit->m_shift = nullptr; unit->m_prevtrig = 0.f; unit->m_triggered = false; } void PV_Diffuser_Dtor(PV_Diffuser* unit) { RTFree(unit->mWorld, unit->m_shift); } ////////////////////// void PV_MagFreeze_next(PV_MagFreeze* unit, int inNumSamples) { PV_GET_BUF float freeze = ZIN0(1); if (!unit->m_mags) { unit->m_mags = (float*)RTAlloc(unit->mWorld, numbins * sizeof(float)); ClearFFTUnitIfMemFailed(unit->m_mags); unit->m_numbins = numbins; // The first fft frame must use the else branch below // so that unit->m_mags gets populated with actual mag data // before reading; otherwise it might be used uninitialized. freeze = 0.f; } else if (numbins != unit->m_numbins) return; SCPolarBuf* p = ToPolarApx(buf); float* mags = unit->m_mags; if (freeze > 0.f) { for (int i = 0; i < numbins; ++i) { p->bin[i].mag = mags[i]; } p->dc = unit->m_dc; p->nyq = unit->m_nyq; } else { for (int i = 0; i < numbins; ++i) { mags[i] = p->bin[i].mag; } unit->m_dc = p->dc; unit->m_nyq = p->nyq; } } void PV_MagFreeze_Ctor(PV_MagFreeze* unit) { SETCALC(PV_MagFreeze_next); ZOUT0(0) = ZIN0(0); unit->m_mags = nullptr; } void PV_MagFreeze_Dtor(PV_MagFreeze* unit) { RTFree(unit->mWorld, unit->m_mags); } ////////////////////// static void PV_BinScramble_choose(PV_BinScramble* unit) { int numbins = unit->m_numbins; int* to = unit->m_to; int* from = unit->m_from; for (int i = 0; i < numbins; ++i) { to[i] = i; } RGET for (int i = 0; i < numbins; ++i) { int32 j = (int32)(frand(s1, s2, s3) * (numbins - i)); int32 temp = to[i]; to[i] = to[j]; to[j] = temp; } int32 width = (int32)(ZIN0(2) * numbins); for (int i = 0; i < numbins; ++i) { int32 k = to[i]; int32 minr = sc_max(0, k - width); int32 maxr = sc_min(numbins - 1, k + width); int32 j = (int32)(frand(s1, s2, s3) * (maxr - minr) + minr); from[i] = j; } RPUT } void PV_BinScramble_next(PV_BinScramble* unit, int inNumSamples) { float trig = ZIN0(3); if (trig > 0.f && unit->m_prevtrig <= 0.f) unit->m_triggered = true; unit->m_prevtrig = trig; PV_GET_BUF if (!unit->m_to) { unit->m_to = (int*)RTAlloc(unit->mWorld, numbins * 2 * sizeof(int)); unit->m_from = unit->m_to + numbins; unit->m_numbins = numbins; unit->m_tempbuf = (float*)RTAlloc(unit->mWorld, buf->samples * sizeof(float)); ClearFFTUnitIfMemFailed(unit->m_to && unit->m_tempbuf); PV_BinScramble_choose(unit); } else { if (numbins != unit->m_numbins) return; if (unit->m_triggered) { unit->m_triggered = false; PV_BinScramble_choose(unit); } } SCComplexBuf* p = (SCComplexBuf*)buf->data; SCComplexBuf* q = (SCComplexBuf*)unit->m_tempbuf; float wipe = ZIN0(1); int32 scrambleBins = (int32)(numbins * sc_clip(wipe, 0.f, 1.f)); int* to = unit->m_to; int* from = unit->m_from; for (int j = 0; j < scrambleBins; j++) { q->bin[to[j]] = p->bin[from[j]]; } for (int j = scrambleBins; j < numbins; j++) { int32 a = to[j]; q->bin[a] = p->bin[a]; } q->dc = p->dc; q->nyq = p->nyq; memcpy(p->bin, q->bin, numbins * sizeof(SCComplex)); } void PV_BinScramble_Ctor(PV_BinScramble* unit) { SETCALC(PV_BinScramble_next); ZOUT0(0) = ZIN0(0); unit->m_to = nullptr; unit->m_prevtrig = 0.f; unit->m_triggered = false; unit->m_tempbuf = nullptr; } void PV_BinScramble_Dtor(PV_BinScramble* unit) { RTFree(unit->mWorld, unit->m_to); RTFree(unit->mWorld, unit->m_tempbuf); } void PV_Conj_Ctor(PV_Unit* unit) { SETCALC(PV_Conj_next); ZOUT0(0) = ZIN0(0); } void PV_Conj_next(PV_Unit* unit, int inNumSamples) { PV_GET_BUF SCComplexBuf* p = ToComplexApx(buf); for (int i = 0; i < numbins; ++i) { p->bin[i].imag = 0.f - p->bin[i].imag; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// #define DefinePVUnit(name) (*ft->fDefineUnit)(#name, sizeof(PV_Unit), (UnitCtorFunc)&name##_Ctor, 0, 0); void initPV(InterfaceTable* inTable) { DefinePVUnit(PV_MagAbove); DefinePVUnit(PV_MagBelow); DefinePVUnit(PV_MagClip); DefinePVUnit(PV_MagMul); DefinePVUnit(PV_MagDiv); DefinePVUnit(PV_MagSquared); DefinePVUnit(PV_MagNoise); DefinePVUnit(PV_Copy); DefinePVUnit(PV_CopyPhase); DefinePVUnit(PV_PhaseShift); DefinePVUnit(PV_PhaseShift90); DefinePVUnit(PV_PhaseShift270); DefinePVUnit(PV_Min); DefinePVUnit(PV_Max); DefinePVUnit(PV_Mul); DefinePVUnit(PV_Div); DefinePVUnit(PV_Add); DefinePVUnit(PV_RectComb); DefinePVUnit(PV_RectComb2); DefinePVUnit(PV_BrickWall); DefinePVUnit(PV_BinWipe); DefinePVUnit(PV_LocalMax); DefinePVUnit(PV_Conj); DefineDtorUnit(PV_BinScramble); DefineDtorUnit(PV_MagSmear); DefineDtorUnit(PV_MagShift); DefineDtorUnit(PV_BinShift); DefineDtorUnit(PV_RandWipe); DefineDtorUnit(PV_Diffuser); DefineDtorUnit(PV_RandComb); DefineDtorUnit(PV_MagFreeze); }
33,992
C++
.cpp
1,045
26.896651
116
0.579947
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
29,949
DemandUGens.cpp
supercollider_supercollider/server/plugins/DemandUGens.cpp
/* 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_PlugIn.h" #include <cstdio> #include <cmath> #include <limits> using std::floor; using std::numeric_limits; static InterfaceTable* ft; struct Demand : public Unit { float m_prevtrig; float m_prevreset; float* m_prevout; float** m_out; }; struct Duty : public Unit { float m_count; float m_prevreset; float m_prevout; }; struct DemandEnvGen : public Unit { float m_phase; float m_prevreset; double m_a1, m_a2, m_b1, m_y1, m_y2, m_grow, m_level, m_endLevel, m_curve; int m_shape; bool m_release, m_running; }; struct TDuty : public Unit { float m_count; float m_prevreset; }; struct Dseries : public Unit { double m_repeats; int32 m_repeatCount; double m_value; double m_step; }; struct Dgeom : public Unit { double m_repeats; int32 m_repeatCount; double m_value; double m_grow; }; struct Dwhite : public Unit { double m_repeats; int32 m_repeatCount; float m_lo; float m_range; }; struct Dbrown : public Unit { double m_repeats; int32 m_repeatCount; float m_lo; float m_hi; float m_step; float m_val; }; struct Diwhite : public Unit { double m_repeats; int32 m_repeatCount; int32 m_lo; int32 m_range; }; struct Dibrown : public Unit { double m_repeats; int32 m_repeatCount; int32 m_lo; int32 m_hi; int32 m_step; int32 m_val; }; struct Dseq : public Unit { double m_repeats; int32 m_repeatCount; int32 m_index; bool m_needToResetChild; }; struct Dshuf : public Unit { double m_repeats; int32 m_repeatCount; int32 m_index; bool m_needToResetChild; int32* m_indices; }; struct Dbufrd : public Unit { float m_fbufnum; SndBuf* m_buf; }; struct Dbufwr : public Unit { float m_fbufnum; SndBuf* m_buf; }; struct Dser : public Dseq {}; struct Drand : public Dseq {}; struct Dxrand : public Dseq {}; struct Dwrand : public Dseq { int32 m_weights_size; }; struct Dswitch1 : public Unit {}; struct Dswitch : public Unit { int m_index; }; struct Dstutter : public Unit { double m_repeats; double m_repeatCount; float m_value; }; struct Ddup : public Unit { double m_repeats; double m_repeatCount; float m_value; }; struct Dpoll : public Unit { char* m_id_string; bool m_mayprint; float m_id; }; struct Dreset : public Unit { float prev_reset; }; struct Dconst : public Unit { float m_total; float m_runningsum; float m_tolerance; }; extern "C" { void Demand_Ctor(Demand* unit); void Demand_Dtor(Demand* unit); void Demand_next_aa(Demand* unit, int inNumSamples); void Demand_next_ak(Demand* unit, int inNumSamples); void Demand_next_ka(Demand* unit, int inNumSamples); void Duty_Ctor(Duty* unit); void Duty_next_da(Duty* unit, int inNumSamples); void Duty_next_dk(Duty* unit, int inNumSamples); void Duty_next_dd(Duty* unit, int inNumSamples); void TDuty_Ctor(TDuty* unit); void TDuty_next_da(TDuty* unit, int inNumSamples); void TDuty_next_dk(TDuty* unit, int inNumSamples); void TDuty_next_dd(TDuty* unit, int inNumSamples); void DemandEnvGen_Ctor(DemandEnvGen* unit); void DemandEnvGen_next_k(DemandEnvGen* unit, int inNumSamples); void DemandEnvGen_next_a(DemandEnvGen* unit, int inNumSamples); void Dseries_Ctor(Dseries* unit); void Dseries_next(Dseries* unit, int inNumSamples); void Dgeom_Ctor(Dgeom* unit); void Dgeom_next(Dgeom* unit, int inNumSamples); void Dwhite_Ctor(Dwhite* unit); void Dwhite_next(Dwhite* unit, int inNumSamples); void Dbrown_Ctor(Dbrown* unit); void Dbrown_next(Dbrown* unit, int inNumSamples); void Diwhite_Ctor(Diwhite* unit); void Diwhite_next(Diwhite* unit, int inNumSamples); void Dibrown_Ctor(Dibrown* unit); void Dibrown_next(Dibrown* unit, int inNumSamples); void Dseq_Ctor(Dseq* unit); void Dseq_next(Dseq* unit, int inNumSamples); void Dshuf_Ctor(Dshuf* unit); void Dshuf_Dtor(Dshuf* unit); void Dshuf_next(Dshuf* unit, int inNumSamples); void Dbufrd_Ctor(Dbufrd* unit); void Dbufrd_next(Dbufrd* unit, int inNumSamples); void Dbufwr_Ctor(Dbufwr* unit); void Dbufwr_next(Dbufwr* unit, int inNumSamples); void Dser_Ctor(Dser* unit); void Dser_next(Dser* unit, int inNumSamples); void Drand_Ctor(Drand* unit); void Drand_next(Drand* unit, int inNumSamples); void Dxrand_Ctor(Dxrand* unit); void Dxrand_next(Dxrand* unit, int inNumSamples); void Dwrand_Ctor(Dwrand* unit); void Dwrand_next(Dwrand* unit, int inNumSamples); void Dswitch1_Ctor(Dswitch1* unit); void Dswitch1_next(Dswitch1* unit, int inNumSamples); void Dswitch_Ctor(Dswitch* unit); void Dswitch_next(Dswitch* unit, int inNumSamples); void Dstutter_Ctor(Dstutter* unit); void Dstutter_next(Dstutter* unit, int inNumSamples); void Ddup_Ctor(Ddup* unit); void Ddup_next(Ddup* unit, int inNumSamples); void Dpoll_Ctor(Dpoll* unit); void Dpoll_Ctor(Dpoll* unit); void Dpoll_next(Dpoll* unit, int inNumSamples); void Dreset_Ctor(Dreset* unit); void Dreset_next(Dreset* unit, int inNumSamples); void Dconst_Ctor(Dconst* unit); void Dconst_next(Dconst* unit, int inNumSamples); }; void Demand_next_aa(Demand* unit, int inNumSamples) { float* trig = ZIN(0); float* reset = ZIN(1); float** out = unit->m_out; float* prevout = unit->m_prevout; for (int i = 0; i < unit->mNumOutputs; ++i) { out[i] = OUT(i); } float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; // Print("Demand_next_aa %d %g\n", inNumSamples, prevtrig); for (int i = 0; i < inNumSamples; ++i) { float ztrig = ZXP(trig); float zreset = ZXP(reset); if (zreset > 0.f && prevreset <= 0.f) { for (int j = 2; j < unit->mNumInputs; ++j) { RESETINPUT(j); } } if (ztrig > 0.f && prevtrig <= 0.f) { // Print("triggered\n"); for (int j = 2, k = 0; j < unit->mNumInputs; ++j, ++k) { float x = DEMANDINPUT_A(j, i + 1); // printf("in %d %g\n", k, x); if (sc_isnan(x)) { x = prevout[k]; unit->mDone = true; } else prevout[k] = x; out[k][i] = x; } } else { for (int j = 2, k = 0; j < unit->mNumInputs; ++j, ++k) { out[k][i] = prevout[k]; } } prevtrig = ztrig; prevreset = zreset; } unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void Demand_next_ak(Demand* unit, int inNumSamples) { float* trig = ZIN(0); float zreset = IN0(1); float** out = unit->m_out; float* prevout = unit->m_prevout; for (int i = 0; i < unit->mNumOutputs; ++i) { out[i] = OUT(i); } float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; for (int i = 0; i < inNumSamples; ++i) { float ztrig = ZXP(trig); if (zreset > 0.f && prevreset <= 0.f) { for (int j = 2; j < unit->mNumInputs; ++j) { RESETINPUT(j); } } if (ztrig > 0.f && prevtrig <= 0.f) { for (int j = 2, k = 0; j < unit->mNumInputs; ++j, ++k) { float x = DEMANDINPUT_A(j, i + 1); if (sc_isnan(x)) { x = prevout[k]; unit->mDone = true; } else prevout[k] = x; out[k][i] = x; } } else { for (int j = 2, k = 0; j < unit->mNumInputs; ++j, ++k) { out[k][i] = prevout[k]; } } prevtrig = ztrig; prevreset = zreset; } unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void Demand_next_ka(Demand* unit, int inNumSamples) { float ztrig = IN0(0); float* reset = ZIN(1); float** out = unit->m_out; float* prevout = unit->m_prevout; for (int i = 0; i < unit->mNumOutputs; ++i) { out[i] = OUT(i); } float prevtrig = unit->m_prevtrig; float prevreset = unit->m_prevreset; for (int i = 0; i < inNumSamples; ++i) { float zreset = ZXP(reset); if (zreset > 0.f && prevreset <= 0.f) { for (int j = 2; j < unit->mNumInputs; ++j) { RESETINPUT(j); } } if (ztrig > 0.f && prevtrig <= 0.f) { for (int j = 2, k = 0; j < unit->mNumInputs; ++j, ++k) { float x = DEMANDINPUT_A(j, i + 1); if (sc_isnan(x)) { x = prevout[k]; unit->mDone = true; } else prevout[k] = x; out[k][i] = x; } } prevtrig = ztrig; prevreset = zreset; } unit->m_prevtrig = prevtrig; unit->m_prevreset = prevreset; } void Demand_Ctor(Demand* unit) { // Print("Demand_Ctor\n"); if (INRATE(0) == calc_FullRate) { if (INRATE(1) == calc_FullRate) { SETCALC(Demand_next_aa); } else { SETCALC(Demand_next_ak); } } else { if (INRATE(1) == calc_FullRate) { SETCALC(Demand_next_ka); } else { SETCALC(Demand_next_aa); } } for (int i = 0; i < unit->mNumOutputs; ++i) OUT0(i) = 0.f; char* memoryChunk = (char*)RTAlloc(unit->mWorld, unit->mNumOutputs * (sizeof(float) + sizeof(float*))); ClearUnitIfMemFailed(memoryChunk); unit->m_prevout = (float*)memoryChunk; unit->m_out = (float**)(memoryChunk + unit->mNumOutputs * sizeof(float)); unit->m_prevtrig = 0.f; unit->m_prevreset = 0.f; std::fill_n(unit->m_prevout, unit->mNumOutputs, 0.f); } void Demand_Dtor(Demand* unit) { if (unit->m_prevout) RTFree(unit->mWorld, unit->m_prevout); } ///////////////////////////////////////////////////////////////////////////// enum { duty_dur, duty_reset, duty_doneAction, duty_level }; void Duty_next_da(Duty* unit, int inNumSamples) { float* reset = ZIN(duty_reset); float* out = OUT(0); float prevout = unit->m_prevout; float count = unit->m_count; float prevreset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { float zreset = ZXP(reset); if (zreset > 0.f && prevreset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); // printf("in %d\n", count); if (sc_isnan(x)) { x = prevout; int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } else { prevout = x; } out[i] = x; } else { out[i] = prevout; } count--; prevreset = zreset; } unit->m_count = count; unit->m_prevreset = prevreset; unit->m_prevout = prevout; } void Duty_next_dk(Duty* unit, int inNumSamples) { float zreset = ZIN0(duty_reset); float* out = OUT(0); float prevout = unit->m_prevout; float count = unit->m_count; float prevreset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { if (zreset > 0.f && prevreset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); if (sc_isnan(x)) { x = prevout; int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } else { prevout = x; } out[i] = x; } else { out[i] = prevout; } count--; prevreset = zreset; } unit->m_count = count; unit->m_prevreset = prevreset; unit->m_prevout = prevout; } void Duty_next_dd(Duty* unit, int inNumSamples) { float* out = OUT(0); float prevout = unit->m_prevout; float count = unit->m_count; float reset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { if (reset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; reset = DEMANDINPUT_A(duty_reset, i + 1) * sr + reset; } else { reset--; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); // printf("in %d %g\n", k, x); if (sc_isnan(x)) { x = prevout; int doneAction = (int)ZIN0(duty_doneAction); DoneAction(doneAction, unit); } else { prevout = x; } } out[i] = prevout; count--; } unit->m_count = count; unit->m_prevreset = reset; unit->m_prevout = prevout; } void Duty_Ctor(Duty* unit) { // DEMANDINPUT_A is not needed here, because we are at init time. if (INRATE(duty_reset) == calc_FullRate) { SETCALC(Duty_next_da); unit->m_prevreset = 0.f; } else { if (INRATE(duty_reset) == calc_DemandRate) { SETCALC(Duty_next_dd); unit->m_prevreset = DEMANDINPUT(duty_reset) * SAMPLERATE; } else { SETCALC(Duty_next_dk); unit->m_prevreset = 0.f; } } unit->m_count = DEMANDINPUT(duty_dur) * SAMPLERATE; unit->m_prevout = DEMANDINPUT(duty_level); OUT0(0) = unit->m_prevout; } ///////////////////////////////////////////////////////////////////////////// enum { d_env_level, d_env_dur, d_env_shape, d_env_curve, d_env_gate, d_env_reset, d_env_levelScale, d_env_levelBias, d_env_timeScale, d_env_doneAction }; enum { shape_Step, shape_Linear, shape_Exponential, shape_Sine, shape_Welch, shape_Curve, shape_Squared, shape_Cubed, shape_Sustain = 9999 }; void DemandEnvGen_next_k(DemandEnvGen* unit, int inNumSamples) { float zreset = ZIN0(d_env_reset); float* out = ZOUT(0); double level = unit->m_level; float phase = unit->m_phase; double curve = unit->m_curve; bool release = unit->m_release; bool running = unit->m_running; int shape = unit->m_shape; // printf("phase %f level %f \n", phase, level); for (int i = 0; i < inNumSamples; ++i) { if (zreset > 0.f && unit->m_prevreset <= 0.f) { // printf("reset: %f %f \n", zreset, unit->m_prevreset); RESETINPUT(d_env_level); RESETINPUT(d_env_dur); RESETINPUT(d_env_shape); RESETINPUT(d_env_curve); if (zreset <= 1.f) { DEMANDINPUT(d_env_level); // remove first level } else { level = DEMANDINPUT(d_env_level); // jump to first level } release = false; running = true; phase = 0.f; } if (phase <= 0.f && running) { // was a release during last segment? if (release) { running = false; release = false; // printf("release: %f %f \n", phase, level); int doneAction = (int)ZIN0(d_env_doneAction); DoneAction(doneAction, unit); } else { // new time float dur = DEMANDINPUT(d_env_dur); // printf("dur: %f \n", dur); if (sc_isnan(dur)) { release = true; running = false; phase = numeric_limits<float>::max(); } else { phase = dur * ZIN0(d_env_timeScale) * SAMPLERATE + phase; } // new shape float fshape = DEMANDINPUT(d_env_shape); if (sc_isnan(fshape)) shape = unit->m_shape; else shape = (int)fshape; curve = DEMANDINPUT(d_env_curve); if (sc_isnan(curve)) curve = unit->m_curve; float count; if (phase <= 1.f) { shape = 1; // shape_Linear count = 1.f; } else { count = phase; } if (dur * 0.5f < SAMPLEDUR) shape = 1; // printf("shape: %i, curve: %f, dur: %f \n", shape, curve, dur); // new end level double endLevel = DEMANDINPUT(d_env_level); // printf("levels: %f %f\n", level, endLevel); if (sc_isnan(endLevel)) { endLevel = unit->m_endLevel; release = true; phase = 0.f; shape = 0; } else { endLevel = endLevel * ZIN0(d_env_levelScale) + ZIN0(d_env_levelBias); unit->m_endLevel = endLevel; } // calculate shape parameters switch (shape) { case shape_Step: { level = endLevel; } break; case shape_Linear: { unit->m_grow = (endLevel - level) / count; } break; case shape_Exponential: { unit->m_grow = pow(endLevel / level, 1.0 / count); } break; case shape_Sine: { double w = pi / count; unit->m_a2 = (endLevel + level) * 0.5; unit->m_b1 = 2. * cos(w); unit->m_y1 = (endLevel - level) * 0.5; unit->m_y2 = unit->m_y1 * sin(pi * 0.5 - w); level = unit->m_a2 - unit->m_y1; } break; case shape_Welch: { double w = (pi * 0.5) / count; unit->m_b1 = 2. * cos(w); if (endLevel >= level) { unit->m_a2 = level; unit->m_y1 = 0.; unit->m_y2 = -sin(w) * (endLevel - level); } else { unit->m_a2 = endLevel; unit->m_y1 = level - endLevel; unit->m_y2 = cos(w) * (level - endLevel); } level = unit->m_a2 + unit->m_y1; } break; case shape_Curve: { if (fabs(curve) < 0.001) { unit->m_shape = shape = 1; // shape_Linear unit->m_grow = (endLevel - level) / count; } else { double a1 = (endLevel - level) / (1.0 - exp(curve)); unit->m_a2 = level + a1; unit->m_b1 = a1; unit->m_grow = exp(curve / ceil(count)); } } break; case shape_Squared: { unit->m_y1 = sqrt(level); unit->m_y2 = sqrt(endLevel); unit->m_grow = (unit->m_y2 - unit->m_y1) / count; } break; case shape_Cubed: { unit->m_y1 = pow(level, 0.33333333); unit->m_y2 = pow(endLevel, 0.33333333); unit->m_grow = (unit->m_y2 - unit->m_y1) / count; } break; } } } if (running) { switch (shape) { case shape_Step: { } break; case shape_Linear: { double grow = unit->m_grow; // Print("level %g\n", level); level += grow; } break; case shape_Exponential: { double grow = unit->m_grow; level *= grow; } break; case shape_Sine: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; double y0 = b1 * y1 - y2; level = a2 - y0; y2 = y1; y1 = y0; unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Welch: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; double y0 = b1 * y1 - y2; level = a2 + y0; y2 = y1; y1 = y0; unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Curve: { double a2 = unit->m_a2; double b1 = unit->m_b1; double grow = unit->m_grow; b1 *= grow; level = a2 - b1; unit->m_b1 = b1; } break; case shape_Squared: { double grow = unit->m_grow; double y1 = unit->m_y1; y1 += grow; level = y1 * y1; unit->m_y1 = y1; } break; case shape_Cubed: { double grow = unit->m_grow; double y1 = unit->m_y1; y1 += grow; level = y1 * y1 * y1; unit->m_y1 = y1; } break; case shape_Sustain: { } break; } phase--; } ZXP(out) = level; } float zgate = ZIN0(d_env_gate); if (zgate >= 1.f) { unit->m_running = true; } else if (zgate > 0.f) { unit->m_running = true; release = true; // release next time. } else { unit->m_running = false; // sample and hold } unit->m_level = level; unit->m_curve = curve; unit->m_shape = shape; unit->m_prevreset = zreset; unit->m_release = release; unit->m_phase = phase; } void DemandEnvGen_next_a(DemandEnvGen* unit, int inNumSamples) { float* reset = ZIN(d_env_reset); float* gate = ZIN(d_env_gate); float* out = ZOUT(0); float prevreset = unit->m_prevreset; double level = unit->m_level; float phase = unit->m_phase; double curve = unit->m_curve; bool release = unit->m_release; bool running = unit->m_running; int shape = unit->m_shape; // printf("phase %f \n", phase); for (int i = 0; i < inNumSamples; ++i) { float zreset = ZXP(reset); if (zreset > 0.f && prevreset <= 0.f) { // printf("reset: %f %f \n", zreset, unit->m_prevreset); RESETINPUT(d_env_level); if (zreset <= 1.f) { DEMANDINPUT_A(d_env_level, i + 1); // remove first level } else { level = DEMANDINPUT_A(d_env_level, i + 1); // jump to first level } RESETINPUT(d_env_dur); RESETINPUT(d_env_shape); release = false; running = true; phase = 0.f; } prevreset = zreset; if (phase <= 0.f && running) { // was a release? if (release) { running = false; release = false; // printf("release: %f %f \n", phase, level); int doneAction = (int)ZIN0(d_env_doneAction); DoneAction(doneAction, unit); } else { // new time float dur = DEMANDINPUT_A(d_env_dur, i + 1); // printf("dur: %f \n", dur); if (sc_isnan(dur)) { release = true; running = false; phase = numeric_limits<float>::max(); } else { phase = dur * ZIN0(d_env_timeScale) * SAMPLERATE + phase; } // new shape float count; curve = DEMANDINPUT_A(d_env_curve, i + 1); // printf("shapes: %i \n", shape); if (sc_isnan(curve)) curve = unit->m_curve; float fshape = DEMANDINPUT_A(d_env_shape, i + 1); if (sc_isnan(fshape)) shape = unit->m_shape; else shape = (int)fshape; if (phase <= 1.f) { shape = 1; // shape_Linear count = 1.f; } else { count = phase; } if (dur * 0.5f < SAMPLEDUR) shape = 1; // new end level double endLevel = DEMANDINPUT_A(d_env_level, i + 1); // printf("levels: %f %f\n", level, endLevel); if (sc_isnan(endLevel)) { endLevel = unit->m_endLevel; release = true; phase = 0.f; shape = 0; } else { endLevel = endLevel * ZIN0(d_env_levelScale) + ZIN0(d_env_levelBias); unit->m_endLevel = endLevel; } // calculate shape parameters switch (shape) { case shape_Step: { level = endLevel; } break; case shape_Linear: { unit->m_grow = (endLevel - level) / count; } break; case shape_Exponential: { unit->m_grow = pow(endLevel / level, 1.0 / count); } break; case shape_Sine: { double w = pi / count; unit->m_a2 = (endLevel + level) * 0.5; unit->m_b1 = 2. * cos(w); unit->m_y1 = (endLevel - level) * 0.5; unit->m_y2 = unit->m_y1 * sin(pi * 0.5 - w); level = unit->m_a2 - unit->m_y1; } break; case shape_Welch: { double w = (pi * 0.5) / count; unit->m_b1 = 2. * cos(w); if (endLevel >= level) { unit->m_a2 = level; unit->m_y1 = 0.; unit->m_y2 = -sin(w) * (endLevel - level); } else { unit->m_a2 = endLevel; unit->m_y1 = level - endLevel; unit->m_y2 = cos(w) * (level - endLevel); } level = unit->m_a2 + unit->m_y1; } break; case shape_Curve: { if (fabs(curve) < 0.001) { unit->m_shape = shape = 1; // shape_Linear unit->m_grow = (endLevel - level) / count; } else { double a1 = (endLevel - level) / (1.0 - exp(curve)); unit->m_a2 = level + a1; unit->m_b1 = a1; unit->m_grow = exp(curve / ceil(count)); } } break; case shape_Squared: { unit->m_y1 = sqrt(level); unit->m_y2 = sqrt(endLevel); unit->m_grow = (unit->m_y2 - unit->m_y1) / count; } break; case shape_Cubed: { unit->m_y1 = pow(level, 0.33333333); unit->m_y2 = pow(endLevel, 0.33333333); unit->m_grow = (unit->m_y2 - unit->m_y1) / count; } break; } } } if (running) { switch (shape) { case shape_Step: { } break; case shape_Linear: { double grow = unit->m_grow; // Print("level %g\n", level); level += grow; } break; case shape_Exponential: { double grow = unit->m_grow; level *= grow; } break; case shape_Sine: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; double y0 = b1 * y1 - y2; level = a2 - y0; y2 = y1; y1 = y0; unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Welch: { double a2 = unit->m_a2; double b1 = unit->m_b1; double y2 = unit->m_y2; double y1 = unit->m_y1; double y0 = b1 * y1 - y2; level = a2 + y0; y2 = y1; y1 = y0; unit->m_y1 = y1; unit->m_y2 = y2; } break; case shape_Curve: { double a2 = unit->m_a2; double b1 = unit->m_b1; double grow = unit->m_grow; b1 *= grow; level = a2 - b1; unit->m_b1 = b1; } break; case shape_Squared: { double grow = unit->m_grow; double y1 = unit->m_y1; y1 += grow; level = y1 * y1; unit->m_y1 = y1; } break; case shape_Cubed: { double grow = unit->m_grow; double y1 = unit->m_y1; y1 += grow; level = y1 * y1 * y1; unit->m_y1 = y1; } break; case shape_Sustain: { } break; } phase--; } ZXP(out) = level; float zgate = ZXP(gate); if (zgate >= 1.f) { unit->m_running = true; } else if (zgate > 0.f) { unit->m_running = true; release = true; // release next time. } else { unit->m_running = false; // sample and hold } } unit->m_level = level; unit->m_curve = curve; unit->m_shape = shape; unit->m_prevreset = prevreset; unit->m_release = release; unit->m_phase = phase; } void DemandEnvGen_Ctor(DemandEnvGen* unit) { // derive the first level. unit->m_level = DEMANDINPUT(d_env_level); if (sc_isnan(unit->m_level)) { unit->m_level = 0.f; } unit->m_endLevel = unit->m_level; unit->m_release = false; unit->m_prevreset = 0.f; unit->m_phase = 0.f; unit->m_running = ZIN0(d_env_gate) > 0.f; if (INRATE(d_env_gate) == calc_FullRate) { SETCALC(DemandEnvGen_next_a); } else { SETCALC(DemandEnvGen_next_k); } DemandEnvGen_next_k(unit, 1); } ///////////////////////////////////////////////////////////////////////////// void TDuty_next_da(TDuty* unit, int inNumSamples) { float* reset = ZIN(duty_reset); float* out = OUT(0); float count = unit->m_count; float prevreset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { float zreset = ZXP(reset); if (zreset > 0.f && prevreset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(2); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); // printf("in %d %g\n", k, x); if (sc_isnan(x)) x = 0.f; out[i] = x; } else { out[i] = 0.f; } count--; prevreset = zreset; } unit->m_count = count; unit->m_prevreset = prevreset; } void TDuty_next_dk(TDuty* unit, int inNumSamples) { float zreset = ZIN0(duty_reset); float* out = OUT(0); float count = unit->m_count; float prevreset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { if (zreset > 0.f && prevreset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(2); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); // printf("in %d %g\n", k, x); if (sc_isnan(x)) x = 0.f; out[i] = x; } else { out[i] = 0.f; } count--; prevreset = zreset; } unit->m_count = count; unit->m_prevreset = prevreset; } void TDuty_next_dd(TDuty* unit, int inNumSamples) { float* out = OUT(0); float count = unit->m_count; float reset = unit->m_prevreset; float sr = (float)SAMPLERATE; for (int i = 0; i < inNumSamples; ++i) { if (reset <= 0.f) { RESETINPUT(duty_level); RESETINPUT(duty_dur); count = 0.f; reset = DEMANDINPUT_A(duty_reset, i + 1) * sr + reset; } else { reset--; } if (count <= 0.f) { count = DEMANDINPUT_A(duty_dur, i + 1) * sr + count; if (sc_isnan(count)) { int doneAction = (int)ZIN0(2); DoneAction(doneAction, unit); } float x = DEMANDINPUT_A(duty_level, i + 1); // printf("in %d %g\n", k, x); if (sc_isnan(x)) x = 0.f; out[i] = x; } else { out[i] = 0.f; } count--; } unit->m_count = count; unit->m_prevreset = reset; } void TDuty_Ctor(TDuty* unit) { // DEMANDINPUT_A is not needed here, because we are at init time. if (INRATE(1) == calc_FullRate) { SETCALC(TDuty_next_da); unit->m_prevreset = 0.f; } else { if (INRATE(1) == calc_DemandRate) { SETCALC(TDuty_next_dd); unit->m_prevreset = DEMANDINPUT(duty_reset) * SAMPLERATE; } else { SETCALC(TDuty_next_dk); unit->m_prevreset = 0.f; } } // support for gap-first. if (IN0(4)) { unit->m_count = DEMANDINPUT(duty_dur) * SAMPLERATE; } else { unit->m_count = 0.f; } OUT0(0) = 0.f; } ///////////////////////////////////////////////////////////////////////////// void Dseries_next(Dseries* unit, int inNumSamples) { if (inNumSamples) { float step = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(step)) { unit->m_step = step; } if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); unit->m_value = DEMANDINPUT_A(1, inNumSamples); } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } OUT0(0) = unit->m_value; unit->m_value += unit->m_step; unit->m_repeatCount++; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Dseries_Ctor(Dseries* unit) { SETCALC(Dseries_next); Dseries_next(unit, 0); OUT0(0) = 0.f; } void Dgeom_next(Dgeom* unit, int inNumSamples) { if (inNumSamples) { float grow = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(grow)) { unit->m_grow = grow; } if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); unit->m_value = DEMANDINPUT_A(1, inNumSamples); } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } OUT0(0) = unit->m_value; unit->m_value *= unit->m_grow; unit->m_repeatCount++; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Dgeom_Ctor(Dgeom* unit) { SETCALC(Dgeom_next); Dgeom_next(unit, 0); OUT0(0) = 0.f; } void Dwhite_next(Dwhite* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } unit->m_repeatCount++; float lo = DEMANDINPUT_A(1, inNumSamples); float hi = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(lo)) { unit->m_lo = lo; } if (!sc_isnan(hi)) { unit->m_range = hi - lo; } float x = unit->mParent->mRGen->frand() * unit->m_range + unit->m_lo; OUT0(0) = x; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Dwhite_Ctor(Dwhite* unit) { SETCALC(Dwhite_next); Dwhite_next(unit, 0); OUT0(0) = 0.f; } void Diwhite_next(Diwhite* unit, int inNumSamples) { if (inNumSamples) { float lo = DEMANDINPUT_A(1, inNumSamples); float hi = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(lo)) { unit->m_lo = (int32)floor(DEMANDINPUT_A(1, inNumSamples) + 0.5f); } if (!sc_isnan(hi)) { int32 hi = (int32)floor(DEMANDINPUT_A(2, inNumSamples) + 0.5f); unit->m_range = hi - unit->m_lo + 1; } if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } unit->m_repeatCount++; float x = unit->mParent->mRGen->irand(unit->m_range) + unit->m_lo; OUT0(0) = x; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Diwhite_Ctor(Diwhite* unit) { SETCALC(Diwhite_next); Diwhite_next(unit, 0); OUT0(0) = 0.f; } void Dbrown_next(Dbrown* unit, int inNumSamples) { if (inNumSamples) { float lo = DEMANDINPUT_A(1, inNumSamples); if (!sc_isnan(lo)) { unit->m_lo = lo; } float hi = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(hi)) { unit->m_hi = hi; } float step = DEMANDINPUT_A(3, inNumSamples); if (!sc_isnan(step)) { unit->m_step = step; } if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); unit->m_val = unit->mParent->mRGen->frand() * (unit->m_hi - unit->m_lo) + unit->m_lo; } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } unit->m_repeatCount++; OUT0(0) = unit->m_val; float x = unit->m_val + unit->mParent->mRGen->frand2() * unit->m_step; unit->m_val = sc_fold(x, unit->m_lo, unit->m_hi); } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Dbrown_Ctor(Dbrown* unit) { SETCALC(Dbrown_next); Dbrown_next(unit, 0); OUT0(0) = 0.f; } void Dibrown_next(Dibrown* unit, int inNumSamples) { if (inNumSamples) { float lo = DEMANDINPUT_A(1, inNumSamples); if (!sc_isnan(lo)) { unit->m_lo = (int32)lo; } float hi = DEMANDINPUT_A(2, inNumSamples); if (!sc_isnan(hi)) { unit->m_hi = (int32)hi; } float step = DEMANDINPUT_A(3, inNumSamples); if (!sc_isnan(step)) { unit->m_step = (int32)step; } if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); unit->m_val = unit->mParent->mRGen->irand(unit->m_hi - unit->m_lo + 1) + unit->m_lo; } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } unit->m_repeatCount++; OUT0(0) = unit->m_val; int32 z = unit->m_val + unit->mParent->mRGen->irand2(unit->m_step); unit->m_val = sc_fold(z, unit->m_lo, unit->m_hi); } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; } } void Dibrown_Ctor(Dibrown* unit) { SETCALC(Dibrown_next); Dibrown_next(unit, 0); OUT0(0) = 0.f; } void Dseq_next(Dseq* unit, int inNumSamples) { // Print("->Dseq_next %d\n", inNumSamples); if (inNumSamples) { // Print(" unit->m_repeats %d\n", unit->m_repeats); if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } int attempts = 0; while (true) { // Print(" unit->m_index %d unit->m_repeatCount %d\n", unit->m_index, unit->m_repeatCount); if (unit->m_index >= unit->mNumInputs) { unit->m_index = 1; unit->m_repeatCount++; } if (unit->m_repeatCount >= unit->m_repeats) { // Print("done\n"); OUT0(0) = NAN; unit->m_index = 1; return; } if (ISDEMANDINPUT(unit->m_index)) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_index); } float x = DEMANDINPUT_A(unit->m_index, inNumSamples); if (sc_isnan(x)) { unit->m_index++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = DEMANDINPUT_A(unit->m_index, inNumSamples); // Print(" unit->m_index %d OUT0(0) %g\n", unit->m_index, OUT0(0)); unit->m_index++; unit->m_needToResetChild = true; return; } if (attempts++ > unit->mNumInputs) { Print("Warning: empty sequence in Dseq\n"); return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; unit->m_index = 1; } } void Dseq_Ctor(Dseq* unit) { SETCALC(Dseq_next); Dseq_next(unit, 0); OUT0(0) = 0.f; } void Dser_next(Dser* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } while (true) { if (unit->m_index >= unit->mNumInputs) { unit->m_index = 1; } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } if (ISDEMANDINPUT(unit->m_index)) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_index); } float x = DEMANDINPUT_A(unit->m_index, inNumSamples); if (sc_isnan(x)) { unit->m_index++; unit->m_repeatCount++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = IN0(unit->m_index); unit->m_index++; unit->m_repeatCount++; unit->m_needToResetChild = true; return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; unit->m_index = 1; } } void Dser_Ctor(Dser* unit) { SETCALC(Dser_next); Dser_next(unit, 0); OUT0(0) = 0.f; } void Drand_next(Drand* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } while (true) { if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } if (ISDEMANDINPUT(unit->m_index)) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_index); } float x = DEMANDINPUT_A(unit->m_index, inNumSamples); if (sc_isnan(x)) { unit->m_index = unit->mParent->mRGen->irand(unit->mNumInputs - 1) + 1; unit->m_repeatCount++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = DEMANDINPUT_A(unit->m_index, inNumSamples); unit->m_index = unit->mParent->mRGen->irand(unit->mNumInputs - 1) + 1; unit->m_repeatCount++; unit->m_needToResetChild = true; return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; unit->m_index = unit->mParent->mRGen->irand(unit->mNumInputs - 1) + 1; } } void Drand_Ctor(Drand* unit) { SETCALC(Drand_next); Drand_next(unit, 0); OUT0(0) = 0.f; } void Dxrand_next(Dxrand* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } while (true) { if (unit->m_index >= unit->mNumInputs) { unit->m_index = 1; } if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } if (ISDEMANDINPUT(unit->m_index)) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_index); } float x = DEMANDINPUT_A(unit->m_index, inNumSamples); if (sc_isnan(x)) { int newindex = unit->mParent->mRGen->irand(unit->mNumInputs - 2) + 1; unit->m_index = newindex < unit->m_index ? newindex : newindex + 1; unit->m_repeatCount++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = DEMANDINPUT_A(unit->m_index, inNumSamples); int newindex = unit->mParent->mRGen->irand(unit->mNumInputs - 2) + 1; unit->m_index = newindex < unit->m_index ? newindex : newindex + 1; unit->m_repeatCount++; unit->m_needToResetChild = true; return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; int newindex = unit->mParent->mRGen->irand(unit->mNumInputs - 2) + 1; unit->m_index = newindex < unit->m_index ? newindex : newindex + 1; } } void Dxrand_Ctor(Dxrand* unit) { SETCALC(Dxrand_next); Dxrand_next(unit, 0); OUT0(0) = 0.f; } #define WINDEX \ float w, sum = 0.0; \ float r = unit->mParent->mRGen->frand(); \ for (int i = 0; i < weights_size; ++i) { \ w = IN0(2 + i); \ sum += w; \ if (sum >= r) { \ unit->m_index = i + offset; \ break; \ } \ } void Dwrand_next(Dwrand* unit, int inNumSamples) { int offset = unit->m_weights_size + 2; int weights_size = unit->mNumInputs - offset; if (inNumSamples) { if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } while (true) { if (unit->m_repeatCount >= unit->m_repeats) { OUT0(0) = NAN; return; } if (ISDEMANDINPUT(unit->m_index)) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_index); } float x = DEMANDINPUT_A(unit->m_index, inNumSamples); if (sc_isnan(x)) { WINDEX; unit->m_repeatCount++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = DEMANDINPUT_A(unit->m_index, inNumSamples); WINDEX; unit->m_repeatCount++; unit->m_needToResetChild = true; return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; WINDEX; } } void Dwrand_Ctor(Dwrand* unit) { SETCALC(Dwrand_next); unit->m_weights_size = IN0(1); Dwrand_next(unit, 0); OUT0(0) = 0.f; } static void Dshuf_scramble(Dshuf* unit); void Dshuf_next(Dshuf* unit, int inNumSamples) { // Print("->Dshuf_next %d\n", inNumSamples); if (inNumSamples) { // Print(" unit->m_repeats %d\n", unit->m_repeats); if (unit->m_repeats < 0.) { float x = DEMANDINPUT_A(0, inNumSamples); unit->m_repeats = sc_isnan(x) ? 0.f : floor(x + 0.5f); } while (true) { // Print(" unit->m_index %d unit->m_repeatCount %d\n", unit->m_index, unit->m_repeatCount); if (unit->m_index >= (unit->mNumInputs - 1)) { unit->m_index = 0; unit->m_repeatCount++; } if (unit->m_repeatCount >= unit->m_repeats) { // Print("done\n"); OUT0(0) = NAN; unit->m_index = 0; return; } if (ISDEMANDINPUT(unit->m_indices[unit->m_index])) { if (unit->m_needToResetChild) { unit->m_needToResetChild = false; RESETINPUT(unit->m_indices[unit->m_index]); } float x = DEMANDINPUT_A(unit->m_indices[unit->m_index], inNumSamples); if (sc_isnan(x)) { unit->m_index++; unit->m_needToResetChild = true; } else { OUT0(0) = x; return; } } else { OUT0(0) = DEMANDINPUT_A(unit->m_indices[unit->m_index], inNumSamples); // Print(" unit->m_index %d OUT0(0) %g\n", unit->m_index, OUT0(0)); unit->m_index++; unit->m_needToResetChild = true; return; } } } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0; unit->m_needToResetChild = true; unit->m_index = 0; Dshuf_scramble(unit); } } void Dshuf_scramble(Dshuf* unit) { int32 i, j, m, k, size; int32 temp; size = (int32)(unit->mNumInputs) - 1; if (size > 1) { k = size; for (i = 0, m = k; i < k - 1; ++i, --m) { j = i + unit->mParent->mRGen->irand(m); temp = unit->m_indices[i]; unit->m_indices[i] = unit->m_indices[j]; unit->m_indices[j] = temp; } } } void Dshuf_Ctor(Dshuf* unit) { OUT0(0) = 0.f; uint32 size = (unit->mNumInputs) - 1; unit->m_indices = (int32*)RTAlloc(unit->mWorld, size * sizeof(int32)); ClearUnitIfMemFailed(unit->m_indices); for (uint32 i = 0; i < size; ++i) unit->m_indices[i] = i + 1; SETCALC(Dshuf_next); Dshuf_next(unit, 0); } void Dshuf_Dtor(Dshuf* unit) { RTFree(unit->mWorld, unit->m_indices); } void Dswitch1_next(Dswitch1* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); if (sc_isnan(x)) { OUT0(0) = x; return; } int index = (int32)floor(x + 0.5f); index = sc_wrap(index, 0, unit->mNumInputs - 2) + 1; OUT0(0) = DEMANDINPUT_A(index, inNumSamples); } else { for (int i = 0; i < unit->mNumInputs; ++i) { RESETINPUT(i); } } } void Dswitch1_Ctor(Dswitch1* unit) { SETCALC(Dswitch1_next); OUT0(0) = 0.f; } ///////////////////////////// void Dswitch_next(Dswitch* unit, int inNumSamples) { if (inNumSamples) { float val = DEMANDINPUT_A(unit->m_index, inNumSamples); // printf("index: %i\n", (int) val); if (sc_isnan(val)) { float ival = DEMANDINPUT_A(0, inNumSamples); if (sc_isnan(ival)) val = ival; else { int index = (int32)floor(ival + 0.5f); index = sc_wrap(index, 0, unit->mNumInputs - 2) + 1; val = DEMANDINPUT_A(index, inNumSamples); RESETINPUT(unit->m_index); // printf("resetting index: %i\n", unit->m_index); unit->m_index = index; } } OUT0(0) = val; } else { printf("...\n"); for (int i = 0; i < unit->mNumInputs; ++i) { RESETINPUT(i); } int index = (int32)floor(DEMANDINPUT(0) + 0.5f); index = sc_wrap(index, 0, unit->mNumInputs - 1) + 1; unit->m_index = index; } } void Dswitch_Ctor(Dswitch* unit) { SETCALC(Dswitch_next); int index = (int32)floor(DEMANDINPUT(0) + 0.5f); index = sc_wrap(index, 0, unit->mNumInputs - 1) + 1; unit->m_index = index; OUT0(0) = 0.f; } ////////////////////////////// void Dstutter_next(Dstutter* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeatCount >= unit->m_repeats) { float val = DEMANDINPUT_A(1, inNumSamples); float repeats = DEMANDINPUT_A(0, inNumSamples); if (sc_isnan(repeats) || sc_isnan(val)) { OUT0(0) = NAN; return; } else { unit->m_value = val; unit->m_repeats = floor(repeats + 0.5f); unit->m_repeatCount = 0.f; } } OUT0(0) = unit->m_value; unit->m_repeatCount++; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0.f; RESETINPUT(0); RESETINPUT(1); } } void Dstutter_Ctor(Dstutter* unit) { SETCALC(Dstutter_next); Dstutter_next(unit, 0); OUT0(0) = 0.f; } void Ddup_next(Ddup* unit, int inNumSamples) { if (inNumSamples) { if (unit->m_repeatCount >= unit->m_repeats) { float val = DEMANDINPUT_A(1, inNumSamples); float repeats = DEMANDINPUT_A(0, inNumSamples); if (sc_isnan(repeats) || sc_isnan(val)) { OUT0(0) = NAN; return; } else { unit->m_value = val; unit->m_repeats = floor(repeats + 0.5f); unit->m_repeatCount = 0.f; } } OUT0(0) = unit->m_value; unit->m_repeatCount++; } else { unit->m_repeats = -1.f; unit->m_repeatCount = 0.f; RESETINPUT(0); RESETINPUT(1); } } void Ddup_Ctor(Ddup* unit) { SETCALC(Ddup_next); Ddup_next(unit, 0); OUT0(0) = 0.f; } ////////////////////////////// void Dconst_next(Dconst* unit, int inNumSamples) { float total, tolerance; if (inNumSamples) { if (sc_isnan(unit->m_runningsum)) { OUT0(0) = NAN; return; } if (unit->m_total < 0.f) { total = DEMANDINPUT_A(0, inNumSamples); tolerance = DEMANDINPUT_A(2, inNumSamples); if (sc_isnan(total) || sc_isnan(tolerance)) { OUT0(0) = NAN; return; } unit->m_total = total; unit->m_tolerance = tolerance; } { total = unit->m_total; tolerance = unit->m_tolerance; } float val = DEMANDINPUT_A(1, inNumSamples); if (sc_isnan(val)) { OUT0(0) = NAN; return; } else { float runningsum = unit->m_runningsum + val; if ((runningsum > total) || (fabs(total - runningsum) <= tolerance)) { OUT0(0) = total - unit->m_runningsum; unit->m_runningsum = NAN; // stop next time } else { unit->m_runningsum = runningsum; OUT0(0) = val; } } } else { unit->m_total = -1.f; unit->m_runningsum = 0.f; RESETINPUT(0); RESETINPUT(1); RESETINPUT(2); } } void Dconst_Ctor(Dconst* unit) { SETCALC(Dconst_next); Dconst_next(unit, 0); OUT0(0) = 0.f; } ////////////////////////////// void Dpoll_next(Dpoll* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); float run = DEMANDINPUT_A(2, inNumSamples) > 0.f; if (unit->m_mayprint && run) { Print("%s: %g block offset: %d\n", unit->m_id_string, x, inNumSamples - 1); } if (IN0(1) >= 0.0) SendTrigger(&unit->mParent->mNode, (int)IN0(1), x); OUT0(0) = x; } else { RESETINPUT(0); } } void Dpoll_Ctor(Dpoll* unit) { OUT0(0) = 0.f; const int idStringSize = (int)IN0(3); unit->m_id_string = (char*)RTAlloc(unit->mWorld, (idStringSize + 1) * sizeof(char)); ClearUnitIfMemFailed(unit->m_id_string); for (int i = 0; i < idStringSize; i++) unit->m_id_string[i] = (char)IN0(4 + i); SETCALC(Dpoll_next); unit->m_id_string[idStringSize] = '\0'; unit->m_mayprint = unit->mWorld->mVerbosity >= -1; OUT0(0) = 0.f; } void Dpoll_Dtor(Dpoll* unit) { RTFree(unit->mWorld, unit->m_id_string); } ////////////////////////////// void Dreset_next(Dreset* unit, int inNumSamples) { if (inNumSamples) { float x = DEMANDINPUT_A(0, inNumSamples); float reset = DEMANDINPUT_A(1, inNumSamples); if (sc_isnan(x)) { OUT0(0) = NAN; return; } if (reset > 0.0 && (unit->prev_reset <= 0.0)) { RESETINPUT(0); } unit->prev_reset = reset; OUT0(0) = x; } else { RESETINPUT(0); } } void Dreset_Ctor(Dreset* unit) { SETCALC(Dreset_next); unit->prev_reset = 0.0; Dreset_next(unit, 0); } ////////////////////////////// inline double sc_loop(Unit* unit, double in, double hi, int loop) { // avoid the divide if possible if (in >= hi) { if (!loop) { unit->mDone = true; return hi; } in -= hi; if (in < hi) return in; } else if (in < 0.) { if (!loop) { unit->mDone = true; return 0.; } in += hi; if (in >= 0.) return in; } else return in; return in - hi * floor(in / hi); } #define D_CHECK_BUF \ if (!bufData) { \ unit->mDone = true; \ ClearUnitOutputs(unit, 1); \ return; \ } #define D_GET_BUF \ float fbufnum = DEMANDINPUT_A(0, inNumSamples); \ ; \ if (sc_isnan(fbufnum)) { \ OUT0(0) = NAN; \ return; \ } \ fbufnum = sc_max(0.f, fbufnum); \ if (fbufnum != unit->m_fbufnum) { \ int bufnum = (int)fbufnum; \ World* world = unit->mWorld; \ if (bufnum < 0) { \ bufnum = 0; \ } \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ unit->m_buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ unit->m_buf = world->mSndBufs + bufnum; \ } \ } else { \ unit->m_buf = world->mSndBufs + bufnum; \ } \ unit->m_fbufnum = fbufnum; \ } \ SndBuf* buf = unit->m_buf; \ LOCK_SNDBUF(buf); \ float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples __attribute__((__unused__)) = buf->samples; \ uint32 bufFrames = buf->frames; \ int mask __attribute__((__unused__)) = buf->mask; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; #define D_GET_BUF_SHARED \ float fbufnum = DEMANDINPUT_A(0, inNumSamples); \ ; \ if (sc_isnan(fbufnum)) { \ OUT0(0) = NAN; \ return; \ } \ fbufnum = sc_max(0.f, fbufnum); \ if (fbufnum != unit->m_fbufnum) { \ int bufnum = (int)fbufnum; \ World* world = unit->mWorld; \ if (bufnum < 0) { \ bufnum = 0; \ } \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph* parent = unit->mParent; \ if (localBufNum <= parent->localBufNum) { \ unit->m_buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ unit->m_buf = world->mSndBufs + bufnum; \ } \ } else { \ unit->m_buf = world->mSndBufs + bufnum; \ } \ unit->m_fbufnum = fbufnum; \ } \ const SndBuf* buf = unit->m_buf; \ LOCK_SNDBUF_SHARED(buf); \ const float* bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples __attribute__((__unused__)) = buf->samples; \ uint32 bufFrames = buf->frames; \ int mask __attribute__((__unused__)) = buf->mask; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; void Dbufrd_next(Dbufrd* unit, int inNumSamples) { int32 loop = (int32)DEMANDINPUT_A(2, inNumSamples); D_GET_BUF_SHARED D_CHECK_BUF double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase; if (inNumSamples) { float x = DEMANDINPUT_A(1, inNumSamples); if (sc_isnan(x)) { OUT0(0) = NAN; return; } phase = x; phase = sc_loop((Unit*)unit, phase, loopMax, loop); int32 iphase = (int32)phase; const float* table1 = bufData + iphase * bufChannels; OUT0(0) = table1[0]; } else { RESETINPUT(1); } } void Dbufrd_Ctor(Dbufrd* unit) { SETCALC(Dbufrd_next); unit->m_fbufnum = -1e9f; Dbufrd_next(unit, 0); OUT0(0) = 0.f; } //////////////////////////////////// void Dbufwr_next(Dbufwr* unit, int inNumSamples) { int32 loop = (int32)DEMANDINPUT_A(3, inNumSamples); D_GET_BUF D_CHECK_BUF double loopMax = (double)(loop ? bufFrames : bufFrames - 1); double phase; float val; if (inNumSamples) { float x = DEMANDINPUT_A(1, inNumSamples); if (sc_isnan(x)) { OUT0(0) = NAN; return; } phase = x; val = DEMANDINPUT_A(2, inNumSamples); if (sc_isnan(val)) { OUT0(0) = NAN; return; } phase = sc_loop((Unit*)unit, phase, loopMax, loop); int32 iphase = (int32)phase; float* table0 = bufData + iphase * bufChannels; table0[0] = val; OUT0(0) = val; } else { RESETINPUT(1); RESETINPUT(2); } } void Dbufwr_Ctor(Dbufwr* unit) { SETCALC(Dbufwr_next); unit->m_fbufnum = -1e9f; Dbufwr_next(unit, 0); OUT0(0) = 0.f; } ////////////////////////////////////////////////////// PluginLoad(Demand) { ft = inTable; DefineDtorCantAliasUnit(Demand); DefineSimpleCantAliasUnit(Duty); DefineSimpleCantAliasUnit(DemandEnvGen); DefineSimpleCantAliasUnit(TDuty); DefineSimpleUnit(Dseries); DefineSimpleUnit(Dgeom); DefineSimpleUnit(Dwhite); DefineSimpleUnit(Dbrown); DefineSimpleUnit(Diwhite); DefineSimpleUnit(Dibrown); DefineSimpleUnit(Dseq); DefineSimpleUnit(Dser); DefineSimpleUnit(Dbufrd); DefineSimpleUnit(Dbufwr); DefineSimpleUnit(Drand); DefineSimpleUnit(Dwrand); DefineSimpleUnit(Dxrand); DefineDtorUnit(Dshuf); DefineSimpleUnit(Dswitch1); DefineSimpleUnit(Dswitch); DefineSimpleUnit(Dstutter); DefineSimpleUnit(Ddup); DefineSimpleUnit(Dconst); DefineSimpleUnit(Dreset); DefineDtorUnit(Dpoll); }
74,496
C++
.cpp
2,012
26.87674
120
0.438127
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
29,950
Convolution.cpp
supercollider_supercollider/server/plugins/Convolution.cpp
/* 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 */ // Convolution by nick collins for sc3 (later input from Marije as below, Dan Stowell and Nick worked on sc_fft // compatibility late 2008) see ch18 http://www.dspguide.com/ch18.htm Steven W Smith // Convolution2 adapted by marije baalman for triggered kernel swap, with help from alberto de campo // Convolution2L (with linear crossfade) by marije baalman // Convolution3 (time-based) by marije baalman #include "FFT_UGens.h" //#include "SC_fftlib.h" #include <stdio.h> struct Convolution : Unit { int m_pos, m_framesize, m_fftsize; float *m_inbuf1, *m_inbuf2, *m_fftbuf1, *m_fftbuf2, *m_outbuf, *m_overlapbuf; scfft *m_scfft1, *m_scfft2, *m_scfftR; }; struct Convolution2 : Unit { int m_pos, m_framesize, m_fftsize; float m_prevtrig; float *m_inbuf1, *m_fftbuf1, *m_fftbuf2, *m_outbuf, *m_overlapbuf; scfft *m_scfft1, *m_scfft2, *m_scfftR; }; struct Convolution2L : Unit { int m_pos, m_framesize, m_fftsize; int m_cfpos, m_cflength, m_curbuf; // for crossfading int m_log2n; float m_prevtrig; float *m_inbuf1, *m_fftbuf1, *m_fftbuf2, *m_outbuf, *m_overlapbuf; float *m_tempbuf, *m_fftbuf3; // for crossfading scfft *m_scfft1, *m_scfft2, *m_scfft3, *m_scfftR, *m_scfftR2; // source plus two kernels forwards, and two inverse from outbuf and from tempbuf }; // could be done also using complex signal fft and appropriate unwrapping, but sc_fft doesn't support that struct StereoConvolution2L : Unit { int m_pos, m_framesize, m_fftsize; int m_cfpos, m_cflength, m_curbuf; // for crossfading int m_log2n; float m_prevtrig; float *m_inbuf1, *m_fftbuf1; // input float *m_fftbuf2[2], *m_outbuf[2], *m_overlapbuf[2]; // output float *m_tempbuf[2], *m_fftbuf3[2]; // for crossfading scfft *m_scfft1, *m_scfft2[2], *m_scfft3[2], *m_scfftR[2], *m_scfftR2[2]; }; struct Convolution3 : Unit { int m_pos, m_framesize; float m_prevtrig; float *m_inbuf1, *m_inbuf2, *m_outbuf; }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void Convolution_next(Convolution* unit, int wrongNumSamples); void Convolution_Ctor(Convolution* unit); void Convolution_Dtor(Convolution* unit); void Convolution2_next(Convolution2* unit, int wrongNumSamples); void Convolution2_Ctor(Convolution2* unit); void Convolution2_Dtor(Convolution2* unit); void Convolution2L_next(Convolution2L* unit, int wrongNumSamples); void Convolution2L_Ctor(Convolution2L* unit); void Convolution2L_Dtor(Convolution2L* unit); void StereoConvolution2L_next(StereoConvolution2L* unit, int wrongNumSamples); void StereoConvolution2L_Ctor(StereoConvolution2L* unit); void StereoConvolution2L_Dtor(StereoConvolution2L* unit); void Convolution3_next_a(Convolution3* unit); void Convolution3_next_k(Convolution3* unit); void Convolution3_Ctor(Convolution3* unit); void Convolution3_Dtor(Convolution3* unit); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // PROPER CONVOLVER // two possibilities- fixed kernel (in which case can derive the kernel spectrum in the constructor) // and changing kernel (same size as target) void Convolution_Ctor(Convolution* unit) { // require size N+M-1 to be a power of two unit->m_framesize = (int)ZIN0(2); unit->m_fftsize = 2 * (unit->m_framesize); // just use memory for the input buffers and fft buffers int framesize_f = unit->m_framesize * sizeof(float); int fftsize_f = unit->m_fftsize * sizeof(float); unit->m_scfft1 = unit->m_scfft2 = unit->m_scfftR = nullptr; unit->m_inbuf1 = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_inbuf2 = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_fftbuf1 = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf2 = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_outbuf = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_overlapbuf = (float*)RTAlloc(unit->mWorld, framesize_f); ClearUnitIfMemFailed(unit->m_inbuf1 && unit->m_inbuf2 && unit->m_fftbuf1 && unit->m_fftbuf2 && unit->m_outbuf && unit->m_overlapbuf); memset(unit->m_outbuf, 0, fftsize_f); memset(unit->m_overlapbuf, 0, framesize_f); unit->m_pos = 0; SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft1 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_fftbuf1, kForward, alloc); unit->m_scfft2 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf2, unit->m_fftbuf2, kForward, alloc); unit->m_scfftR = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_outbuf, kBackward, alloc); ClearUnitIfMemFailed(unit->m_scfft1 && unit->m_scfft2 && unit->m_scfftR); SETCALC(Convolution_next); // initialize output OUT0(0) = IN0(0); } void Convolution_Dtor(Convolution* unit) { RTFree(unit->mWorld, unit->m_inbuf1); RTFree(unit->mWorld, unit->m_inbuf2); RTFree(unit->mWorld, unit->m_fftbuf1); RTFree(unit->mWorld, unit->m_fftbuf2); RTFree(unit->mWorld, unit->m_outbuf); RTFree(unit->mWorld, unit->m_overlapbuf); SCWorld_Allocator alloc(ft, unit->mWorld); scfft_destroy(unit->m_scfft1, alloc); scfft_destroy(unit->m_scfft2, alloc); scfft_destroy(unit->m_scfftR, alloc); } void Convolution_next(Convolution* unit, int numSamples) { float* in1 = IN(0); float* in2 = IN(1); float* out1 = unit->m_inbuf1 + unit->m_pos; float* out2 = unit->m_inbuf2 + unit->m_pos; // int numSamples = unit->mWorld->mFullRate.mBufLength; // copy input Copy(numSamples, out1, in1); Copy(numSamples, out2, in2); unit->m_pos += numSamples; int framesize = unit->m_framesize; if (unit->m_pos & framesize) { // have collected enough samples to transform next frame unit->m_pos = 0; // reset collection counter int memsize = framesize * sizeof(float); // copy to fftbuf memcpy(unit->m_fftbuf1, unit->m_inbuf1, memsize); memcpy(unit->m_fftbuf2, unit->m_inbuf2, memsize); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf1 + unit->m_framesize, 0, memsize); memset(unit->m_fftbuf2 + unit->m_framesize, 0, memsize); // do fft // in place transform for now scfft_dofft(unit->m_scfft1); scfft_dofft(unit->m_scfft2); // complex multiply time float* p1 = unit->m_fftbuf1; float* p2 = unit->m_fftbuf2; p1[0] *= p2[0]; p1[1] *= p2[1]; // complex multiply for (int i = 1; i < framesize; ++i) { float real, imag; int realind, imagind; realind = 2 * i; imagind = realind + 1; real = p1[realind] * p2[realind] - p1[imagind] * p2[imagind]; imag = p1[realind] * p2[imagind] + p1[imagind] * p2[realind]; p1[realind] = real; p1[imagind] = imag; } // copy second part from before to overlap memcpy(unit->m_overlapbuf, unit->m_outbuf + unit->m_framesize, memsize); // inverse fft into outbuf memcpy(unit->m_outbuf, unit->m_fftbuf1, unit->m_fftsize * sizeof(float)); // in place scfft_doifft(unit->m_scfftR); } // write out samples copied from outbuf, with overlap added in float* output = ZOUT(0); float* out = unit->m_outbuf + unit->m_pos; float* overlap = unit->m_overlapbuf + unit->m_pos; for (int i = 0; i < numSamples; ++i) ZXP(output) = out[i] + overlap[i]; } // include local buffer test in one place static SndBuf* ConvGetBuffer(Unit* unit, uint32 bufnum, const char* ugenName, int inNumSamples) { SndBuf* buf; World* world = unit->mWorld; if (bufnum >= world->mNumSndBufs) { int localBufNum = bufnum - world->mNumSndBufs; Graph* parent = unit->mParent; if (localBufNum <= parent->localMaxBufNum) { buf = parent->mLocalSndBufs + localBufNum; } else { if (unit->mWorld->mVerbosity > -1) Print("%s: invalid buffer number (%d).\n", ugenName, bufnum); goto handle_failure; } } else { buf = world->mSndBufs + bufnum; } if (buf->data == nullptr) { if (unit->mWorld->mVerbosity > -1) Print("%s: uninitialized buffer (%i).\n", ugenName, bufnum); goto handle_failure; } return buf; handle_failure: SETCALC(*ClearUnitOutputs); ClearUnitOutputs(unit, inNumSamples); unit->mDone = true; return nullptr; } void Convolution2_Ctor(Convolution2* unit) { // require size N+M-1 to be a power of two unit->m_framesize = (int)ZIN0(3); uint32 kernelbufnum = (int)ZIN0(1); World* world = unit->mWorld; unit->m_inbuf1 = unit->m_fftbuf1 = unit->m_fftbuf2 = unit->m_outbuf = unit->m_overlapbuf = nullptr; unit->m_scfft1 = unit->m_scfft2 = unit->m_scfftR = nullptr; SndBuf* kernelbuf = ConvGetBuffer(unit, kernelbufnum, "Convolution2", 1); if (kernelbuf) { if (unit->m_framesize <= 0) { // if smaller than zero, we use the size of the buffer unit->m_framesize = kernelbuf->frames; } unit->m_fftsize = 2 * (unit->m_framesize); if (unit->m_fftsize > SC_FFT_ABSOLUTE_MAXSIZE) { printf("Convolution2: FFT size is larger than SC_FFT_ABSOLUTE_MAXSIZE, cannot run. We suggest PartConv " "instead.\n"); SETCALC(*ClearUnitOutputs); } // allocate memory internally for the input buffers and fft buffers int framesize_f = unit->m_framesize * sizeof(float); int fftsize_f = unit->m_fftsize * sizeof(float); unit->m_inbuf1 = (float*)RTAlloc(world, framesize_f); unit->m_fftbuf1 = (float*)RTAlloc(world, fftsize_f); unit->m_fftbuf2 = (float*)RTAlloc(world, fftsize_f); unit->m_outbuf = (float*)RTAlloc(world, fftsize_f); unit->m_overlapbuf = (float*)RTAlloc(world, framesize_f); ClearUnitIfMemFailed(unit->m_inbuf1 && unit->m_fftbuf1 && unit->m_fftbuf2 && unit->m_outbuf && unit->m_overlapbuf); memset(unit->m_outbuf, 0, fftsize_f); memset(unit->m_overlapbuf, 0, framesize_f); unit->m_pos = 0; SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft1 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_fftbuf1, kForward, alloc); unit->m_scfft2 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf2, unit->m_fftbuf2, kForward, alloc); unit->m_scfftR = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_outbuf, kBackward, alloc); ClearUnitIfMemFailed(unit->m_scfft1 && unit->m_scfft2 && unit->m_scfftR); // calculate fft for kernel straight away // we cannot use a kernel larger than the fft size, so truncate if needed. the kernel may be smaller though. uint32 framesize = unit->m_framesize; size_t kernelcopysize = sc_min(kernelbuf->frames, framesize); memcpy(unit->m_fftbuf2, kernelbuf->data, kernelcopysize * sizeof(float)); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf2 + kernelcopysize, 0, (2 * framesize - kernelcopysize) * sizeof(float)); scfft_dofft(unit->m_scfft2); unit->m_pos = 0; unit->m_prevtrig = 0.f; if (unit->m_framesize >= world->mFullRate.mBufLength) { SETCALC(Convolution2_next); // initialize output OUT0(0) = IN0(0); } else { printf("Convolution2 framesize smaller than blocksize \n"); SETCALC(*ClearUnitOutputs); unit->mDone = true; } } else { unit->m_scfft2 = unit->m_scfft1 = unit->m_scfftR = nullptr; printf("Convolution2_Ctor: can't get kernel buffer, giving up.\n"); SETCALC(*ClearUnitOutputs); } } void Convolution2_Dtor(Convolution2* unit) { RTFree(unit->mWorld, unit->m_inbuf1); RTFree(unit->mWorld, unit->m_fftbuf1); RTFree(unit->mWorld, unit->m_fftbuf2); RTFree(unit->mWorld, unit->m_outbuf); RTFree(unit->mWorld, unit->m_overlapbuf); SCWorld_Allocator alloc(ft, unit->mWorld); scfft_destroy(unit->m_scfft1, alloc); scfft_destroy(unit->m_scfft2, alloc); scfft_destroy(unit->m_scfftR, alloc); } void Convolution2_next(Convolution2* unit, int wrongNumSamples) { float* in1 = IN(0); float curtrig = ZIN0(2); float* inbuf1writepos = unit->m_inbuf1 + unit->m_pos; int numSamples = unit->mWorld->mFullRate.mBufLength; uint32 framesize = unit->m_framesize; uint32 framesize_f = framesize * sizeof(float); // copy input Copy(numSamples, inbuf1writepos, in1); unit->m_pos += numSamples; if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { SndBuf* kernelbuf = ConvGetBuffer(unit, (uint32)ZIN0(1), "Convolution2", numSamples); if (!kernelbuf) return; LOCK_SNDBUF_SHARED(kernelbuf); // we cannot use a kernel larger than the fft size, so truncate if needed. the kernel may be smaller though. size_t kernelcopysize = sc_min(kernelbuf->frames, framesize); memcpy(unit->m_fftbuf2, kernelbuf->data, kernelcopysize * sizeof(float)); memset(unit->m_fftbuf2 + kernelcopysize, 0, (2 * framesize - kernelcopysize) * sizeof(float)); scfft_dofft(unit->m_scfft2); } if (unit->m_pos >= framesize) { // have collected enough samples to transform next frame unit->m_pos = 0; // reset collection counter // copy to fftbuf memcpy(unit->m_fftbuf1, unit->m_inbuf1, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf1 + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft1); // complex multiply time int numbins = unit->m_fftsize >> 1; float* p1 = unit->m_fftbuf1; float* p2 = unit->m_fftbuf2; p1[0] *= p2[0]; p1[1] *= p2[1]; // complex multiply for (int i = 1; i < numbins; ++i) { float real, imag; int realind, imagind; realind = 2 * i; imagind = realind + 1; real = p1[realind] * p2[realind] - p1[imagind] * p2[imagind]; imag = p1[realind] * p2[imagind] + p1[imagind] * p2[realind]; p1[realind] = real; p1[imagind] = imag; } // copy second part from before to overlap memcpy(unit->m_overlapbuf, unit->m_outbuf + unit->m_framesize, framesize_f); // inverse fft into outbuf scfft_doifft(unit->m_scfftR); } // write out samples copied from outbuf, with overlap added in float* output = ZOUT(0); float* out = unit->m_outbuf + unit->m_pos; float* overlap = unit->m_overlapbuf + unit->m_pos; unit->m_prevtrig = curtrig; for (int i = 0; i < numSamples; ++i) ZXP(output) = out[i] + overlap[i]; } void Convolution2L_Ctor(Convolution2L* unit) { // require size N+M-1 to be a power of two unit->m_framesize = (int)ZIN0(3); unit->m_cflength = (int)ZIN0(4); unit->m_curbuf = 0; unit->m_cfpos = unit->m_cflength; unit->m_fftsize = 2 * (unit->m_framesize); // just use memory for the input buffers and fft buffers int framesize_f = unit->m_framesize * sizeof(float); int fftsize_f = unit->m_fftsize * sizeof(float); unit->m_inbuf1 = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_fftbuf1 = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf2 = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf3 = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_tempbuf = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_outbuf = unit->m_overlapbuf = nullptr; unit->m_scfft1 = unit->m_scfft2 = unit->m_scfft3 = nullptr; unit->m_scfftR = unit->m_scfftR2 = nullptr; ClearUnitIfMemFailed(unit->m_inbuf1 && unit->m_fftbuf1 && unit->m_fftbuf2 && unit->m_fftbuf3 && unit->m_tempbuf); uint32 bufnum = (int)ZIN0(1); // fbufnum; SndBuf* buf = ConvGetBuffer(unit, bufnum, "Convolution2L", 1); if (buf) { unit->m_outbuf = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_overlapbuf = (float*)RTAlloc(unit->mWorld, framesize_f); ClearUnitIfMemFailed(unit->m_outbuf && unit->m_overlapbuf); memset(unit->m_outbuf, 0, fftsize_f); memset(unit->m_overlapbuf, 0, framesize_f); // calculate fft for kernel straight away memcpy(unit->m_fftbuf2, buf->data, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf2 + unit->m_framesize, 0, framesize_f); SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft1 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_fftbuf1, kForward, alloc); unit->m_scfft2 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf2, unit->m_fftbuf2, kForward, alloc); unit->m_scfft3 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf3, unit->m_fftbuf3, kForward, alloc); unit->m_scfftR = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_outbuf, unit->m_outbuf, kBackward, alloc); unit->m_scfftR2 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_tempbuf, unit->m_tempbuf, kBackward, alloc); ClearUnitIfMemFailed(unit->m_scfft1 && unit->m_scfft2 && unit->m_scfft3 && unit->m_scfftR && unit->m_scfftR2); scfft_dofft(unit->m_scfft2); unit->m_pos = 0; unit->m_prevtrig = 0.f; SETCALC(Convolution2L_next); // initialize output OUT0(0) = IN0(0); } else { unit->m_scfft1 = unit->m_scfft2 = unit->m_scfft3 = unit->m_scfftR = unit->m_scfftR2 = nullptr; } } void Convolution2L_Dtor(Convolution2L* unit) { SCWorld_Allocator alloc(ft, unit->mWorld); scfft_destroy(unit->m_scfft1, alloc); scfft_destroy(unit->m_scfft2, alloc); scfft_destroy(unit->m_scfft3, alloc); scfft_destroy(unit->m_scfftR, alloc); scfft_destroy(unit->m_scfftR2, alloc); RTFree(unit->mWorld, unit->m_inbuf1); RTFree(unit->mWorld, unit->m_fftbuf1); RTFree(unit->mWorld, unit->m_fftbuf2); RTFree(unit->mWorld, unit->m_fftbuf3); RTFree(unit->mWorld, unit->m_tempbuf); RTFree(unit->mWorld, unit->m_outbuf); RTFree(unit->mWorld, unit->m_overlapbuf); } void Convolution2L_next(Convolution2L* unit, int numSamples) { float* in1 = IN(0); float curtrig = ZIN0(2); float* out1 = unit->m_inbuf1 + unit->m_pos; int framesize_f = unit->m_framesize * sizeof(float); // copy input memcpy(out1, in1, numSamples * sizeof(float)); unit->m_pos += numSamples; if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { uint32 bufnum = (int)ZIN0(1); SndBuf* buf = ConvGetBuffer(unit, bufnum, "Convolution2L", numSamples); if (!buf) return; unit->m_cflength = (int)ZIN0(4); unit->m_cfpos = 0; if (unit->m_curbuf == 1) { LOCK_SNDBUF_SHARED(buf); memcpy(unit->m_fftbuf2, buf->data, framesize_f); memset(unit->m_fftbuf2 + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft2); } else if (unit->m_curbuf == 0) { LOCK_SNDBUF_SHARED(buf); memcpy(unit->m_fftbuf3, buf->data, framesize_f); memset(unit->m_fftbuf3 + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft3); } } if (unit->m_pos & unit->m_framesize) { // have collected enough samples to transform next frame unit->m_pos = 0; // reset collection counter // copy to fftbuf memcpy(unit->m_fftbuf1, unit->m_inbuf1, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf1 + unit->m_framesize, 0, framesize_f); // in place transform for now scfft_dofft(unit->m_scfft1); // rffts(unit->m_fftbuf1, log2n, 1, cosTable[log2n]); // complex multiply time int numbins = unit->m_fftsize >> 1; // unit->m_fftsize - 2 >> 1; float* p1 = unit->m_fftbuf1; float* p2; if (unit->m_curbuf == 0) p2 = unit->m_fftbuf2; else p2 = unit->m_fftbuf3; float* p3 = unit->m_tempbuf; // multiply the dc and nyquist components p3[0] = p1[0] * p2[0]; p3[1] = p1[1] * p2[1]; // complex multiply for (int i = 1; i < numbins; ++i) { float real, imag; int realind, imagind; realind = 2 * i; imagind = realind + 1; real = p1[realind] * p2[realind] - p1[imagind] * p2[imagind]; imag = p1[realind] * p2[imagind] + p1[imagind] * p2[realind]; p3[realind] = real; p3[imagind] = imag; } // copy second part from before to overlap memcpy(unit->m_overlapbuf, unit->m_outbuf + unit->m_framesize, unit->m_framesize * sizeof(float)); // inverse fft into outbuf memcpy(unit->m_outbuf, unit->m_tempbuf, unit->m_fftsize * sizeof(float)); // in place scfft_doifft(unit->m_scfftR); if (unit->m_cfpos < unit->m_cflength) // do crossfade { if (unit->m_curbuf == 0) p2 = unit->m_fftbuf3; else p2 = unit->m_fftbuf2; // multiply the dc and nyquist components p1[0] *= p2[0]; p1[1] *= p2[1]; // complex multiply for (int i = 1; i < numbins; ++i) { float real, imag; int realind, imagind; realind = 2 * i; imagind = realind + 1; real = p1[realind] * p2[realind] - p1[imagind] * p2[imagind]; imag = p1[realind] * p2[imagind] + p1[imagind] * p2[realind]; p1[realind] = real; // p2->bin[i]; p1[imagind] = imag; } // copy second part from before to overlap // inverse fft into tempbuf memcpy(unit->m_tempbuf, unit->m_fftbuf1, unit->m_fftsize * sizeof(float)); scfft_doifft(unit->m_scfftR2); // now crossfade between outbuf and tempbuf float fact1 = (float)unit->m_cfpos / unit->m_cflength; // crossfade amount startpoint float rc = 1.f / (unit->m_cflength * unit->m_framesize); // crossfade amount increase per sample float* p4 = unit->m_outbuf; float* p5 = unit->m_tempbuf; for (int i = 0; i < unit->m_framesize; i++) { float res; res = (1 - fact1) * p4[i] + fact1 * p5[i]; fact1 += rc; p4[i] = res; } if (unit->m_cflength == 1) memcpy(unit->m_outbuf + unit->m_framesize, unit->m_tempbuf + unit->m_framesize, framesize_f); else { for (int i = unit->m_framesize + 1; i < unit->m_fftsize; i++) { float res = (1 - fact1) * p4[i] + fact1 * p5[i]; fact1 += rc; p4[i] = res; } } unit->m_cfpos++; if (unit->m_cfpos == unit->m_cflength) // at end of crossfade, update the current buffer index { if (unit->m_curbuf == 0) unit->m_curbuf = 1; else unit->m_curbuf = 0; } } } // write out samples copied from outbuf, with overlap added in float* output = ZOUT(0); float* out = unit->m_outbuf + unit->m_pos; float* overlap = unit->m_overlapbuf + unit->m_pos; unit->m_prevtrig = curtrig; for (int i = 0; i < numSamples; ++i) ZXP(output) = out[i] + overlap[i]; } /** basically the same as Convolution2L, but takes a stereo buffer to convolve with and outputs a stereo signal */ void StereoConvolution2L_Ctor(StereoConvolution2L* unit) { // require size N+M-1 to be a power of two unit->m_framesize = (int)ZIN0(4); unit->m_cflength = (int)ZIN0(5); unit->m_curbuf = 0; unit->m_cfpos = unit->m_cflength; unit->m_fftsize = 2 * (unit->m_framesize); // just use memory for the input buffers and fft buffers int framesize_f = unit->m_framesize * sizeof(float); int fftsize_f = unit->m_fftsize * sizeof(float); unit->m_inbuf1 = (float*)RTAlloc(unit->mWorld, framesize_f); // source: unit->m_fftbuf1 = (float*)RTAlloc(unit->mWorld, fftsize_f); // 2 channel buffer: unit->m_fftbuf2[0] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf2[1] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf3[0] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_fftbuf3[1] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_tempbuf[0] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_tempbuf[1] = (float*)RTAlloc(unit->mWorld, fftsize_f); // unit->m_tempfftbuf[0] = (float*)RTAlloc(unit->mWorld, fftsize_f); // unit->m_tempfftbuf[1] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_outbuf[0] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_overlapbuf[0] = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_outbuf[1] = (float*)RTAlloc(unit->mWorld, fftsize_f); unit->m_overlapbuf[1] = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_scfft1 = nullptr; unit->m_scfft2[0] = unit->m_scfft3[0] = unit->m_scfftR[0] = unit->m_scfftR2[0] = nullptr; unit->m_scfft2[1] = unit->m_scfft3[1] = unit->m_scfftR[1] = unit->m_scfftR2[1] = nullptr; ClearUnitIfMemFailed(unit->m_inbuf1 && unit->m_fftbuf1 && unit->m_fftbuf2[0] && unit->m_fftbuf2[1] && unit->m_fftbuf3[0] && unit->m_fftbuf3[1] && unit->m_tempbuf[0] && unit->m_tempbuf[1] && unit->m_outbuf[0] && unit->m_outbuf[1] && unit->m_overlapbuf[0] && unit->m_overlapbuf[1]); memset(unit->m_outbuf[0], 0, fftsize_f); memset(unit->m_overlapbuf[0], 0, framesize_f); memset(unit->m_outbuf[1], 0, fftsize_f); memset(unit->m_overlapbuf[1], 0, framesize_f); SCWorld_Allocator alloc(ft, unit->mWorld); unit->m_scfft1 = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf1, unit->m_fftbuf1, kForward, alloc); unit->m_scfft2[0] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf2[0], unit->m_fftbuf2[0], kForward, alloc); unit->m_scfft3[0] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf2[1], unit->m_fftbuf2[1], kForward, alloc); unit->m_scfftR[0] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf3[0], unit->m_fftbuf3[0], kForward, alloc); unit->m_scfftR2[0] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_fftbuf3[1], unit->m_fftbuf3[1], kForward, alloc); unit->m_scfft2[1] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_outbuf[0], unit->m_outbuf[0], kBackward, alloc); unit->m_scfft3[1] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_tempbuf[0], unit->m_tempbuf[0], kBackward, alloc); unit->m_scfftR[1] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_outbuf[1], unit->m_outbuf[1], kBackward, alloc); unit->m_scfftR2[1] = scfft_create(unit->m_fftsize, unit->m_fftsize, kRectWindow, unit->m_tempbuf[1], unit->m_tempbuf[1], kBackward, alloc); ClearUnitIfMemFailed(unit->m_scfft1 && unit->m_scfft2[0] && unit->m_scfft3[0] && unit->m_scfftR[0] && unit->m_scfftR2[0]); ClearUnitIfMemFailed(unit->m_scfft2[1] && unit->m_scfft3[1] && unit->m_scfftR[1] && unit->m_scfftR2[1]); float fbufnum = ZIN0(1); uint32 bufnumL = (int)fbufnum; fbufnum = ZIN0(2); uint32 bufnumR = (int)fbufnum; // printf("bufnum %i \n", bufnum); // unit->m_log2n = LOG2CEIL(unit->m_fftsize); // int log2n = unit->m_log2n; SndBuf* buf = ConvGetBuffer(unit, bufnumL, "StereoConvolution2L", 1); if (buf) { LOCK_SNDBUF_SHARED(buf); // calculate fft for kernel straight away memcpy(unit->m_fftbuf2[0], buf->data, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf2[0] + unit->m_framesize, 0, framesize_f); // in place transform for now scfft_dofft(unit->m_scfft2[0]); } else return; buf = ConvGetBuffer(unit, bufnumR, "StereoConvolution2L", 1); if (buf) { LOCK_SNDBUF(buf); // calculate fft for kernel straight away memcpy(unit->m_fftbuf2[1], buf->data, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf2[1] + unit->m_framesize, 0, framesize_f); // in place transform for now scfft_dofft(unit->m_scfft2[1]); unit->m_pos = 0; unit->m_prevtrig = 0.f; SETCALC(StereoConvolution2L_next); // initialize outputs OUT0(0) = IN0(0); OUT0(1) = IN0(0); } } void StereoConvolution2L_Dtor(StereoConvolution2L* unit) { SCWorld_Allocator alloc(ft, unit->mWorld); scfft_destroy(unit->m_scfft1, alloc); scfft_destroy(unit->m_scfft2[0], alloc); scfft_destroy(unit->m_scfft3[0], alloc); scfft_destroy(unit->m_scfftR[0], alloc); scfft_destroy(unit->m_scfftR2[0], alloc); scfft_destroy(unit->m_scfft2[1], alloc); scfft_destroy(unit->m_scfft3[1], alloc); scfft_destroy(unit->m_scfftR[1], alloc); scfft_destroy(unit->m_scfftR2[1], alloc); RTFree(unit->mWorld, unit->m_inbuf1); RTFree(unit->mWorld, unit->m_fftbuf1); RTFree(unit->mWorld, unit->m_fftbuf2[0]); RTFree(unit->mWorld, unit->m_fftbuf3[0]); RTFree(unit->mWorld, unit->m_tempbuf[0]); RTFree(unit->mWorld, unit->m_outbuf[0]); RTFree(unit->mWorld, unit->m_overlapbuf[0]); RTFree(unit->mWorld, unit->m_fftbuf2[1]); RTFree(unit->mWorld, unit->m_fftbuf3[1]); RTFree(unit->mWorld, unit->m_tempbuf[1]); RTFree(unit->mWorld, unit->m_outbuf[1]); RTFree(unit->mWorld, unit->m_overlapbuf[1]); } void StereoConvolution2L_next(StereoConvolution2L* unit, int wrongNumSamples) { float* in1 = IN(0); float curtrig = ZIN0(3); float* out1 = unit->m_inbuf1 + unit->m_pos; int numSamples = unit->mWorld->mFullRate.mBufLength; uint32 framesize_f = unit->m_framesize * sizeof(float); // copy input Copy(numSamples, out1, in1); unit->m_pos += numSamples; if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { float fbufnum = ZIN0(1); uint32 bufnumL = (int)fbufnum; fbufnum = ZIN0(2); uint32 bufnumR = (int)fbufnum; unit->m_cflength = (int)ZIN0(5); SndBuf* bufL = ConvGetBuffer(unit, bufnumL, "StereoConvolution2L", numSamples); SndBuf* bufR = ConvGetBuffer(unit, bufnumR, "StereoConvolution2L", numSamples); if (!bufL || !bufL) return; unit->m_cfpos = 0; if (unit->m_curbuf == 1) { LOCK_SNDBUF2_SHARED(bufL, bufR); memcpy(unit->m_fftbuf2[0], bufL->data, framesize_f); memset(unit->m_fftbuf2[0] + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft2[0]); memcpy(unit->m_fftbuf2[1], bufR->data, framesize_f); memset(unit->m_fftbuf2[1] + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft2[1]); } else if (unit->m_curbuf == 0) { LOCK_SNDBUF2_SHARED(bufL, bufR); memcpy(unit->m_fftbuf3[0], bufL->data, framesize_f); memset(unit->m_fftbuf3[0] + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft3[0]); memcpy(unit->m_fftbuf3[1], bufR->data, framesize_f); memset(unit->m_fftbuf3[1] + unit->m_framesize, 0, framesize_f); scfft_dofft(unit->m_scfft3[1]); } } if (unit->m_pos & unit->m_framesize) { // have collected enough samples to transform next frame unit->m_pos = 0; // reset collection counter // copy to fftbuf memcpy(unit->m_fftbuf1, unit->m_inbuf1, framesize_f); // zero pad second part of buffer to allow for convolution memset(unit->m_fftbuf1 + unit->m_framesize, 0, framesize_f); // in place transform for now scfft_dofft(unit->m_scfft1); // complex multiply time int numbins = unit->m_fftsize >> 1; // unit->m_fftsize - 2 >> 1; float* p1 = unit->m_fftbuf1; float *p2L, *p2R; if (unit->m_curbuf == 0) { p2L = unit->m_fftbuf2[0]; p2R = unit->m_fftbuf2[1]; } else { p2L = unit->m_fftbuf3[0]; p2R = unit->m_fftbuf3[1]; } float* p3L = unit->m_tempbuf[0]; float* p3R = unit->m_tempbuf[1]; // complex multiply for (int i = 1; i < numbins; ++i) { float realL, imagL; float realR, imagR; int realind, imagind; realind = 2 * i; imagind = realind + 1; realL = p1[realind] * p2L[realind] - p1[imagind] * p2L[imagind]; imagL = p1[realind] * p2L[imagind] + p1[imagind] * p2L[realind]; realR = p1[realind] * p2R[realind] - p1[imagind] * p2R[imagind]; imagR = p1[realind] * p2R[imagind] + p1[imagind] * p2R[realind]; p3L[realind] = realL; // p2->bin[i]; p3L[imagind] = imagL; p3R[realind] = realR; // p2->bin[i]; p3R[imagind] = imagR; } for (int i = 0; i < 2; i++) { // copy second part from before to overlap memcpy(unit->m_overlapbuf[i], unit->m_outbuf[i] + unit->m_framesize, unit->m_framesize * sizeof(float)); // inverse fft into outbuf memcpy(unit->m_outbuf[i], unit->m_tempbuf[i], unit->m_fftsize * sizeof(float)); // in place scfft_doifft(unit->m_scfftR[i]); } if (unit->m_cfpos < unit->m_cflength) // do crossfade { if (unit->m_curbuf == 0) { p2L = unit->m_fftbuf3[0]; p2R = unit->m_fftbuf3[1]; } else { p2L = unit->m_fftbuf2[0]; p2R = unit->m_fftbuf2[1]; } // complex multiply for (int i = 1; i < numbins; ++i) { float realL, imagL; float realR, imagR; int realind, imagind; realind = 2 * i; imagind = realind + 1; realL = p1[realind] * p2L[realind] - p1[imagind] * p2L[imagind]; imagL = p1[realind] * p2L[imagind] + p1[imagind] * p2L[realind]; realR = p1[realind] * p2R[realind] - p1[imagind] * p2R[imagind]; imagR = p1[realind] * p2R[imagind] + p1[imagind] * p2R[realind]; p3L[realind] = realL; // p2->bin[i]; p3L[imagind] = imagL; p3R[realind] = realR; // p2->bin[i]; p3R[imagind] = imagR; } scfft_doifft(unit->m_scfftR2[0]); scfft_doifft(unit->m_scfftR2[1]); // now crossfade between outbuf and tempbuf float fact1 = (float)unit->m_cfpos / unit->m_cflength; // crossfade amount startpoint float rc = 1.f / (unit->m_cflength * unit->m_framesize); // crossfade amount increase per sample float* p4L = unit->m_outbuf[0]; float* p5L = unit->m_tempbuf[0]; float* p4R = unit->m_outbuf[1]; float* p5R = unit->m_tempbuf[1]; for (int i = 0; i < unit->m_framesize; i++) { float res; res = (1 - fact1) * p4L[i] + fact1 * p5L[i]; p4L[i] = res; res = (1 - fact1) * p4R[i] + fact1 * p5R[i]; p4R[i] = res; fact1 += rc; } if (unit->m_cflength == 1) // in the overlap the convolution is already at the new buffer { memcpy(unit->m_outbuf[0] + unit->m_framesize, unit->m_tempbuf[0] + unit->m_framesize, unit->m_framesize * sizeof(float)); memcpy(unit->m_outbuf[1] + unit->m_framesize, unit->m_tempbuf[1] + unit->m_framesize, unit->m_framesize * sizeof(float)); } else { for (int i = unit->m_framesize + 1; i < unit->m_fftsize; i++) { float res; res = (1 - fact1) * p4L[i] + fact1 * p5L[i]; p4L[i] = res; res = (1 - fact1) * p4R[i] + fact1 * p5R[i]; p4R[i] = res; fact1 += rc; } } unit->m_cfpos++; if (unit->m_cfpos == unit->m_cflength) // at end of crossfade, update the current buffer index { if (unit->m_curbuf == 0) unit->m_curbuf = 1; else unit->m_curbuf = 0; } } } // write out samples copied from outbuf, with overlap added in float* outputL = ZOUT(0); float* outputR = ZOUT(1); float* outL = unit->m_outbuf[0] + unit->m_pos; float* overlapL = unit->m_overlapbuf[0] + unit->m_pos; float* outR = unit->m_outbuf[1] + unit->m_pos; float* overlapR = unit->m_overlapbuf[1] + unit->m_pos; unit->m_prevtrig = curtrig; for (int i = 0; i < numSamples; ++i) { ZXP(outputL) = outL[i] + overlapL[i]; ZXP(outputR) = outR[i] + overlapR[i]; } } void Convolution3_Ctor(Convolution3* unit) { unit->m_framesize = (int)ZIN0(3); float fbufnum = ZIN0(1); uint32 bufnum = (int)fbufnum; SndBuf* buf = ConvGetBuffer(unit, bufnum, "Convolution3", 1); unit->m_inbuf1 = unit->m_inbuf2 = unit->m_outbuf = nullptr; if (buf) { if (unit->m_framesize <= 0) // if smaller than zero, equal to size of buffer { unit->m_framesize = buf->frames; } // just use memory for the input buffers and out buffer int framesize_f = unit->m_framesize * sizeof(float); unit->m_inbuf1 = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_inbuf2 = (float*)RTAlloc(unit->mWorld, framesize_f); unit->m_outbuf = (float*)RTAlloc(unit->mWorld, framesize_f); ClearUnitIfMemFailed(unit->m_inbuf1 && unit->m_inbuf2 && unit->m_outbuf); LOCK_SNDBUF_SHARED(buf); // calculate fft for kernel straight away memcpy(unit->m_inbuf2, buf->data, framesize_f); unit->m_pos = 0; memset(unit->m_outbuf, 0, framesize_f); unit->m_prevtrig = 0.f; if (INRATE(0) == calc_FullRate) SETCALC(Convolution3_next_a); else SETCALC(Convolution3_next_k); // initialize output OUT0(0) = IN0(0); } } void Convolution3_Dtor(Convolution3* unit) { RTFree(unit->mWorld, unit->m_inbuf1); RTFree(unit->mWorld, unit->m_inbuf2); RTFree(unit->mWorld, unit->m_outbuf); } void Convolution3_next_a(Convolution3* unit) { float* in = IN(0); float curtrig = ZIN0(2); float* pin1 = unit->m_inbuf1; int numSamples = unit->mWorld->mFullRate.mBufLength; // copy input Copy(numSamples, pin1, in); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { uint32 framesize_f = unit->m_framesize * sizeof(float); float fbufnum = ZIN0(1); uint32 bufnum = (int)fbufnum; SndBuf* buf = ConvGetBuffer(unit, bufnum, "Convolution3", numSamples); LOCK_SNDBUF_SHARED(buf); memcpy(unit->m_inbuf2, buf->data, framesize_f); } float* pin2 = unit->m_inbuf2; float* pout = unit->m_outbuf; int pos = unit->m_pos; int size = unit->m_framesize; for (int j = 0; j < numSamples; ++j) { float input = pin1[j]; for (int i = 0; i < size; ++i) { int ind = (pos + i + j) % (size); pout[ind] = pout[ind] + pin2[i] * input; } } float* output = ZOUT(0); for (int i = 0; i < numSamples; ++i) { int ind = (pos + i) % (size); *++output = pout[ind]; } pos = pos + numSamples; if (pos > size) { unit->m_pos = pos - size; // reset collection counter } else { unit->m_pos += numSamples; } unit->m_prevtrig = curtrig; } void Convolution3_next_k(Convolution3* unit) { float input = ZIN0(0); float curtrig = ZIN0(2); uint32 framesize_f = unit->m_framesize * sizeof(float); if (unit->m_prevtrig <= 0.f && curtrig > 0.f) { float fbufnum = ZIN0(1); uint32 bufnum = (int)fbufnum; SndBuf* buf = ConvGetBuffer(unit, bufnum, "Convolution3", 1); if (!buf) return; LOCK_SNDBUF_SHARED(buf); memcpy(unit->m_inbuf2, buf->data, framesize_f); } float* pin = unit->m_inbuf2; float* pout = unit->m_outbuf; int pos = unit->m_pos; int size = unit->m_framesize; for (int i = 0; i < size; ++i) { int ind = (pos + i) % (size); pout[ind] = pout[ind] + pin[i] * input; } float* output = OUT(0); *output = pout[pos]; if (++pos > size) unit->m_pos = 0; // reset collection counter else unit->m_pos++; unit->m_prevtrig = curtrig; } void initConvolution(InterfaceTable* it) { DefineDtorUnit(Convolution); DefineDtorUnit(Convolution2); DefineDtorUnit(Convolution2L); DefineDtorUnit(StereoConvolution2L); DefineDtorUnit(Convolution3); }
43,466
C++
.cpp
935
37.640642
119
0.591283
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
29,951
FilterUGens.cpp
supercollider_supercollider/server/plugins/FilterUGens.cpp
/* 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_PlugIn.h" #include <limits> // NaNs are not equal to any floating point number static const float uninitializedControl = std::numeric_limits<float>::quiet_NaN(); #define PI 3.1415926535898f #define PUSH_LOOPVALS \ int tmp_floops = unit->mRate->mFilterLoops; \ int tmp_fremain = unit->mRate->mFilterRemain; \ unit->mRate->mFilterLoops = 0; \ unit->mRate->mFilterRemain = 1; #define POP_LOOPVALS \ unit->mRate->mFilterLoops = tmp_floops; \ unit->mRate->mFilterRemain = tmp_fremain; using namespace std; // for math functions static InterfaceTable* ft; struct Ramp : public Unit { double m_level, m_slope; int m_counter; }; struct Lag : public Unit { float m_lag; double m_b1, m_y1; }; struct Lag2 : public Unit { float m_lag; double m_b1, m_y1a, m_y1b; }; struct Lag3 : public Unit { float m_lag; double m_b1, m_y1a, m_y1b, m_y1c; }; struct LagUD : public Unit { float m_lagu, m_lagd; double m_b1u, m_b1d, m_y1; }; struct Lag2UD : public Unit { float m_lagu, m_lagd; double m_b1u, m_b1d, m_y1a, m_y1b; }; struct Lag3UD : public Unit { float m_lagu, m_lagd; double m_b1u, m_b1d, m_y1a, m_y1b, m_y1c; }; struct VarLag : public Unit { double m_level, m_slope; int m_counter; float m_in, m_lagTime; }; struct OnePole : public Unit { double m_b1, m_y1; }; struct OneZero : public Unit { double m_b1, m_x1; }; struct Integrator : public Unit { double m_b1, m_y1; }; struct Decay : public Unit { float m_decayTime; double m_y1, m_b1; }; struct Decay2 : public Unit { float m_attackTime; double m_y1a, m_b1a; float m_decayTime; double m_y1b, m_b1b; }; struct LeakDC : public Unit { double m_b1, m_x1, m_y1; }; struct TwoPole : public Unit { float m_freq, m_reson; double m_y1, m_y2, m_b1, m_b2; }; struct APF : public Unit { float m_freq, m_reson; double m_y1, m_y2, m_x1, m_x2, m_b1, m_b2; }; struct TwoZero : public Unit { float m_freq, m_reson; double m_x1, m_x2, m_b1, m_b2; }; struct LPZ1 : public Unit { double m_x1; }; struct HPZ1 : public Unit { double m_x1; }; struct HPZ2 : public Unit { double m_x1, m_x2; }; struct BPZ2 : public Unit { double m_x1, m_x2; }; struct BRZ2 : public Unit { double m_x1, m_x2; }; struct LPZ2 : public Unit { double m_x1, m_x2; }; struct Flip : public Unit {}; struct Delay1 : public Unit { float m_x1; }; struct Delay2 : public Unit { float m_x1, m_x2; }; struct Slope : public Unit { double m_x1; }; struct Slew : public Unit { double mLevel; }; struct RLPF : public Unit { float m_freq, m_reson; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct RHPF : public Unit { float m_freq, m_reson; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct LPF : public Unit { float m_freq; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct HPF : public Unit { float m_freq; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct BPF : public Unit { float m_freq, m_bw; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct BRF : public Unit { float m_freq, m_bw; double m_y1, m_y2, m_a0, m_a1, m_b2; }; struct MidEQ : public Unit { float m_freq, m_bw, m_db; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct Resonz : public Unit { float m_freq, m_rq; double m_y1, m_y2, m_a0, m_b1, m_b2; }; struct Ringz : public Unit { float m_freq, m_decayTime; double m_y1, m_y2, m_b1, m_b2; }; struct FOS : public Unit { double m_y1, m_a0, m_a1, m_b1; }; struct SOS : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; }; struct Formlet : public Unit { float m_freq, m_decayTime, m_attackTime; double m_y01, m_y02, m_b01, m_b02; double m_y11, m_y12, m_b11, m_b12; }; const int kMAXMEDIANSIZE = 32; struct Median : public Unit { float m_medianValue[kMAXMEDIANSIZE]; long m_medianAge[kMAXMEDIANSIZE]; long m_medianSize, m_medianIndex; }; struct Compander : public Unit { float m_prevmaxval, m_gain, m_clamp, m_clampcoef, m_relax, m_relaxcoef; }; struct Normalizer : public Unit { float *m_table, *m_xinbuf, *m_xoutbuf, *m_xmidbuf; long m_flips, m_pos, m_bufsize; float m_slope, m_level, m_curmaxval, m_prevmaxval, m_slopefactor; }; struct Limiter : public Unit { float *m_table, *m_xinbuf, *m_xoutbuf, *m_xmidbuf; long m_flips, m_pos, m_bufsize; float m_slope, m_level, m_curmaxval, m_prevmaxval, m_slopefactor; }; struct Amplitude : public Unit { float m_previn, m_clampcoef, m_relaxcoef, m_clamp_in, m_relax_in; }; struct DetectSilence : public Unit { float mThresh; int32 mCounter, mEndCounter; }; struct Hilbert : public Unit { double m_coefs[12]; double m_y1[12]; }; struct FreqShift : public Unit { float m_coefs[12]; float m_y1[12]; int32 m_phase; int32 m_phaseoffset, m_lomask; double m_cpstoinc, m_radtoinc, m_phasein; }; struct MoogFF : public Unit { float m_freq, m_k; double m_b0, m_a1; // Resonant freq and corresponding vals; stored because we need to compare against prev vals double m_s1, m_s2, m_s3, m_s4; // 1st order filter states }; ////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" { void Ramp_next(Ramp* unit, int inNumSamples); void Ramp_next_1(Ramp* unit, int inNumSamples); void Ramp_Ctor(Ramp* unit); void Lag_next(Lag* unit, int inNumSamples); void Lag_Ctor(Lag* unit); void Lag2_Ctor(Lag2* unit); void Lag3_next(Lag3* unit, int inNumSamples); void Lag3_Ctor(Lag3* unit); void LagUD_next(LagUD* unit, int inNumSamples); void LagUD_Ctor(LagUD* unit); void Lag2UD_next(Lag2UD* unit, int inNumSamples); void Lag2UD_Ctor(Lag2UD* unit); void Lag3UD_next(Lag3UD* unit, int inNumSamples); void Lag3UD_Ctor(Lag3UD* unit); void VarLag_next(VarLag* unit, int inNumSamples); void VarLag_Ctor(VarLag* unit); void OnePole_next_a(OnePole* unit, int inNumSamples); void OnePole_next_k(OnePole* unit, int inNumSamples); void OnePole_Ctor(OnePole* unit); void OneZero_next(OneZero* unit, int inNumSamples); void OneZero_Ctor(OneZero* unit); void Integrator_next(Integrator* unit, int inNumSamples); void Integrator_next_i(Integrator* unit, int inNumSamples); void Integrator_Ctor(Integrator* unit); void Decay_next(Decay* unit, int inNumSamples); void Decay_Ctor(Decay* unit); void Decay2_next(Decay2* unit, int inNumSamples); void Decay2_Ctor(Decay2* unit); void LeakDC_next(LeakDC* unit, int inNumSamples); void LeakDC_next_1(LeakDC* unit, int inNumSamples); void LeakDC_Ctor(LeakDC* unit); void TwoPole_next(TwoPole* unit, int inNumSamples); void TwoPole_Ctor(TwoPole* unit); void TwoZero_next(TwoZero* unit, int inNumSamples); void TwoZero_Ctor(TwoZero* unit); void APF_next(APF* unit, int inNumSamples); void APF_Ctor(APF* unit); void LPZ1_next(LPZ1* unit, int inNumSamples); void LPZ1_Ctor(LPZ1* unit); void HPZ1_next(HPZ1* unit, int inNumSamples); void HPZ1_Ctor(HPZ1* unit); void Slope_next(Slope* unit, int inNumSamples); void Slope_Ctor(Slope* unit); void Delay1_next(Delay1* unit, int inNumSamples); void Delay1_Ctor(Delay1* unit); void Flip_Ctor(Flip* unit); void Flip_next_even(Flip* unit, int inNumSamples); void Flip_next_odd(Flip* unit, int inNumSamples); void Delay2_next(Delay2* unit, int inNumSamples); void Delay2_Ctor(Delay2* unit); void LPZ2_next(LPZ2* unit, int inNumSamples); void LPZ2_Ctor(LPZ2* unit); void HPZ2_next(HPZ2* unit, int inNumSamples); void HPZ2_Ctor(HPZ2* unit); void BPZ2_next(BPZ2* unit, int inNumSamples); void BPZ2_Ctor(BPZ2* unit); void BRZ2_next(BRZ2* unit, int inNumSamples); void BRZ2_Ctor(BRZ2* unit); void Slew_next(Slew* unit, int inNumSamples); void Slew_Ctor(Slew* unit); void RLPF_next(RLPF* unit, int inNumSamples); void RLPF_next_1(RLPF* unit, int inNumSamples); void RLPF_Ctor(RLPF* unit); void RHPF_next(RHPF* unit, int inNumSamples); void RHPF_next_1(RHPF* unit, int inNumSamples); void RHPF_Ctor(RHPF* unit); void LPF_next(LPF* unit, int inNumSamples); void LPF_next_1(LPF* unit, int inNumSamples); void LPF_Ctor(LPF* unit); void HPF_next(HPF* unit, int inNumSamples); void HPF_next_1(HPF* unit, int inNumSamples); void HPF_Ctor(HPF* unit); void BPF_next(BPF* unit, int inNumSamples); void BPF_next_1(BPF* unit, int inNumSamples); void BPF_Ctor(BPF* unit); void BRF_next(BRF* unit, int inNumSamples); void BRF_next_1(BRF* unit, int inNumSamples); void BRF_Ctor(BRF* unit); void Median_next(Median* unit, int inNumSamples); void Median_Ctor(Median* unit); void MidEQ_next(MidEQ* unit, int inNumSamples); void MidEQ_Ctor(MidEQ* unit); void Resonz_next(Resonz* unit, int inNumSamples); void Resonz_Ctor(Resonz* unit); void Ringz_next(Ringz* unit, int inNumSamples); void Ringz_Ctor(Ringz* unit); void Formlet_next(Formlet* unit, int inNumSamples); void Formlet_next_1(Formlet* unit, int inNumSamples); void Formlet_Ctor(Formlet* unit); void FOS_next_k(FOS* unit, int inNumSamples); void FOS_next_a(FOS* unit, int inNumSamples); void FOS_next_1(FOS* unit, int inNumSamples); void FOS_Ctor(FOS* unit); void SOS_next_i(SOS* unit, int inNumSamples); void SOS_next_k(SOS* unit, int inNumSamples); void SOS_next_a(SOS* unit, int inNumSamples); void SOS_next_1(SOS* unit, int inNumSamples); void SOS_Ctor(SOS* unit); void Normalizer_next(Normalizer* unit, int inNumSamples); void Normalizer_Ctor(Normalizer* unit); void Normalizer_Dtor(Normalizer* unit); void Limiter_next(Limiter* unit, int inNumSamples); void Limiter_Ctor(Limiter* unit); void Limiter_Dtor(Limiter* unit); void Compander_next(Compander* unit, int inNumSamples); void Compander_Ctor(Compander* unit); void Amplitude_next(Amplitude* unit, int inNumSamples); void Amplitude_next_kk(Amplitude* unit, int inNumSamples); void Amplitude_next_atok(Amplitude* unit, int inNumSamples); void Amplitude_next_atok_kk(Amplitude* unit, int inNumSamples); void Amplitude_Ctor(Amplitude* unit); void DetectSilence_next(DetectSilence* unit, int inNumSamples); void DetectSilence_next_k(DetectSilence* unit, int inNumSamples); // void DetectSilence_done(DetectSilence *unit, int inNumSamples); void DetectSilence_Ctor(DetectSilence* unit); void Hilbert_Ctor(Hilbert* unit); void Hilbert_next(Hilbert* unit, int inNumSamples); void FreqShift_Ctor(FreqShift* unit); void FreqShift_next_kk(FreqShift* unit, int inNumSamples); void FreqShift_next_aa(FreqShift* unit, int inNumSamples); void FreqShift_next_ak(FreqShift* unit, int inNumSamples); void FreqShift_next_ka(FreqShift* unit, int inNumSamples); void MoogFF_next(MoogFF* unit, int inNumSamples); void MoogFF_Ctor(MoogFF* unit); /* void Lag_next(Lag *unit, int inNumSamples); void Lag_Ctor(Lag* unit); void Lag_next(Lag *unit, int inNumSamples); void Lag_Ctor(Lag* unit); */ } ////////////////////////////////////////////////////////////////////////////////////////////////// void Ramp_next(Ramp* unit, int inNumSamples) { float* out = ZOUT(0); float* in = IN(0); float period = ZIN0(1); double slope = unit->m_slope; double level = unit->m_level; int counter = unit->m_counter; int remain = inNumSamples; while (remain) { int nsmps = sc_min(remain, counter); LOOP(nsmps, ZXP(out) = level; level += slope;); in += nsmps; counter -= nsmps; remain -= nsmps; if (counter <= 0) { counter = (int)(period * SAMPLERATE); counter = sc_max(1, counter); slope = (*in - level) / counter; } } unit->m_level = level; unit->m_slope = slope; unit->m_counter = counter; } void Ramp_next_1(Ramp* unit, int inNumSamples) { float* out = OUT(0); *out = unit->m_level; unit->m_level += unit->m_slope; if (--unit->m_counter <= 0) { float in = ZIN0(0); float period = ZIN0(1); int counter = (int)(period * SAMPLERATE); unit->m_counter = counter = sc_max(1, counter); unit->m_slope = (in - unit->m_level) / counter; } } void Ramp_Ctor(Ramp* unit) { if (BUFLENGTH == 1) { SETCALC(Ramp_next_1); } else { SETCALC(Ramp_next); } unit->m_counter = 1; unit->m_level = ZIN0(0); unit->m_slope = 0.f; ZOUT0(0) = unit->m_level; } ////////////////////////////////////////////////////////////////////////////////////////////////// void Lag_next(Lag* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lag = ZIN0(1); double y1 = unit->m_y1; double b1 = unit->m_b1; if (lag == unit->m_lag) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 - y0);); } else { unit->m_b1 = lag == 0.f ? 0.f : exp(log001 / (lag * unit->mRate->mSampleRate)); double b1_slope = CALCSLOPE(unit->m_b1, b1); unit->m_lag = lag; LOOP1(inNumSamples, b1 += b1_slope; double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 - y0);); } unit->m_y1 = zapgremlins(y1); } void Lag_next_1(Lag* unit, int inNumSamples) { float* out = OUT(0); float* in = IN(0); float lag = IN0(1); double y1 = unit->m_y1; double b1 = unit->m_b1; if (lag == unit->m_lag) { double y0 = *in; *out = y1 = y0 + b1 * (y1 - y0); } else { unit->m_b1 = b1 = lag == 0.f ? 0.f : exp(log001 / (lag * unit->mRate->mSampleRate)); unit->m_lag = lag; double y0 = *in; *out = y1 = y0 + b1 * (y1 - y0); } unit->m_y1 = zapgremlins(y1); } void Lag_Ctor(Lag* unit) { if (BUFLENGTH == 1) SETCALC(Lag_next_1); else SETCALC(Lag_next); unit->m_lag = uninitializedControl; unit->m_b1 = 0.f; unit->m_y1 = ZIN0(0); Lag_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void LagUD_next(LagUD* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lagu = ZIN0(1); float lagd = ZIN0(2); double y1 = unit->m_y1; double b1u = unit->m_b1u; double b1d = unit->m_b1d; if ((lagu == unit->m_lagu) && (lagd == unit->m_lagd)) { LOOP1(inNumSamples, double y0 = ZXP(in); if (y0 > y1) ZXP(out) = y1 = y0 + b1u * (y1 - y0); else ZXP(out) = y1 = y0 + b1d * (y1 - y0);); } else { unit->m_b1u = lagu == 0.f ? 0.f : exp(log001 / (lagu * unit->mRate->mSampleRate)); double b1u_slope = CALCSLOPE(unit->m_b1u, b1u); unit->m_lagu = lagu; unit->m_b1d = lagd == 0.f ? 0.f : exp(log001 / (lagd * unit->mRate->mSampleRate)); double b1d_slope = CALCSLOPE(unit->m_b1d, b1d); unit->m_lagd = lagd; LOOP1(inNumSamples, b1u += b1u_slope; b1d += b1d_slope; double y0 = ZXP(in); if (y0 > y1) ZXP(out) = y1 = y0 + b1u * (y1 - y0); else ZXP(out) = y1 = y0 + b1d * (y1 - y0);); } unit->m_y1 = zapgremlins(y1); } void LagUD_Ctor(LagUD* unit) { SETCALC(LagUD_next); unit->m_lagu = uninitializedControl; unit->m_lagd = uninitializedControl; unit->m_b1u = 0.f; unit->m_b1d = 0.f; unit->m_y1 = ZIN0(0); LagUD_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// static void Lag2_next_k(Lag2* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lag = ZIN0(1); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double b1 = unit->m_b1; if (lag == unit->m_lag) { LOOP1(inNumSamples, double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); ZXP(out) = y1b;); } else { unit->m_b1 = lag == 0.f ? 0.f : exp(log001 / (lag * unit->mRate->mSampleRate)); double b1_slope = CALCSLOPE(unit->m_b1, b1); unit->m_lag = lag; LOOP1(inNumSamples, b1 += b1_slope; double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); ZXP(out) = y1b;); } unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); } static void Lag2_next_i(Lag2* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double b1 = unit->m_b1; LOOP1(inNumSamples, double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); ZXP(out) = y1b;); unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); } static void Lag2_next_1_i(Lag2* unit, int inNumSamples) { double y1a = unit->m_y1a; double y1b = unit->m_y1b; double b1 = unit->m_b1; float y0a = ZIN0(0); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); ZOUT0(0) = y1b; unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); } void Lag2_Ctor(Lag2* unit) { switch (INRATE(1)) { case calc_FullRate: case calc_BufRate: SETCALC(Lag2_next_k); break; default: if (BUFLENGTH == 1) SETCALC(Lag2_next_1_i); else SETCALC(Lag2_next_i); break; } unit->m_lag = uninitializedControl; unit->m_b1 = 0.f; unit->m_y1a = unit->m_y1b = ZIN0(0); Lag2_next_k(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Lag2UD_next(Lag2UD* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lagu = ZIN0(1); float lagd = ZIN0(2); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double b1u = unit->m_b1u; double b1d = unit->m_b1d; if ((lagu == unit->m_lagu) && (lagd == unit->m_lagd)) { LOOP1( inNumSamples, double y0a = ZXP(in); if (y0a > y1a) { y1a = y0a + b1u * (y1a - y0a); } else { y1a = y0a + b1d * (y1a - y0a); } if (y1a > y1b) y1b = y1a + b1u * (y1b - y1a); else y1b = y1a + b1d * (y1b - y1a); ZXP(out) = y1b;); } else { unit->m_b1u = lagu == 0.f ? 0.f : exp(log001 / (lagu * unit->mRate->mSampleRate)); double b1u_slope = CALCSLOPE(unit->m_b1u, b1u); unit->m_lagu = lagu; unit->m_b1d = lagd == 0.f ? 0.f : exp(log001 / (lagd * unit->mRate->mSampleRate)); double b1d_slope = CALCSLOPE(unit->m_b1d, b1d); unit->m_lagd = lagd; LOOP1( inNumSamples, b1u += b1u_slope; b1d += b1d_slope; double y0a = ZXP(in); if (y0a > y1a) { y1a = y0a + b1u * (y1a - y0a); } else { y1a = y0a + b1d * (y1a - y0a); } if (y1a > y1b) y1b = y1a + b1u * (y1b - y1a); else y1b = y1a + b1d * (y1b - y1a); ZXP(out) = y1b;); } unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); } void Lag2UD_Ctor(Lag2UD* unit) { SETCALC(Lag2UD_next); unit->m_lagu = 0.f; unit->m_lagd = 0.f; unit->m_b1u = 0.f; unit->m_b1d = 0.f; unit->m_y1a = unit->m_y1b = ZIN0(0); Lag2UD_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Lag3_next(Lag3* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lag = ZIN0(1); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double y1c = unit->m_y1c; double b1 = unit->m_b1; if (lag == unit->m_lag) { LOOP1(inNumSamples, double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); y1c = y1b + b1 * (y1c - y1b); ZXP(out) = y1c;); } else { unit->m_b1 = lag == 0.f ? 0.f : exp(log001 / (lag * unit->mRate->mSampleRate)); double b1_slope = CALCSLOPE(unit->m_b1, b1); unit->m_lag = lag; LOOP1(inNumSamples, b1 += b1_slope; double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); y1c = y1b + b1 * (y1c - y1b); ZXP(out) = y1c;); } unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); unit->m_y1c = zapgremlins(y1c); } static void Lag3_next_1_i(Lag3* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double y1c = unit->m_y1c; double b1 = unit->m_b1; double y0a = ZXP(in); y1a = y0a + b1 * (y1a - y0a); y1b = y1a + b1 * (y1b - y1a); y1c = y1b + b1 * (y1c - y1b); ZXP(out) = y1c; unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); unit->m_y1c = zapgremlins(y1c); } void Lag3_Ctor(Lag3* unit) { switch (INRATE(1)) { case calc_FullRate: case calc_BufRate: SETCALC(Lag3_next); break; default: if (BUFLENGTH == 1) SETCALC(Lag3_next_1_i); else SETCALC(Lag3_next); break; } unit->m_lag = uninitializedControl; unit->m_b1 = 0.f; unit->m_y1a = unit->m_y1b = unit->m_y1c = ZIN0(0); Lag3_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void Lag3UD_next(Lag3UD* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float lagu = ZIN0(1); float lagd = ZIN0(2); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double y1c = unit->m_y1c; double b1u = unit->m_b1u; double b1d = unit->m_b1d; if ((lagu == unit->m_lagu) && (lagd == unit->m_lagd)) { LOOP1( inNumSamples, double y0a = ZXP(in); if (y0a > y1a) { y1a = y0a + b1u * (y1a - y0a); } else { y1a = y0a + b1d * (y1a - y0a); } if (y1a > y1b) { y1b = y1a + b1u * (y1b - y1a); } else { y1b = y1a + b1d * (y1b - y1a); } if (y1a > y1b) { y1c = y1b + b1u * (y1c - y1b); } else { y1c = y1b + b1d * (y1c - y1b); } ZXP(out) = y1c;); } else { unit->m_b1u = lagu == 0.f ? 0.f : exp(log001 / (lagu * unit->mRate->mSampleRate)); double b1u_slope = CALCSLOPE(unit->m_b1u, b1u); unit->m_lagu = lagu; unit->m_b1d = lagd == 0.f ? 0.f : exp(log001 / (lagd * unit->mRate->mSampleRate)); double b1d_slope = CALCSLOPE(unit->m_b1d, b1d); unit->m_lagd = lagd; LOOP1( inNumSamples, b1u += b1u_slope; b1d += b1d_slope; double y0a = ZXP(in); if (y0a > y1a) { y1a = y0a + b1u * (y1a - y0a); } else { y1a = y0a + b1d * (y1a - y0a); } if (y1a > y1b) { y1b = y1a + b1u * (y1b - y1a); } else { y1b = y1a + b1d * (y1b - y1a); } if (y1a > y1b) { y1c = y1b + b1u * (y1c - y1b); } else { y1c = y1b + b1d * (y1c - y1b); } ZXP(out) = y1c;); } unit->m_y1a = zapgremlins(y1a); unit->m_y1b = zapgremlins(y1b); unit->m_y1c = zapgremlins(y1c); } void Lag3UD_Ctor(Lag3UD* unit) { SETCALC(Lag3UD_next); unit->m_lagu = uninitializedControl; unit->m_lagd = uninitializedControl; unit->m_b1u = 0.f; unit->m_b1d = 0.f; unit->m_y1a = unit->m_y1b = unit->m_y1c = ZIN0(0); Lag3UD_next(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void VarLag_next(VarLag* unit, int inNumSamples) { float* out = ZOUT(0); float* in = IN(0); float lagTime = ZIN0(1); double slope = unit->m_slope; double level = unit->m_level; int counter = unit->m_counter; int remain = inNumSamples; if (*in != unit->m_in) { counter = (int)(lagTime * SAMPLERATE); counter = unit->m_counter = sc_max(1, counter); slope = unit->m_slope = (*in - unit->m_level) / counter; unit->m_in = *in; unit->m_lagTime = lagTime; } else { if (lagTime != unit->m_lagTime) { float scaleFactor = lagTime / unit->m_lagTime; counter = (int)(unit->m_counter * scaleFactor); counter = unit->m_counter = sc_max(1, counter); slope = unit->m_slope / scaleFactor; unit->m_lagTime = lagTime; } } if (counter > 0) { LOOP( remain, ZXP(out) = level; if (counter > 0) { level += slope; --counter; } else { level = unit->m_in; };) } else { LOOP(remain, ZXP(out) = level); } unit->m_level = level; unit->m_slope = slope; unit->m_counter = counter; } void VarLag_next_1(VarLag* unit, int inNumSamples) { float* out = OUT(0); float in = *IN(0); float lagTime = ZIN0(1); int counter = unit->m_counter; if (in != unit->m_in) { counter = (int)(lagTime * SAMPLERATE); unit->m_counter = counter = sc_max(1, counter); unit->m_slope = (in - unit->m_level) / counter; unit->m_in = in; unit->m_lagTime = lagTime; } { if (lagTime != unit->m_lagTime) { if (counter != 0) { double scaleFactor = lagTime / unit->m_lagTime; counter = (int)(unit->m_counter * scaleFactor); unit->m_counter = counter = sc_max(1, counter); unit->m_slope = unit->m_slope / scaleFactor; } unit->m_lagTime = lagTime; } } *out = unit->m_level; if (unit->m_counter > 0) { unit->m_level += unit->m_slope; --unit->m_counter; } else { unit->m_level = unit->m_in; } } void VarLag_Ctor(VarLag* unit) { if (BUFLENGTH == 1) { SETCALC(VarLag_next_1); } else { SETCALC(VarLag_next); } float in = *IN(0); float lagTime = ZIN0(1); unit->m_level = ZIN0(2); int counter = (int)(lagTime * SAMPLERATE); unit->m_counter = counter = sc_max(1, counter); unit->m_slope = (in - unit->m_level) / counter; unit->m_in = in; unit->m_lagTime = lagTime; ZOUT0(0) = unit->m_level; } ////////////////////////////////////////////////////////////////////////////////////////////////// void OnePole_next_a(OnePole* unit, int inNumSamples) { // printf("OnePole_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); float* b1p = ZIN(1); double y1 = unit->m_y1; LOOP1(inNumSamples, double y0 = ZXP(in); double b1 = ZXP(b1p); ZXP(out) = y1 = y0 + b1 * (y1 - y0);); unit->m_y1 = zapgremlins(y1); } void OnePole_next_k(OnePole* unit, int inNumSamples) { // printf("OnePole_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; unit->m_b1 = ZIN0(1); double y1 = unit->m_y1; if (b1 == unit->m_b1) { if (b1 >= 0.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 - y0);); } else { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 + y0);); } } else { double b1_slope = CALCSLOPE(unit->m_b1, b1); if (b1 >= 0.f && unit->m_b1 >= 0) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 - y0); b1 += b1_slope;); } else if (b1 <= 0.f && unit->m_b1 <= 0) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * (y1 + y0); b1 += b1_slope;); } else { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = (1.f - std::abs(b1)) * y0 + b1 * y1; b1 += b1_slope;); } } unit->m_y1 = zapgremlins(y1); } void OnePole_Ctor(OnePole* unit) { if (INRATE(1) == calc_FullRate) { SETCALC(OnePole_next_a); } else { SETCALC(OnePole_next_k); } unit->m_b1 = ZIN0(1); unit->m_y1 = 0.f; OnePole_next_a(unit, 1); } ////////////////////////////////////////////////////////////////////////////////////////////////// void OneZero_Ctor(OneZero* unit) { SETCALC(OneZero_next); unit->m_b1 = ZIN0(1); unit->m_x1 = ZIN0(0); OneZero_next(unit, 1); } void OneZero_next(OneZero* unit, int inNumSamples) { // printf("OneZero::next\n"); float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; unit->m_b1 = ZIN0(1); double x1 = unit->m_x1; if (b1 == unit->m_b1) { if (b1 >= 0.f) { LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = x0 + b1 * (x1 - x0); x1 = x0;); } else { LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = x0 + b1 * (x1 + x0); x1 = x0;); } } else { double b1_slope = CALCSLOPE(unit->m_b1, b1); if (b1 >= 0.f && unit->m_b1 >= 0) { LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = x0 + b1 * (x1 - x0); x1 = x0; b1 += b1_slope;); } else if (b1 <= 0.f && unit->m_b1 <= 0) { LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = x0 + b1 * (x1 + x0); x1 = x0; b1 += b1_slope;); } else { LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = (1.f - std::abs(b1)) * x0 + b1 * x1; x1 = x0; b1 += b1_slope;); } } unit->m_x1 = x1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Integrator_Ctor(Integrator* unit) { if (INRATE(1) == calc_ScalarRate) SETCALC(Integrator_next_i); else SETCALC(Integrator_next); unit->m_b1 = ZIN0(1); unit->m_y1 = 0.f; ZOUT0(0) = ZIN0(0); // out = in + (coef * out[-1]); out[-1] = 0 } void Integrator_next_i(Integrator* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; double y1 = unit->m_y1; if (b1 == 1.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + y1;); } else if (b1 == 0.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0;); } else { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * y1;); } unit->m_y1 = zapgremlins(y1); } void Integrator_next(Integrator* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double newB1 = ZIN0(1); double b1 = unit->m_b1; double y1 = unit->m_y1; if (b1 == newB1) { if (b1 == 1.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + y1;); } else if (b1 == 0.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0;); } else { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * y1;); } } else { double b1_slope = CALCSLOPE(newB1, b1); LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * y1; b1 += b1_slope;); unit->m_b1 = newB1; } unit->m_y1 = zapgremlins(y1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Decay_Ctor(Decay* unit) { SETCALC(Decay_next); unit->m_decayTime = uninitializedControl; unit->m_b1 = 0.f; unit->m_y1 = 0.f; Decay_next(unit, 1); unit->m_y1 = 0.f; } void Decay_next(Decay* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float decayTime = ZIN0(1); double y1 = unit->m_y1; double b1 = unit->m_b1; if (decayTime == unit->m_decayTime) { if (b1 == 0.f) { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0;); } else { LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * y1;); } } else { unit->m_b1 = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); unit->m_decayTime = decayTime; double b1_slope = CALCSLOPE(unit->m_b1, b1); LOOP1(inNumSamples, double y0 = ZXP(in); ZXP(out) = y1 = y0 + b1 * y1; b1 += b1_slope;); } unit->m_y1 = zapgremlins(y1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Decay2_Ctor(Decay2* unit) { SETCALC(Decay2_next); float attackTime = ZIN0(1); float decayTime = ZIN0(2); unit->m_b1a = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); unit->m_b1b = attackTime == 0.f ? 0.f : exp(log001 / (attackTime * SAMPLERATE)); unit->m_decayTime = decayTime; unit->m_attackTime = attackTime; unit->m_y1a = 0.f; unit->m_y1b = 0.f; Decay2_next(unit, 1); unit->m_y1a = 0.f; unit->m_y1b = 0.f; } void Decay2_next(Decay2* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float attackTime = ZIN0(1); float decayTime = ZIN0(2); double y1a = unit->m_y1a; double y1b = unit->m_y1b; double b1a = unit->m_b1a; double b1b = unit->m_b1b; if (decayTime == unit->m_decayTime && attackTime == unit->m_attackTime) { LOOP1(inNumSamples, double y0 = ZXP(in); y1a = y0 + b1a * y1a; y1b = y0 + b1b * y1b; ZXP(out) = y1a - y1b;); } else { unit->m_decayTime = decayTime; unit->m_attackTime = attackTime; double next_b1a = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); double next_b1b = attackTime == 0.f ? 0.f : exp(log001 / (attackTime * SAMPLERATE)); unit->m_decayTime = decayTime; double b1a_slope = CALCSLOPE(next_b1a, b1a); double b1b_slope = CALCSLOPE(next_b1b, b1b); unit->m_b1a = next_b1a; unit->m_b1b = next_b1b; LOOP1(inNumSamples, double y0 = ZXP(in); y1a = y0 + b1a * y1a; y1b = y0 + b1b * y1b; ZXP(out) = y1a - y1b; b1a += b1a_slope; b1b += b1b_slope;); } unit->m_y1a = y1a; unit->m_y1b = y1b; unit->m_b1a = b1a; unit->m_b1b = b1b; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LeakDC_next_i_4(LeakDC* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; double y1 = unit->m_y1; double x1 = unit->m_x1; LOOP1(inNumSamples / 4, double x00 = ZXP(in); double x01 = ZXP(in); double x02 = ZXP(in); double x03 = ZXP(in); float out0 = y1 = x00 - x1 + b1 * y1; float out1 = y1 = x01 - x00 + b1 * y1; float out2 = y1 = x02 - x01 + b1 * y1; float out3 = y1 = x03 - x02 + b1 * y1; ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2; ZXP(out) = out3; x1 = x03;); unit->m_x1 = x1; unit->m_y1 = zapgremlins(y1); } void LeakDC_next_i(LeakDC* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; double y1 = unit->m_y1; double x1 = unit->m_x1; LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = y1 = x0 - x1 + b1 * y1; x1 = x0;); unit->m_x1 = x1; unit->m_y1 = zapgremlins(y1); } void LeakDC_next(LeakDC* unit, int inNumSamples) { if (ZIN0(1) == unit->m_b1) { if ((inNumSamples & 3) == 0) LeakDC_next_i_4(unit, inNumSamples); else LeakDC_next_i(unit, inNumSamples); } else { float* out = ZOUT(0); float* in = ZIN(0); double b1 = unit->m_b1; unit->m_b1 = ZIN0(1); double y1 = unit->m_y1; double x1 = unit->m_x1; double b1_slope = CALCSLOPE(unit->m_b1, b1); LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = y1 = x0 - x1 + b1 * y1; x1 = x0; b1 += b1_slope;); unit->m_x1 = x1; unit->m_y1 = zapgremlins(y1); } } void LeakDC_next_1(LeakDC* unit, int inNumSamples) { double b1 = unit->m_b1 = ZIN0(1); double y1 = unit->m_y1; double x1 = unit->m_x1; double x0 = ZIN0(0); ZOUT0(0) = y1 = x0 - x1 + b1 * y1; x1 = x0; unit->m_x1 = x1; unit->m_y1 = zapgremlins(y1); } void LeakDC_Ctor(LeakDC* unit) { // printf("LeakDC_Ctor\n"); if (BUFLENGTH == 1) SETCALC(LeakDC_next_1); else { if (INRATE(1) == calc_ScalarRate) { if ((BUFLENGTH & 3) == 0) SETCALC(LeakDC_next_i_4); else SETCALC(LeakDC_next_i); } else SETCALC(LeakDC_next); } unit->m_b1 = 0.0; unit->m_x1 = ZIN0(0); unit->m_y1 = 0.0; LeakDC_next_1(unit, 1); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void TwoPole_Ctor(TwoPole* unit) { // printf("TwoPole_Reset\n"); SETCALC(TwoPole_next); unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_reson = uninitializedControl; PUSH_LOOPVALS TwoPole_next(unit, 1); POP_LOOPVALS } void TwoPole_next(TwoPole* unit, int inNumSamples) { // printf("TwoPole_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float reson = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; if (freq != unit->m_freq || reson != unit->m_reson) { double b1 = unit->m_b1; double b2 = unit->m_b2; double b1_next = 2 * reson * cos(freq * unit->mRate->mRadiansPerSample); double b2_next = -(reson * reson); double b1_slope = (b1_next - b1) * unit->mRate->mFilterSlope; double b2_slope = (b2_next - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, ZXP(out) = y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y1 = ZXP(in) + b1 * y2 + b2 * y0; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, ZXP(out) = y0 = ZXP(in) + b1 * y1 + b2 * y2; y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_reson = reson; unit->m_b1 = b1_next; unit->m_b2 = b2_next; } else { double b1 = unit->m_b1; double b2 = unit->m_b2; LOOP(unit->mRate->mFilterLoops, ZXP(out) = y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y1 = ZXP(in) + b1 * y2 + b2 * y0;); LOOP(unit->mRate->mFilterRemain, ZXP(out) = y0 = ZXP(in) + b1 * y1 + b2 * y2; y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void TwoZero_Ctor(TwoZero* unit) { // printf("TwoZero_Reset\n"); SETCALC(TwoZero_next); unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_x1 = 0.f; unit->m_x2 = 0.f; unit->m_freq = uninitializedControl; unit->m_reson = uninitializedControl; PUSH_LOOPVALS TwoZero_next(unit, 1); POP_LOOPVALS } void TwoZero_next(TwoZero* unit, int inNumSamples) { // printf("TwoZero_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float reson = ZIN0(2); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; if (freq != unit->m_freq || reson != unit->m_reson) { double b1 = unit->m_b1; double b2 = unit->m_b2; double b1_next = -2 * reson * cos(freq * unit->mRate->mRadiansPerSample); double b2_next = (reson * reson); double b1_slope = (b1_next - b1) * unit->mRate->mFilterSlope; double b2_slope = (b2_next - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = x0 + b1 * x1 + b2 * x2; x2 = ZXP(in); ZXP(out) = x2 + b1 * x0 + b2 * x1; x1 = ZXP(in); ZXP(out) = x1 + b1 * x2 + b2 * x0; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = x0 + b1 * x1 + b2 * x2; x2 = x1; x1 = x0;); unit->m_freq = freq; unit->m_reson = reson; unit->m_b1 = b1_next; unit->m_b2 = b2_next; } else { double b1 = unit->m_b1; double b2 = unit->m_b2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = x0 + b1 * x1 + b2 * x2; x2 = ZXP(in); ZXP(out) = x2 + b1 * x0 + b2 * x1; x1 = ZXP(in); ZXP(out) = x1 + b1 * x2 + b2 * x0;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = x0 + b1 * x1 + b2 * x2; x2 = x1; x1 = x0;); } unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void APF_Ctor(APF* unit) { // printf("APF_Reset\n"); SETCALC(APF_next); unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_x1 = 0.f; unit->m_x2 = 0.f; unit->m_freq = uninitializedControl; unit->m_reson = uninitializedControl; PUSH_LOOPVALS APF_next(unit, 1); POP_LOOPVALS } void APF_next(APF* unit, int inNumSamples) { // printf("APF_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float reson = ZIN0(2); double x0, y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double x1 = unit->m_x1; double x2 = unit->m_x2; if (freq != unit->m_freq || reson != unit->m_reson) { double b1 = unit->m_b1; double b2 = unit->m_b2; double b1_next = 2.f * reson * cos(freq * unit->mRate->mRadiansPerSample); double b2_next = -(reson * reson); double b1_slope = (b1_next - b1) * unit->mRate->mFilterSlope; double b2_slope = (b2_next - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = y0 = x0 + b1 * (y1 - x1) + b2 * (y2 - x2); x2 = ZXP(in); ZXP(out) = y2 = x2 + b1 * (y0 - x0) + b2 * (y2 - x1); x1 = ZXP(in); ZXP(out) = y1 = x1 + b1 * (y2 - x2) + b2 * (y2 - x0); b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = y0 = x0 + b1 * (y1 - x1) + b2 * (y2 - x2); y2 = y1; y1 = y0; x2 = x1; x1 = x0;); unit->m_freq = freq; unit->m_reson = reson; unit->m_b1 = b1_next; unit->m_b2 = b2_next; } else { double b1 = unit->m_b1; double b2 = unit->m_b2; LOOP(unit->mRate->mFilterLoops, float in0 = ZXP(in); float in1 = ZXP(in); float in2 = ZXP(in); x0 = in0; float out0 = y0 = x0 + b1 * (y1 - x1) + b2 * (y2 - x2); x2 = in1; float out1 = y2 = x2 + b1 * (y0 - x0) + b2 * (y2 - x1); x1 = in2; float out2 = y1 = x1 + b1 * (y2 - x2) + b2 * (y2 - x0); ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = y0 = x0 + b1 * (y1 - x1) + b2 * (y2 - x2); y2 = y1; y1 = y0; x2 = x1; x1 = x0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LPZ1_Ctor(LPZ1* unit) { // printf("LPZ1_Reset\n"); SETCALC(LPZ1_next); unit->m_x1 = ZIN0(0); LPZ1_next(unit, 1); } void LPZ1_next(LPZ1* unit, int inNumSamples) { // printf("LPZ1_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; LOOP(inNumSamples >> 2, x0 = ZXP(in); float out0 = 0.5 * (x0 + x1); x1 = ZXP(in); float out1 = 0.5 * (x1 + x0); x0 = ZXP(in); float out2 = 0.5 * (x0 + x1); x1 = ZXP(in); float out3 = 0.5 * (x1 + x0); ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2; ZXP(out) = out3;); LOOP(inNumSamples & 3, x0 = ZXP(in); ZXP(out) = 0.5 * (x0 + x1); x1 = x0;); unit->m_x1 = x1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void HPZ1_Ctor(HPZ1* unit) { // printf("HPZ1_Reset\n"); SETCALC(HPZ1_next); unit->m_x1 = ZIN0(0); HPZ1_next(unit, 1); } void HPZ1_next(HPZ1* unit, int inNumSamples) { // printf("HPZ1_next\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; LOOP(inNumSamples >> 2, x0 = ZXP(in); float out0 = 0.5 * (x0 - x1); x1 = ZXP(in); float out1 = 0.5 * (x1 - x0); x0 = ZXP(in); float out2 = 0.5 * (x0 - x1); x1 = ZXP(in); float out3 = 0.5 * (x1 - x0); ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2; ZXP(out) = out3;); LOOP(inNumSamples & 3, x0 = ZXP(in); // printf("%d %d %g %g\n", this, inNumSamples, x0, x1); ZXP(out) = 0.5f * (x0 - x1); x1 = x0;); unit->m_x1 = x1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Slope_Ctor(Slope* unit) { // printf("Slope_Reset\n"); SETCALC(Slope_next); unit->m_x1 = ZIN0(0); // printf("Slope_Reset %g\n", unit->m_x1); Slope_next(unit, 1); } void Slope_next(Slope* unit, int inNumSamples) { // printf("Slope_next_a %g\n", unit->m_x1); float* out = ZOUT(0); float* in = ZIN(0); double x1 = unit->m_x1; double sr = SAMPLERATE; LOOP1(inNumSamples, double x0 = ZXP(in); ZXP(out) = sr * (x0 - x1); x1 = x0;); unit->m_x1 = x1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Delay1_Ctor(Delay1* unit) { SETCALC(Delay1_next); float x1 = IN0(1); unit->m_x1 = x1; ZOUT0(0) = x1; } void Delay1_next(Delay1* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float x0; float x1 = unit->m_x1; LOOP(inNumSamples >> 2, x0 = ZXP(in); ZXP(out) = x1; x1 = ZXP(in); ZXP(out) = x0; x0 = ZXP(in); ZXP(out) = x1; x1 = ZXP(in); ZXP(out) = x0;); LOOP(inNumSamples & 3, x0 = ZXP(in); ZXP(out) = x1; x1 = x0;); unit->m_x1 = x1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Flip_Ctor(Flip* unit) { if (unit->mBufLength & 1) { SETCALC(Flip_next_odd); Flip_next_odd(unit, 1); } else { SETCALC(Flip_next_even); ZOUT0(0) = ZIN0(0); } } void Flip_next_even(Flip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); LOOP(inNumSamples >> 1, ZXP(out) = -ZXP(in); ZXP(out) = ZXP(in);); } void Flip_next_odd(Flip* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); if (unit->mWorld->mBufCounter & 1) { ZXP(out) = ZXP(in); LOOP(inNumSamples >> 1, ZXP(out) = -ZXP(in); ZXP(out) = ZXP(in);); } else { LOOP(inNumSamples >> 1, ZXP(out) = -ZXP(in); ZXP(out) = ZXP(in);); ZXP(out) = -ZXP(in); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Delay2_Ctor(Delay2* unit) { SETCALC(Delay2_next); float x1 = IN0(1); float x2 = IN0(2); unit->m_x1 = x1; unit->m_x2 = x2; ZOUT0(0) = x2; } void Delay2_next(Delay2* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = x2; x2 = ZXP(in); ZXP(out) = x1; x1 = ZXP(in); ZXP(out) = x0;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = x2; x2 = x1; x1 = x0;); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LPZ2_Ctor(LPZ2* unit) { // printf("LPZ2_Reset\n"); SETCALC(LPZ2_next); unit->m_x1 = unit->m_x2 = ZIN0(0); PUSH_LOOPVALS LPZ2_next(unit, 1); POP_LOOPVALS } void LPZ2_next(LPZ2* unit, int inNumSamples) { // printf("LPZ2_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); float out0 = (x0 + 2.0 * x1 + x2) * 0.25; x2 = ZXP(in); float out1 = (x2 + 2.0 * x0 + x1) * 0.25; x1 = ZXP(in); float out2 = (x1 + 2.0 * x2 + x0) * 0.25; ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = (x0 + 2. * x1 + x2) * 0.25; x2 = x1; x1 = x0;); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void HPZ2_Ctor(HPZ2* unit) { // printf("HPZ2_Reset\n"); SETCALC(HPZ2_next); unit->m_x1 = unit->m_x2 = ZIN0(0); PUSH_LOOPVALS HPZ2_next(unit, 1); POP_LOOPVALS } void HPZ2_next(HPZ2* unit, int inNumSamples) { // printf("HPZ2_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); float out0 = (x0 - 2.0 * x1 + x2) * 0.25; x2 = ZXP(in); float out1 = (x2 - 2.0 * x0 + x1) * 0.25; x1 = ZXP(in); float out2 = (x1 - 2.0 * x2 + x0) * 0.25; ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = (x0 - 2.0 * x1 + x2) * 0.25; x2 = x1; x1 = x0;); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BPZ2_Ctor(BPZ2* unit) { // printf("BPZ2_Reset\n"); SETCALC(BPZ2_next); unit->m_x1 = unit->m_x2 = ZIN0(0); PUSH_LOOPVALS BPZ2_next(unit, 1); POP_LOOPVALS } void BPZ2_next(BPZ2* unit, int inNumSamples) { // printf("BPZ2_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = (x0 - x2) * 0.5; x2 = ZXP(in); ZXP(out) = (x2 - x1) * 0.5; x1 = ZXP(in); ZXP(out) = (x1 - x0) * 0.5;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = (x0 - x2) * 0.5; x2 = x1; x1 = x0;); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BRZ2_Ctor(BRZ2* unit) { // printf("BRZ2_Reset\n"); SETCALC(BRZ2_next); unit->m_x1 = unit->m_x2 = ZIN0(0); PUSH_LOOPVALS BRZ2_next(unit, 1); POP_LOOPVALS } void BRZ2_next(BRZ2* unit, int inNumSamples) { // printf("BRZ2_next_a\n"); float* out = ZOUT(0); float* in = ZIN(0); double x0; double x1 = unit->m_x1; double x2 = unit->m_x2; LOOP(unit->mRate->mFilterLoops, x0 = ZXP(in); ZXP(out) = (x0 + x2) * 0.5; x2 = ZXP(in); ZXP(out) = (x2 + x1) * 0.5; x1 = ZXP(in); ZXP(out) = (x1 + x0) * 0.5;); LOOP(unit->mRate->mFilterRemain, x0 = ZXP(in); ZXP(out) = (x0 + x2) * 0.5; x2 = x1; x1 = x0;); unit->m_x1 = x1; unit->m_x2 = x2; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Slew_Ctor(Slew* unit) { // printf("Slew_Reset\n"); SETCALC(Slew_next); unit->mLevel = ZIN0(0); Slew_next(unit, 1); } void Slew_next(Slew* unit, int inNumSamples) { // printf("Slew_next_a\n"); float sampleDur = unit->mRate->mSampleDur; float* out = ZOUT(0); float* in = ZIN(0); float upf = ZIN0(1) * sampleDur; float dnf = 0.f - ZIN0(2) * sampleDur; double level = unit->mLevel; LOOP1(inNumSamples, double slope = ZXP(in) - level; level += sc_clip(slope, dnf, upf); ZXP(out) = level;); unit->mLevel = level; } /*void Slew_next_1(Slew* unit, int inNumSamples) { //printf("Slew_next_a\n"); float *out = ZOUT(0); float in = ZIN0(0); float upf = ZIN0(1); float dnf = ZIN0(2); float level = unit->mLevel; float slope = ZXP(in) - level; if (slope > upf) slope = upf; else if (slope < dnf) slope = dnf; level += slope; ZXP(out) = level; unit->mLevel = level; }*/ //////////////////////////////////////////////////////////////////////////////////////////////////////// void RLPF_Ctor(RLPF* unit) { // printf("RLPF_Reset\n"); if (unit->mBufLength == 1) { SETCALC(RLPF_next_1); } else { SETCALC(RLPF_next); } unit->m_a0 = 0.f; unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_reson = uninitializedControl; RLPF_next_1(unit, 1); } void RLPF_next(RLPF* unit, int inNumSamples) { // printf("RLPF_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float reson = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || reson != unit->m_reson) { double qres = sc_max(0.001, reson); double pfreq = freq * unit->mRate->mRadiansPerSample; double D = tan(pfreq * qres * 0.5); double C = ((1.0 - D) / (1.0 + D)); double cosf = cos(pfreq); double next_b1 = (1.0 + C) * cosf; double next_b2 = -C; double next_a0 = (1.0 + C - next_b1) * .25; // post("%g %g %g %g %g %g %g %g %g %g\n", *freq, pfreq, qres, D, C, cosf, next_b1, next_b2, next_a0, y1, // y2); double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 + 2.0 * y1 + y2; y2 = a0 * ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y2 + 2.0 * y0 + y1; y1 = a0 * ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = y1 + 2.0 * y2 + y0; a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 + 2.0 * y1 + y2; y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_reson = reson; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 + 2.0 * y1 + y2; y2 = a0 * ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y2 + 2.0 * y0 + y1; y1 = a0 * ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = y1 + 2.0 * y2 + y0;); LOOP(unit->mRate->mFilterRemain, y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 + 2.0 * y1 + y2; y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void RLPF_next_1(RLPF* unit, int inNumSamples) { // printf("RLPF_next_1\n"); float in = ZIN0(0); float freq = ZIN0(1); float reson = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || reson != unit->m_reson) { double qres = sc_max(0.001f, reson); double pfreq = freq * unit->mRate->mRadiansPerSample; double D = tan(pfreq * qres * 0.5f); double C = ((1.f - D) / (1.f + D)); double cosf = cos(pfreq); b1 = (1.0 + C) * cosf; b2 = -C; a0 = (1.0 + C - b1) * .25; y0 = a0 * in + b1 * y1 + b2 * y2; ZOUT0(0) = y0 + 2.0 * y1 + y2; y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_reson = reson; unit->m_a0 = a0; unit->m_b1 = b1; unit->m_b2 = b2; } else { y0 = a0 * in + b1 * y1 + b2 * y2; ZOUT0(0) = y0 + 2.0 * y1 + y2; y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void RHPF_Ctor(RHPF* unit) { if (unit->mBufLength == 1) SETCALC(RHPF_next_1); else SETCALC(RHPF_next); unit->m_a0 = 0.; unit->m_b1 = 0.; unit->m_b2 = 0.; unit->m_y1 = 0.; unit->m_y2 = 0.; unit->m_freq = uninitializedControl; unit->m_reson = uninitializedControl; RHPF_next_1(unit, 1); } void RHPF_next(RHPF* unit, int inNumSamples) { // printf("RHPFs_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float reson = ZIN0(2); double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || reson != unit->m_reson) { double qres = sc_max(0.001f, reson); double pfreq = freq * unit->mRate->mRadiansPerSample; double D = tan(pfreq * qres * 0.5f); double C = ((1.0 - D) / (1.0 + D)); double cosf = cos(pfreq); double next_b1 = (1.0 + C) * cosf; double next_b2 = -C; double next_a0 = (1.0 + C + next_b1) * .25; // post("%g %g %g %g %g %g %g %g %g %g\n", *freq, pfreq, qres, D, C, cosf, next_b1, next_b2, next_a0, y1, // y2); double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, double y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 - 2.0 * y1 + y2; y2 = a0 * ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y2 - 2.0 * y0 + y1; y1 = a0 * ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = y1 - 2.0 * y2 + y0; a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, double y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 - 2.0 * y1 + y2; y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_reson = reson; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, double y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 - 2.0 * y1 + y2; y2 = a0 * ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = y2 - 2.0 * y0 + y1; y1 = a0 * ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = y1 - 2.0 * y2 + y0;); LOOP(unit->mRate->mFilterRemain, double y0 = a0 * ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = y0 - 2.0 * y1 + y2; y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void RHPF_next_1(RHPF* unit, int inNumSamples) { // printf("RHPFs_next_1\n"); float in = ZIN0(0); float freq = ZIN0(1); float reson = ZIN0(2); double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || reson != unit->m_reson) { double qres = sc_max(0.001f, reson); double pfreq = freq * unit->mRate->mRadiansPerSample; double D = tan(pfreq * qres * 0.5f); double C = ((1. - D) / (1. + D)); double cosf = cos(pfreq); b1 = (1. + C) * cosf; b2 = -C; a0 = (1. + C + b1) * .25; double y0 = a0 * in + b1 * y1 + b2 * y2; ZOUT0(0) = y0 - 2.0 * y1 + y2; y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_reson = reson; unit->m_a0 = a0; unit->m_b1 = b1; unit->m_b2 = b2; } else { double y0 = a0 * in + b1 * y1 + b2 * y2; ZOUT0(0) = y0 - 2.0 * y1 + y2; y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void LPF_Ctor(LPF* unit) { if (unit->mBufLength == 1) SETCALC(LPF_next_1); else SETCALC(LPF_next); unit->m_a0 = 0.f; unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; LPF_next_1(unit, 1); } void LPF_next(LPF* unit, int inNumSamples) { // printf("LPF_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq) { double pfreq = freq * unit->mRate->mRadiansPerSample * 0.5; double C = 1.f / tan(pfreq); double C2 = C * C; double sqrt2C = C * sqrt2_f; double next_a0 = 1.f / (1.f + sqrt2C + C2); double next_b1 = -2.f * (1.f - C2) * next_a0; double next_b2 = -(1.f - sqrt2C + C2) * next_a0; // post("%g %g %g %g %g %g %g %g %g %g\n", *freq, pfreq, qres, D, C, cosf, next_b1, next_b2, next_a0, y1, // y2); double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 + 2. * y1 + y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 + 2. * y0 + y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 + 2.f * y2 + y0); a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 + 2. * y1 + y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; float out0 = a0 * (y0 + 2. * y1 + y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; float out1 = a0 * (y2 + 2. * y0 + y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; float out2 = a0 * (y1 + 2. * y2 + y0); ZXP(out) = out0; ZXP(out) = out1; ZXP(out) = out2;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 + 2. * y1 + y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void LPF_next_1(LPF* unit, int inNumSamples) { // printf("LPF_next\n"); float in = ZIN0(0); float freq = ZIN0(1); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq) { double pfreq = freq * unit->mRate->mRadiansPerSample * 0.5; double C = 1.f / tan(pfreq); double C2 = C * C; double sqrt2C = C * sqrt2_f; a0 = 1.f / (1.f + sqrt2C + C2); b1 = -2.f * (1.f - C2) * a0; b2 = -(1.f - sqrt2C + C2) * a0; y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 + 2. * y1 + y2); y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_a0 = a0; unit->m_b1 = b1; unit->m_b2 = b2; } else { y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 + 2. * y1 + y2); y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void HPF_Ctor(HPF* unit) { if (unit->mBufLength == 1) SETCALC(HPF_next_1); else SETCALC(HPF_next); unit->m_a0 = 0.; unit->m_b1 = 0.; unit->m_b2 = 0.; unit->m_y1 = 0.; unit->m_y2 = 0.; unit->m_freq = uninitializedControl; HPF_next_1(unit, 1); } void HPF_next(HPF* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq) { double pfreq = freq * unit->mRate->mRadiansPerSample * 0.5; double C = tan(pfreq); double C2 = C * C; double sqrt2C = C * sqrt2_f; double next_a0 = 1. / (1. + sqrt2C + C2); double next_b1 = 2. * (1. - C2) * next_a0; double next_b2 = -(1. - sqrt2C + C2) * next_a0; // post("%g %g %g %g %g %g %g %g %g %g\n", *freq, pfreq, qres, D, C, cosf, next_b1, next_b2, next_a0, y1, // y2); double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, double in0 = ZXP(in); double in1 = ZXP(in); double in2 = ZXP(in); double y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - 2. * y1 + y2); y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - 2. * y0 + y1); y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - 2. * y2 + y0); a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, double y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - 2. * y1 + y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, double in0 = ZXP(in); double in1 = ZXP(in); double in2 = ZXP(in); double y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - 2. * y1 + y2); y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - 2. * y0 + y1); y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - 2. * y2 + y0);); LOOP(unit->mRate->mFilterRemain, double y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - 2. * y1 + y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void HPF_next_1(HPF* unit, int inNumSamples) { double in = ZIN0(0); double freq = ZIN0(1); double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq) { double pfreq = freq * unit->mRate->mRadiansPerSample * 0.5f; double C = tan(pfreq); double C2 = C * C; double sqrt2C = C * sqrt2_f; a0 = 1. / (1. + sqrt2C + C2); b1 = 2. * (1. - C2) * a0; b2 = -(1. - sqrt2C + C2) * a0; double y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 - 2. * y1 + y2); y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_a0 = a0; unit->m_b1 = b1; unit->m_b2 = b2; } else { double y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 - 2. * y1 + y2); y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BPF_Ctor(BPF* unit) { // printf("BPF_Reset\n"); if (unit->mBufLength == 1) { SETCALC(BPF_next_1); } else { SETCALC(BPF_next); }; unit->m_a0 = 0.f; unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_bw = uninitializedControl; BPF_next_1(unit, 1); } void BPF_next(BPF* unit, int inNumSamples) { // printf("BPF_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float bw = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || bw != unit->m_bw) { double pfreq = freq * unit->mRate->mRadiansPerSample; double pbw = bw * pfreq * 0.5f; double C = 1.f / tan(pbw); double D = 2.f * cos(pfreq); double next_a0 = 1.f / (1.f + C); double next_b1 = C * D * next_a0; double next_b2 = (1.f - C) * next_a0; double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0); a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_bw = bw; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0);); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BPF_next_1(BPF* unit, int inNumSamples) { // printf("BPF_next_1\n"); float in = ZIN0(0); float freq = ZIN0(1); float bw = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || bw != unit->m_bw) { double pfreq = freq * unit->mRate->mRadiansPerSample; double pbw = bw * pfreq * 0.5; double C = 1.f / tan(pbw); double D = 2.f * cos(pfreq); double a0 = 1.f / (1.f + C); double b1 = C * D * a0; double b2 = (1.f - C) * a0; y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 - y2); y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_bw = bw; unit->m_a0 = a0; unit->m_b1 = b1; unit->m_b2 = b2; } else { y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * (y0 - y2); y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void BRF_Ctor(BRF* unit) { // printf("BRF_Reset\n"); if (unit->mBufLength == 1) { SETCALC(BRF_next_1); } else { SETCALC(BRF_next); }; unit->m_a0 = 0.f; unit->m_a1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_bw = uninitializedControl; BRF_next_1(unit, 1); } void BRF_next(BRF* unit, int inNumSamples) { // printf("BRF_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float bw = ZIN0(2); double ay; double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double a1 = unit->m_a1; double b2 = unit->m_b2; if (freq != unit->m_freq || bw != unit->m_bw) { double pfreq = freq * unit->mRate->mRadiansPerSample; double pbw = bw * pfreq * 0.5f; double C = tan(pbw); double D = 2.f * cos(pfreq); double next_a0 = 1.f / (1.f + C); double next_a1 = -D * next_a0; double next_b2 = (1.f - C) * next_a0; double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double a1_slope = (next_a1 - a1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, ay = a1 * y1; y0 = ZXP(in) - ay - b2 * y2; ZXP(out) = a0 * (y0 + y2) + ay; ay = a1 * y0; y2 = ZXP(in) - ay - b2 * y1; ZXP(out) = a0 * (y2 + y1) + ay; ay = a1 * y2; y1 = ZXP(in) - ay - b2 * y0; ZXP(out) = a0 * (y1 + y0) + ay; a0 += a0_slope; a1 += a1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, ay = a1 * y1; y0 = ZXP(in) - ay - b2 * y2; ZXP(out) = a0 * (y0 + y2) + ay; y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_bw = bw; unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_b2 = next_b2; } else { LOOP(unit->mRate->mFilterLoops, ay = a1 * y1; y0 = ZXP(in) - ay - b2 * y2; ZXP(out) = a0 * (y0 + y2) + ay; ay = a1 * y0; y2 = ZXP(in) - ay - b2 * y1; ZXP(out) = a0 * (y2 + y1) + ay; ay = a1 * y2; y1 = ZXP(in) - ay - b2 * y0; ZXP(out) = a0 * (y1 + y0) + ay;); LOOP(unit->mRate->mFilterRemain, ay = a1 * y1; y0 = ZXP(in) - ay - b2 * y2; ZXP(out) = a0 * (y0 + y2) + ay; y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BRF_next_1(BRF* unit, int inNumSamples) { // printf("BRF_next_1\n"); float in = ZIN0(0); float freq = ZIN0(1); float bw = ZIN0(2); double ay; double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double a1 = unit->m_a1; double b2 = unit->m_b2; if (freq != unit->m_freq || bw != unit->m_bw) { double pfreq = freq * unit->mRate->mRadiansPerSample; double pbw = bw * pfreq * 0.5f; double C = tan(pbw); double D = 2.f * cos(pfreq); double a0 = 1.f / (1.f + C); double a1 = -D * a0; double b2 = (1.f - C) * a0; ay = a1 * y1; y0 = in - ay - b2 * y2; ZOUT0(0) = a0 * (y0 + y2) + ay; y2 = y1; y1 = y0; unit->m_freq = freq; unit->m_bw = bw; unit->m_a0 = a0; unit->m_a1 = a1; unit->m_b2 = b2; } else { ay = a1 * y1; y0 = in - ay - b2 * y2; ZOUT0(0) = a0 * (y0 + y2) + ay; y2 = y1; y1 = y0; } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void MidEQ_Ctor(MidEQ* unit) { // printf("MidEQ_Reset\n"); SETCALC(MidEQ_next); unit->m_a0 = 0.f; unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_bw = uninitializedControl; unit->m_db = uninitializedControl; PUSH_LOOPVALS MidEQ_next(unit, 1); POP_LOOPVALS } void MidEQ_next(MidEQ* unit, int inNumSamples) { // printf("MidEQ_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float bw = ZIN0(2); float db = ZIN0(3); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || bw != unit->m_bw || db != unit->m_db) { double amp = sc_dbamp(db) - 1.0f; double pfreq = freq * unit->mRate->mRadiansPerSample; double pbw = bw * pfreq * 0.5f; double C = 1.f / tan(pbw); double D = 2.f * cos(pfreq); double next_a0 = 1.f / (1.f + C); double next_b1 = C * D * next_a0; double next_b2 = (1.f - C) * next_a0; next_a0 *= amp; double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; double zin; LOOP(unit->mRate->mFilterLoops, zin = ZXP(in); y0 = zin + b1 * y1 + b2 * y2; ZXP(out) = zin + a0 * (y0 - y2); zin = ZXP(in); y2 = zin + b1 * y0 + b2 * y1; ZXP(out) = zin + a0 * (y2 - y1); zin = ZXP(in); y1 = zin + b1 * y2 + b2 * y0; ZXP(out) = zin + a0 * (y1 - y0); a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, zin = ZXP(in); y0 = zin + b1 * y1 + b2 * y2; ZXP(out) = zin + a0 * (y0 - y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_bw = bw; unit->m_db = db; unit->m_a0 = next_a0; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else { double zin; LOOP(unit->mRate->mFilterLoops, zin = ZXP(in); y0 = zin + b1 * y1 + b2 * y2; ZXP(out) = zin + a0 * (y0 - y2); zin = ZXP(in); y2 = zin + b1 * y0 + b2 * y1; ZXP(out) = zin + a0 * (y2 - y1); zin = ZXP(in); y1 = zin + b1 * y2 + b2 * y0; ZXP(out) = zin + a0 * (y1 - y0);); LOOP(unit->mRate->mFilterRemain, zin = ZXP(in); y0 = zin + b1 * y1 + b2 * y2; ZXP(out) = zin + a0 * (y0 - y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// static void Median_InitMedian(Median* unit, long size, float value); static float Median_InsertMedian(Median* unit, float value); void Median_Ctor(Median* unit) { // printf("Median_Reset\n"); SETCALC(Median_next); float in = ZIN0(1); unit->m_medianSize = sc_clip((int)ZIN0(0), 0, kMAXMEDIANSIZE); Median_InitMedian(unit, unit->m_medianSize, in); ZOUT0(0) = Median_InsertMedian(unit, in); } float Median_InsertMedian(Median* unit, float value) { long pos = -1; // keeps a sorted list of the previous n=size values // the oldest is removed and the newest is inserted. // values between the oldest and the newest are shifted over by one. // values and ages are both arrays that are 'size' long. // the median value is always values[size>>1] long last = unit->m_medianSize - 1; // find oldest bin and age the other bins. for (int i = 0; i < unit->m_medianSize; ++i) { if (unit->m_medianAge[i] == last) { // is it the oldest bin ? pos = i; } else { unit->m_medianAge[i]++; // age the bin } } // move values to fill in place of the oldest and make a space for the newest // search lower if value is too small for the open space while (pos != 0 && value < unit->m_medianValue[pos - 1]) { unit->m_medianValue[pos] = unit->m_medianValue[pos - 1]; unit->m_medianAge[pos] = unit->m_medianAge[pos - 1]; pos--; } // search higher if value is too big for the open space while (pos != last && value > unit->m_medianValue[pos + 1]) { unit->m_medianValue[pos] = unit->m_medianValue[pos + 1]; unit->m_medianAge[pos] = unit->m_medianAge[pos + 1]; pos++; } unit->m_medianValue[pos] = value; unit->m_medianAge[pos] = 0; // this is the newest bin, age = 0 return unit->m_medianValue[unit->m_medianSize >> 1]; } void Median_InitMedian(Median* unit, long size, float value) { // initialize the arrays with the first value unit->m_medianSize = size; for (int i = 0; i < size; ++i) { unit->m_medianValue[i] = value; unit->m_medianAge[i] = i; } } void Median_next(Median* unit, int inNumSamples) { // printf("Median_next_a\n"); float* out = ZOUT(0); float* in = ZIN(1); LOOP1(inNumSamples, ZXP(out) = Median_InsertMedian(unit, ZXP(in));); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Resonz_Ctor(Resonz* unit) { // printf("Resonz_Reset\n"); SETCALC(Resonz_next); unit->m_a0 = 0.f; unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_rq = 0.f; PUSH_LOOPVALS Resonz_next(unit, 1); POP_LOOPVALS } void Resonz_next(Resonz* unit, int inNumSamples) { // printf("Resonz_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float rq = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || rq != unit->m_rq) { double ffreq = freq * unit->mRate->mRadiansPerSample; double B = ffreq * rq; double R = 1.f - B * 0.5f; double twoR = 2.f * R; double R2 = R * R; double cost = (twoR * cos(ffreq)) / (1.f + R2); double b1_next = twoR * cost; double b2_next = -R2; double a0_next = (1.f - R2) * 0.5f; double a0_slope = (a0_next - a0) * unit->mRate->mFilterSlope; double b1_slope = (b1_next - b1) * unit->mRate->mFilterSlope; double b2_slope = (b2_next - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0); a0 += a0_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_rq = rq; unit->m_a0 = a0_next; unit->m_b1 = b1_next; unit->m_b2 = b2_next; } else { LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0);); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Ringz_Ctor(Ringz* unit) { // printf("Ringz_ctor\n"); SETCALC(Ringz_next); unit->m_b1 = 0.f; unit->m_b2 = 0.f; unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_freq = uninitializedControl; unit->m_decayTime = 0.f; PUSH_LOOPVALS Ringz_next(unit, 1); POP_LOOPVALS } void Ringz_next(Ringz* unit, int inNumSamples) { // printf("Ringz_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float decayTime = ZIN0(2); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = 0.5f; double b1 = unit->m_b1; double b2 = unit->m_b2; if (freq != unit->m_freq || decayTime != unit->m_decayTime) { double ffreq = freq * unit->mRate->mRadiansPerSample; double R = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); double twoR = 2.f * R; double R2 = R * R; double cost = (twoR * cos(ffreq)) / (1.f + R2); double b1_next = twoR * cost; double b2_next = -R2; double b1_slope = (b1_next - b1) * unit->mRate->mFilterSlope; double b2_slope = (b2_next - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0); b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); unit->m_freq = freq; unit->m_decayTime = decayTime; unit->m_b1 = b1_next; unit->m_b2 = b2_next; } else { LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * (y2 - y1); y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * (y1 - y0);); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * (y0 - y2); y2 = y1; y1 = y0;); } unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Formlet_Ctor(Formlet* unit) { // printf("Formlet_Reset\n"); if (unit->mBufLength == 1) { SETCALC(Formlet_next_1); } else { SETCALC(Formlet_next); }; unit->m_b01 = 0.f; unit->m_b02 = 0.f; unit->m_y01 = 0.f; unit->m_y02 = 0.f; unit->m_b11 = 0.f; unit->m_b12 = 0.f; unit->m_y11 = 0.f; unit->m_y12 = 0.f; unit->m_freq = uninitializedControl; unit->m_attackTime = uninitializedControl; unit->m_decayTime = uninitializedControl; Formlet_next_1(unit, 1); } void Formlet_next(Formlet* unit, int inNumSamples) { // printf("Formlet_next\n"); float* out = ZOUT(0); float* in = ZIN(0); float freq = ZIN0(1); float attackTime = ZIN0(2); float decayTime = ZIN0(3); double y00; double y10; double y01 = unit->m_y01; double y11 = unit->m_y11; double y02 = unit->m_y02; double y12 = unit->m_y12; double b01 = unit->m_b01; double b11 = unit->m_b11; double b02 = unit->m_b02; double b12 = unit->m_b12; double ain; if (freq != unit->m_freq || decayTime != unit->m_decayTime || attackTime != unit->m_attackTime) { double ffreq = freq * unit->mRate->mRadiansPerSample; double R = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); double twoR = 2.f * R; double R2 = R * R; double cost = (twoR * cos(ffreq)) / (1.f + R2); double b01_next = twoR * cost; double b02_next = -R2; double b01_slope = (b01_next - b01) * unit->mRate->mFilterSlope; double b02_slope = (b02_next - b02) * unit->mRate->mFilterSlope; R = attackTime == 0.f ? 0.f : exp(log001 / (attackTime * SAMPLERATE)); twoR = 2.f * R; R2 = R * R; cost = (twoR * cos(ffreq)) / (1.f + R2); double b11_next = twoR * cost; double b12_next = -R2; double b11_slope = (b11_next - b11) * unit->mRate->mFilterSlope; double b12_slope = (b12_next - b12) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, ain = ZXP(in); y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZXP(out) = 0.25 * ((y00 - y02) - (y10 - y12)); ain = ZXP(in); y02 = ain + b01 * y00 + b02 * y01; y12 = ain + b11 * y10 + b12 * y11; ZXP(out) = 0.25 * ((y02 - y01) - (y12 - y11)); ain = ZXP(in); y01 = ain + b01 * y02 + b02 * y00; y11 = ain + b11 * y12 + b12 * y10; ZXP(out) = 0.25 * ((y01 - y00) - (y11 - y10)); b01 += b01_slope; b02 += b02_slope; b11 += b11_slope; b12 += b12_slope;); LOOP(unit->mRate->mFilterRemain, ain = ZXP(in); y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZXP(out) = 0.25 * ((y00 - y02) - (y10 - y12)); y02 = y01; y01 = y00; y12 = y11; y11 = y10;); unit->m_freq = freq; unit->m_attackTime = attackTime; unit->m_decayTime = decayTime; unit->m_b01 = b01_next; unit->m_b02 = b02_next; unit->m_b11 = b11_next; unit->m_b12 = b12_next; } else { LOOP(unit->mRate->mFilterLoops, ain = ZXP(in); y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZXP(out) = 0.25 * ((y00 - y02) - (y10 - y12)); ain = ZXP(in); y02 = ain + b01 * y00 + b02 * y01; y12 = ain + b11 * y10 + b12 * y11; ZXP(out) = 0.25 * ((y02 - y01) - (y12 - y11)); ain = ZXP(in); y01 = ain + b01 * y02 + b02 * y00; y11 = ain + b11 * y12 + b12 * y10; ZXP(out) = 0.25 * ((y01 - y00) - (y11 - y10));); LOOP(unit->mRate->mFilterRemain, ain = ZXP(in); y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZXP(out) = 0.25 * ((y00 - y02) - (y10 - y12)); y02 = y01; y01 = y00; y12 = y11; y11 = y10;); } unit->m_y01 = y01; unit->m_y02 = y02; unit->m_y11 = y11; unit->m_y12 = y12; } void Formlet_next_1(Formlet* unit, int inNumSamples) { // printf("Formlet_next\n"); float in = ZIN0(0); float freq = ZIN0(1); float attackTime = ZIN0(2); float decayTime = ZIN0(3); double y00; double y10; double y01 = unit->m_y01; double y11 = unit->m_y11; double y02 = unit->m_y02; double y12 = unit->m_y12; double b01 = unit->m_b01; double b11 = unit->m_b11; double b02 = unit->m_b02; double b12 = unit->m_b12; double ain; if (freq != unit->m_freq || decayTime != unit->m_decayTime || attackTime != unit->m_attackTime) { double ffreq = freq * unit->mRate->mRadiansPerSample; double R = decayTime == 0.f ? 0.f : exp(log001 / (decayTime * SAMPLERATE)); double twoR = 2.f * R; double R2 = R * R; double cost = (twoR * cos(ffreq)) / (1.f + R2); b01 = twoR * cost; b02 = -R2; R = attackTime == 0.f ? 0.f : exp(log001 / (attackTime * SAMPLERATE)); twoR = 2.f * R; R2 = R * R; cost = (twoR * cos(ffreq)) / (1.f + R2); b11 = twoR * cost; b12 = -R2; ain = in; y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZOUT0(0) = 0.25f * ((y00 - y02) - (y10 - y12)); y02 = y01; y01 = y00; y12 = y11; y11 = y10; unit->m_freq = freq; unit->m_attackTime = attackTime; unit->m_decayTime = decayTime; unit->m_b01 = b01; unit->m_b02 = b02; unit->m_b11 = b11; unit->m_b12 = b12; } else { ain = in; y00 = ain + b01 * y01 + b02 * y02; y10 = ain + b11 * y11 + b12 * y12; ZOUT0(0) = 0.25f * ((y00 - y02) - (y10 - y12)); y02 = y01; y01 = y00; y12 = y11; y11 = y10; } unit->m_y01 = y01; unit->m_y02 = y02; unit->m_y11 = y11; unit->m_y12 = y12; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void FOS_Ctor(FOS* unit) { // printf("FOS_Reset\n"); if (unit->mBufLength == 1) { SETCALC(FOS_next_1); } else { if (INRATE(1) == calc_FullRate && INRATE(2) == calc_FullRate && INRATE(3) == calc_FullRate) { SETCALC(FOS_next_a); } else { SETCALC(FOS_next_k); } }; unit->m_y1 = 0.f; unit->m_a0 = ZIN0(1); unit->m_a1 = ZIN0(2); unit->m_b1 = ZIN0(3); FOS_next_1(unit, 1); } void FOS_next_a(FOS* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* a0 = ZIN(1); float* a1 = ZIN(2); float* b1 = ZIN(3); double y1 = unit->m_y1; LOOP1(inNumSamples, double y0 = ZXP(in) + ZXP(b1) * y1; ZXP(out) = ZXP(a0) * y0 + ZXP(a1) * y1; y1 = y0;); unit->m_y1 = zapgremlins(y1); } void FOS_next_1(FOS* unit, int inNumSamples) { float in = ZIN0(0); float a0 = ZIN0(1); float a1 = ZIN0(2); float b1 = ZIN0(3); double y1 = unit->m_y1; double y0 = in + b1 * y1; ZOUT0(0) = a0 * y0 + a1 * y1; y1 = y0; unit->m_y1 = zapgremlins(y1); } void FOS_next_k(FOS* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_a0 = ZIN0(1); float next_a1 = ZIN0(2); float next_b1 = ZIN0(3); double y1 = unit->m_y1; double a0 = unit->m_a0; double a1 = unit->m_a1; double b1 = unit->m_b1; double a0_slope = CALCSLOPE(next_a0, a0); double a1_slope = CALCSLOPE(next_a1, a1); double b1_slope = CALCSLOPE(next_b1, b1); LOOP1(inNumSamples, double y0 = ZXP(in) + b1 * y1; ZXP(out) = a0 * y0 + a1 * y1; y1 = y0; a0 += a0_slope; a1 += a1_slope; b1 += b1_slope;); unit->m_y1 = zapgremlins(y1); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_b1 = next_b1; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void SOS_Ctor(SOS* unit) { // printf("SOS_Reset\n"); if (unit->mBufLength != 1) { if (INRATE(1) == calc_FullRate && INRATE(2) == calc_FullRate && INRATE(3) == calc_FullRate && INRATE(4) == calc_FullRate && INRATE(5) == calc_FullRate) { SETCALC(SOS_next_a); } else if (INRATE(1) == calc_ScalarRate && INRATE(2) == calc_ScalarRate && INRATE(3) == calc_ScalarRate && INRATE(4) == calc_ScalarRate && INRATE(5) == calc_ScalarRate) { SETCALC(SOS_next_i); } else { SETCALC(SOS_next_k); } } else { SETCALC(SOS_next_1); // printf("SOS_next_1\n"); } unit->m_y1 = 0.f; unit->m_y2 = 0.f; unit->m_a0 = ZIN0(1); unit->m_a1 = ZIN0(2); unit->m_a2 = ZIN0(3); unit->m_b1 = ZIN0(4); unit->m_b2 = ZIN0(5); SOS_next_1(unit, 1); } void SOS_next_a(SOS* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* a0 = ZIN(1); float* a1 = ZIN(2); float* a2 = ZIN(3); float* b1 = ZIN(4); float* b2 = ZIN(5); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; LOOP(unit->mRate->mFilterLoops, y0 = ZXP(in) + ZXP(b1) * y1 + ZXP(b2) * y2; ZXP(out) = ZXP(a0) * y0 + ZXP(a1) * y1 + ZXP(a2) * y2; y2 = ZXP(in) + ZXP(b1) * y0 + ZXP(b2) * y1; ZXP(out) = ZXP(a0) * y2 + ZXP(a1) * y0 + ZXP(a2) * y1; y1 = ZXP(in) + ZXP(b1) * y2 + ZXP(b2) * y0; ZXP(out) = ZXP(a0) * y1 + ZXP(a1) * y2 + ZXP(a2) * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + ZXP(b1) * y1 + ZXP(b2) * y2; ZXP(out) = ZXP(a0) * y0 + ZXP(a1) * y1 + ZXP(a2) * y2; y2 = y1; y1 = y0;); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void SOS_next_k(SOS* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float next_a0 = ZIN0(1); float next_a1 = ZIN0(2); float next_a2 = ZIN0(3); float next_b1 = ZIN0(4); float next_b2 = ZIN0(5); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double a1 = unit->m_a1; double a2 = unit->m_a2; double b1 = unit->m_b1; double b2 = unit->m_b2; double a0_slope = (next_a0 - a0) * unit->mRate->mFilterSlope; double a1_slope = (next_a1 - a1) * unit->mRate->mFilterSlope; double a2_slope = (next_a2 - a2) * unit->mRate->mFilterSlope; double b1_slope = (next_b1 - b1) * unit->mRate->mFilterSlope; double b2_slope = (next_b2 - b2) * unit->mRate->mFilterSlope; LOOP(unit->mRate->mFilterLoops, float in0 = ZXP(in); float in1 = ZXP(in); float in2 = ZXP(in); y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0; a0 += a0_slope; a1 += a1_slope; a2 += a2_slope; b1 += b1_slope; b2 += b2_slope;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0;); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void SOS_next_i(SOS* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; double a0 = unit->m_a0; double a1 = unit->m_a1; double a2 = unit->m_a2; double b1 = unit->m_b1; double b2 = unit->m_b2; LOOP(unit->mRate->mFilterLoops, float in0 = ZXP(in); float in1 = ZXP(in); float in2 = ZXP(in); y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0;); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void SOS_next_1(SOS* unit, int inNumSamples) // optimized for SOS.kr { float in = ZIN0(0); float a0 = ZIN0(1); float a1 = ZIN0(2); float a2 = ZIN0(3); float b1 = ZIN0(4); float b2 = ZIN0(5); double y0; double y1 = unit->m_y1; double y2 = unit->m_y2; y0 = in + b1 * y1 + b2 * y2; ZOUT0(0) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Compander_Ctor(Compander* unit) { // printf("Compander_Reset\n"); SETCALC(Compander_next); unit->m_clamp = 0.f; unit->m_clampcoef = 0.f; unit->m_relax = 0.f; unit->m_relaxcoef = 0.f; unit->m_prevmaxval = 0.f; unit->m_gain = 0.f; Compander_next(unit, 1); } void Compander_next(Compander* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* control = ZIN(1); float thresh = ZIN0(2); float slope_below = ZIN0(3); float slope_above = ZIN0(4); float clamp = ZIN0(5); float relax = ZIN0(6); if (clamp != unit->m_clamp) { unit->m_clampcoef = clamp == 0.0 ? 0.0 : exp(log1 / (clamp * SAMPLERATE)); unit->m_clamp = clamp; } if (relax != unit->m_relax) { unit->m_relaxcoef = relax == 0.0 ? 0.0 : exp(log1 / (relax * SAMPLERATE)); unit->m_relax = relax; } float gain = unit->m_gain; float relaxcoef = unit->m_relaxcoef; float clampcoef = unit->m_clampcoef; float prevmaxval = unit->m_prevmaxval; float val; LOOP1( inNumSamples, val = std::abs(ZXP(control)); if (val < prevmaxval) { val = val + (prevmaxval - val) * relaxcoef; } else { val = val + (prevmaxval - val) * clampcoef; } prevmaxval = val;); unit->m_prevmaxval = prevmaxval; float next_gain; //,absx; if (prevmaxval < thresh) { if (slope_below == 1.f) { next_gain = 1.f; } else { next_gain = pow(prevmaxval / thresh, slope_below - 1.f); // blows up here float32 absx = std::abs(next_gain); // zap gremlins, but returns 0. if gain is too small and 1. if gain is too big next_gain = (absx < (float32)1e-15) ? (float32)0. : (absx > (float32)1e15) ? (float32)1. : next_gain; } } else { if (slope_above == 1.f) { next_gain = 1.f; } else { next_gain = pow(prevmaxval / thresh, slope_above - 1.f); } } float gain_slope = CALCSLOPE(next_gain, gain); LOOP1(inNumSamples, ZXP(out) = ZXP(in) * gain; gain += gain_slope;); unit->m_gain = gain; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Normalizer_Dtor(Normalizer* unit) { RTFree(unit->mWorld, unit->m_table); } void Normalizer_Ctor(Normalizer* unit) { SETCALC(Normalizer_next); // printf("Normalizer_Reset\n"); float dur = ZIN0(2); unit->m_bufsize = (long)(ceil(dur * SAMPLERATE)); long allocsize = unit->m_bufsize * 3; // allocsize = NEXTPOWEROFTWO(allocsize); unit->m_table = (float*)RTAlloc(unit->mWorld, allocsize * sizeof(float)); ClearUnitIfMemFailed(unit->m_table); unit->m_pos = 0; unit->m_flips = 0; unit->m_level = 1.f; unit->m_slope = 0.f; unit->m_prevmaxval = 0.0; unit->m_curmaxval = 0.0; unit->m_slopefactor = 1.f / unit->m_bufsize; unit->m_xinbuf = unit->m_table - ZOFF; unit->m_xmidbuf = unit->m_xinbuf + unit->m_bufsize; unit->m_xoutbuf = unit->m_xmidbuf + unit->m_bufsize; Normalizer_next(unit, 1); } void Normalizer_next(Normalizer* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float amp = ZIN0(1); long pos = unit->m_pos; float slope = unit->m_slope; float level = unit->m_level; float curmaxval = unit->m_curmaxval; float val; long bufsize = unit->m_bufsize; long buf_remain = bufsize - pos; long remain = inNumSamples; while (remain > 0) { long nsmps = sc_min(remain, buf_remain); float* xinbuf = unit->m_xinbuf + pos; float* xoutbuf = unit->m_xoutbuf + pos; if (unit->m_flips >= 2) { LOOP(nsmps, ZXP(xinbuf) = val = ZXP(in); ZXP(out) = level * ZXP(xoutbuf); level += slope; val = std::abs(val); if (val > curmaxval) curmaxval = val;); } else { LOOP(nsmps, ZXP(xinbuf) = val = ZXP(in); ZXP(out) = 0.f; level += slope; val = std::abs(val); if (val > curmaxval) curmaxval = val;); } pos += nsmps; if (pos >= bufsize) { pos = 0; buf_remain = bufsize; float maxval2 = sc_max(unit->m_prevmaxval, curmaxval); unit->m_prevmaxval = curmaxval; unit->m_curmaxval = curmaxval = 0.f; float next_level; if (maxval2 <= 0.00001f) next_level = 100000.f * amp; else next_level = amp / maxval2; slope = unit->m_slope = (next_level - level) * unit->m_slopefactor; float* temp = unit->m_xoutbuf; unit->m_xoutbuf = unit->m_xmidbuf; unit->m_xmidbuf = unit->m_xinbuf; unit->m_xinbuf = temp; unit->m_flips++; } remain -= nsmps; } unit->m_pos = pos; unit->m_level = level; unit->m_curmaxval = curmaxval; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Limiter_Dtor(Limiter* unit) { RTFree(unit->mWorld, unit->m_table); } void Limiter_Ctor(Limiter* unit) { // printf("Limiter_Reset\n"); SETCALC(Limiter_next); float dur = ZIN0(2); unit->m_bufsize = (long)(ceil(dur * SAMPLERATE)); long allocsize = unit->m_bufsize * 3; allocsize = NEXTPOWEROFTWO(allocsize); unit->m_table = (float*)RTAlloc(unit->mWorld, allocsize * sizeof(float)); ClearUnitIfMemFailed(unit->m_table); unit->m_flips = 0; unit->m_pos = 0; unit->m_slope = 0.f; unit->m_level = 1.f; unit->m_prevmaxval = 0.0; unit->m_curmaxval = 0.0; unit->m_slopefactor = 1.f / unit->m_bufsize; unit->m_xinbuf = unit->m_table - ZOFF; unit->m_xmidbuf = unit->m_xinbuf + unit->m_bufsize; unit->m_xoutbuf = unit->m_xmidbuf + unit->m_bufsize; Limiter_next(unit, 1); } void Limiter_next(Limiter* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float amp = ZIN0(1); long pos = unit->m_pos; float slope = unit->m_slope; float level = unit->m_level; float curmaxval = unit->m_curmaxval; float val; long bufsize = unit->m_bufsize; long buf_remain = bufsize - pos; long remain = inNumSamples; while (remain > 0) { long nsmps = sc_min(remain, buf_remain); float* xinbuf = unit->m_xinbuf + pos; float* xoutbuf = unit->m_xoutbuf + pos; if (unit->m_flips >= 2) { LOOP(nsmps, ZXP(xinbuf) = val = ZXP(in); ZXP(out) = level * ZXP(xoutbuf); level += slope; val = std::abs(val); if (val > curmaxval) curmaxval = val;); } else { LOOP(nsmps, ZXP(xinbuf) = val = ZXP(in); ZXP(out) = 0.f; level += slope; val = std::abs(val); if (val > curmaxval) curmaxval = val;); } pos += nsmps; if (pos >= bufsize) { pos = 0; buf_remain = bufsize; float maxval2 = sc_max(unit->m_prevmaxval, curmaxval); unit->m_prevmaxval = curmaxval; unit->m_curmaxval = curmaxval = 0.f; float next_level; if (maxval2 > amp) next_level = amp / maxval2; else next_level = 1.0; slope = unit->m_slope = (next_level - level) * unit->m_slopefactor; float* temp = unit->m_xoutbuf; unit->m_xoutbuf = unit->m_xmidbuf; unit->m_xmidbuf = unit->m_xinbuf; unit->m_xinbuf = temp; unit->m_flips++; } remain -= nsmps; } unit->m_pos = pos; unit->m_level = level; unit->m_curmaxval = curmaxval; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void Amplitude_Ctor(Amplitude* unit) { if (INRATE(1) != calc_ScalarRate || INRATE(2) != calc_ScalarRate) { if (INRATE(0) == calc_FullRate && unit->mCalcRate == calc_BufRate) { SETCALC(Amplitude_next_atok_kk); } else { SETCALC(Amplitude_next_kk); } } else { if (INRATE(0) == calc_FullRate && unit->mCalcRate == calc_BufRate) { SETCALC(Amplitude_next_atok); } else { SETCALC(Amplitude_next); } } float clamp = ZIN0(1); unit->m_clampcoef = clamp == 0.0 ? 0.0 : exp(log1 / (clamp * SAMPLERATE)); float relax = ZIN0(2); unit->m_relaxcoef = relax == 0.0 ? 0.0 : exp(log1 / (relax * SAMPLERATE)); unit->m_previn = std::abs(ZIN0(0)); Amplitude_next(unit, 1); } void Amplitude_next(Amplitude* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float relaxcoef = unit->m_relaxcoef; float clampcoef = unit->m_clampcoef; float previn = unit->m_previn; float val; LOOP1( inNumSamples, val = std::abs(ZXP(in)); if (val < previn) { val = val + (previn - val) * relaxcoef; } else { val = val + (previn - val) * clampcoef; } ZXP(out) = previn = val;); unit->m_previn = previn; } void Amplitude_next_atok(Amplitude* unit, int inNumSamples) { float* in = ZIN(0); float relaxcoef = unit->m_relaxcoef; float clampcoef = unit->m_clampcoef; float previn = unit->m_previn; float val; LOOP1( FULLBUFLENGTH, val = std::abs(ZXP(in)); if (val < previn) { val = val + (previn - val) * relaxcoef; } else { val = val + (previn - val) * clampcoef; } previn = val;); ZOUT0(0) = val; unit->m_previn = previn; } void Amplitude_next_kk(Amplitude* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float relaxcoef, clampcoef; if (ZIN0(1) != unit->m_clamp_in) { clampcoef = unit->m_clampcoef = exp(log1 / (ZIN0(1) * SAMPLERATE)); unit->m_clamp_in = ZIN0(1); } else { clampcoef = unit->m_clampcoef; } if (ZIN0(2) != unit->m_relax_in) { relaxcoef = unit->m_relaxcoef = exp(log1 / (ZIN0(2) * SAMPLERATE)); unit->m_relax_in = ZIN0(2); } else { relaxcoef = unit->m_relaxcoef; } float previn = unit->m_previn; float val; LOOP1( inNumSamples, val = std::abs(ZXP(in)); if (val < previn) { val = val + (previn - val) * relaxcoef; } else { val = val + (previn - val) * clampcoef; } ZXP(out) = previn = val;); unit->m_previn = previn; } void Amplitude_next_atok_kk(Amplitude* unit, int inNumSamples) { float* in = ZIN(0); float relaxcoef, clampcoef; if (ZIN0(1) != unit->m_clamp_in) { clampcoef = unit->m_clampcoef = exp(log1 / (ZIN0(1) * SAMPLERATE)); unit->m_clamp_in = ZIN0(1); } else { clampcoef = unit->m_clampcoef; } if (ZIN0(2) != unit->m_relax_in) { relaxcoef = unit->m_relaxcoef = exp(log1 / (ZIN0(2) * SAMPLERATE)); unit->m_relax_in = ZIN0(2); } else { relaxcoef = unit->m_relaxcoef; } float previn = unit->m_previn; float val; LOOP1( FULLBUFLENGTH, val = std::abs(ZXP(in)); if (val < previn) { val = val + (previn - val) * relaxcoef; } else { val = val + (previn - val) * clampcoef; } previn = val;); ZOUT0(0) = val; unit->m_previn = previn; } //////////////////////////////////////////////////////////////////////////////////////////////////////// void DetectSilence_Ctor(DetectSilence* unit) { // printf("DetectSilence_Reset\n"); if (INRATE(1) == calc_ScalarRate && INRATE(2) == calc_ScalarRate) { unit->mThresh = ZIN0(1); unit->mEndCounter = (int32)(SAMPLERATE * ZIN0(2)); SETCALC(DetectSilence_next); } else { SETCALC(DetectSilence_next_k); } unit->mCounter = -1; ClearUnitOutputs(unit, 1); } void DetectSilence_next(DetectSilence* unit, int inNumSamples) { float thresh = unit->mThresh; int counter = unit->mCounter; float val; float* in = IN(0); float* out = OUT(0); for (int i = 0; i < inNumSamples; ++i) { val = std::abs(*in++); if (val > thresh) { counter = 0; *out++ = 0.f; } else if (counter >= 0) { if (++counter >= unit->mEndCounter) { DoneAction((int)ZIN0(3), unit); *out++ = 1.f; } else { *out++ = 0.f; } } else *out++ = 0.f; } unit->mCounter = counter; } void DetectSilence_next_k(DetectSilence* unit, int inNumSamples) { float thresh = ZIN0(1); int endCounter = (int32)(SAMPLERATE * ZIN0(2)); int counter = unit->mCounter; float val; float* in = IN(0); float* out = OUT(0); for (int i = 0; i < inNumSamples; ++i) { val = std::abs(*in++); if (val > thresh) { counter = 0; *out++ = 0.f; } else if (counter >= 0) { if (++counter >= endCounter) { DoneAction((int)ZIN0(3), unit); *out++ = 1.f; } else { *out++ = 0.f; } } else *out++ = 0.f; } unit->mCounter = counter; } /////////////////////////////////////////////////////////////////////////////////////////////////////// // Based on HilbertIIR from SC2 // a 12 pole (6 per side) Hilbert IIR filter // based on Sean Costello and Bernie Hutchins // created by jl anderson - 7 jan 2001 // UGen created by Josh Parmenter #define HILBERT_FILTER \ y0_1 = thisin - (coefs[0]) * y1[0]; \ ay1 = coefs[0] * y0_1 + 1 * y1[0]; \ y1[0] = y0_1; \ y0_2 = ay1 - (coefs[1]) * y1[1]; \ ay2 = coefs[1] * y0_2 + 1 * y1[1]; \ y1[1] = y0_2; \ y0_3 = ay2 - (coefs[2]) * y1[2]; \ ay3 = coefs[2] * y0_3 + 1 * y1[2]; \ y1[2] = y0_3; \ y0_4 = ay3 - (coefs[3]) * y1[3]; \ ay4 = coefs[3] * y0_4 + 1 * y1[3]; \ y1[3] = y0_4; \ y0_5 = ay4 - (coefs[4]) * y1[4]; \ ay5 = coefs[4] * y0_5 + 1 * y1[4]; \ y1[4] = y0_5; \ y0_6 = ay5 - (coefs[5]) * y1[5]; \ ay6 = coefs[5] * y0_6 + 1 * y1[5]; \ y1[5] = y0_6; \ \ y0_7 = thisin - (coefs[6]) * y1[6]; \ ay7 = coefs[6] * y0_7 + 1 * y1[6]; \ y1[6] = y0_7; \ y0_8 = ay7 - (coefs[7]) * y1[7]; \ ay8 = coefs[7] * y0_8 + 1 * y1[7]; \ y1[7] = y0_8; \ y0_9 = ay8 - (coefs[8]) * y1[8]; \ ay9 = coefs[8] * y0_9 + 1 * y1[8]; \ y1[8] = y0_9; \ y0_10 = ay9 - (coefs[9]) * y1[9]; \ ay10 = coefs[9] * y0_10 + 1 * y1[9]; \ y1[9] = y0_10; \ y0_11 = ay10 - (coefs[10]) * y1[10]; \ ay11 = coefs[10] * y0_11 + 1 * y1[10]; \ y1[10] = y0_11; \ y0_12 = ay11 - (coefs[11]) * y1[11]; \ ay12 = coefs[11] * y0_12 + 1 * y1[11]; \ y1[11] = y0_12; void Hilbert_Ctor(Hilbert* unit) { // calculate coefs based on SampleRate, store in the struct SETCALC(Hilbert_next); double gamconst = (15.0f * pi_f) / SAMPLERATE; double gamma01 = gamconst * 0.3609f; double gamma02 = gamconst * 2.7412f; double gamma03 = gamconst * 11.1573f; double gamma04 = gamconst * 44.7581f; double gamma05 = gamconst * 179.6242f; double gamma06 = gamconst * 798.4578f; double gamma07 = gamconst * 1.2524f; double gamma08 = gamconst * 5.5671f; double gamma09 = gamconst * 22.3423f; double gamma10 = gamconst * 89.6271f; double gamma11 = gamconst * 364.7914f; double gamma12 = gamconst * 2770.1114f; unit->m_coefs[0] = (gamma01 - 1.f) / (gamma01 + 1.f); unit->m_coefs[1] = (gamma02 - 1.f) / (gamma02 + 1.f); unit->m_coefs[2] = (gamma03 - 1.f) / (gamma03 + 1.f); unit->m_coefs[3] = (gamma04 - 1.f) / (gamma04 + 1.f); unit->m_coefs[4] = (gamma05 - 1.f) / (gamma05 + 1.f); unit->m_coefs[5] = (gamma06 - 1.f) / (gamma06 + 1.f); unit->m_coefs[6] = (gamma07 - 1.f) / (gamma07 + 1.f); unit->m_coefs[7] = (gamma08 - 1.f) / (gamma08 + 1.f); unit->m_coefs[8] = (gamma09 - 1.f) / (gamma09 + 1.f); unit->m_coefs[9] = (gamma10 - 1.f) / (gamma10 + 1.f); unit->m_coefs[10] = (gamma11 - 1.f) / (gamma11 + 1.f); unit->m_coefs[11] = (gamma12 - 1.f) / (gamma12 + 1.f); Clear(12, unit->m_y1); Hilbert_next(unit, 1); } void Hilbert_next(Hilbert* unit, int inNumSamples) { float* in = ZIN(0); float* outcos = ZOUT(0); float* outsin = ZOUT(1); float y1[12]; float coefs[12]; // each filter's last sample for (int i = 0; i < 12; ++i) { y1[i] = unit->m_y1[i]; coefs[i] = unit->m_coefs[i]; } double ay1, ay2, ay3, ay4, ay5, ay6; double ay7, ay8, ay9, ay10, ay11, ay12; double y0_1, y0_2, y0_3, y0_4, y0_5, y0_6; double y0_7, y0_8, y0_9, y0_10, y0_11, y0_12; LOOP1(inNumSamples, float thisin = ZXP(in); HILBERT_FILTER ZXP(outcos) = ay6; ZXP(outsin) = ay12;) for (int i = 0; i < 12; ++i) unit->m_y1[i] = zapgremlins(y1[i]); } /* Hilbert based SSB FreqShifter */ void FreqShift_Ctor(FreqShift* unit) { // calculate coefs based on SampleRate, store in the struct // SETCALC(FreqShift_next_kk); unit->m_phase = 0; if (INRATE(1) == calc_FullRate) { if (INRATE(2) == calc_FullRate) SETCALC(FreqShift_next_aa); else SETCALC(FreqShift_next_ak); } else { if (INRATE(2) == calc_FullRate) SETCALC(FreqShift_next_ka); else { SETCALC(FreqShift_next_kk); unit->m_phase = (int32)(unit->m_radtoinc * IN0(2)); } } // set up for the oscil for the modualtion int tableSizeSin = ft->mSineSize; unit->m_lomask = (tableSizeSin - 1) << 3; unit->m_radtoinc = tableSizeSin * (rtwopi * 65536.); unit->m_cpstoinc = tableSizeSin * SAMPLEDUR * 65536.; unit->m_phasein = IN0(2); double gamconst = (15.0 * pi) / SAMPLERATE; double gamma01 = gamconst * 0.3609f; double gamma02 = gamconst * 2.7412f; double gamma03 = gamconst * 11.1573f; double gamma04 = gamconst * 44.7581f; double gamma05 = gamconst * 179.6242f; double gamma06 = gamconst * 798.4578f; double gamma07 = gamconst * 1.2524f; double gamma08 = gamconst * 5.5671f; double gamma09 = gamconst * 22.3423f; double gamma10 = gamconst * 89.6271f; double gamma11 = gamconst * 364.7914f; double gamma12 = gamconst * 2770.1114f; unit->m_coefs[0] = (gamma01 - 1.f) / (gamma01 + 1.f); unit->m_coefs[1] = (gamma02 - 1.f) / (gamma02 + 1.f); unit->m_coefs[2] = (gamma03 - 1.f) / (gamma03 + 1.f); unit->m_coefs[3] = (gamma04 - 1.f) / (gamma04 + 1.f); unit->m_coefs[4] = (gamma05 - 1.f) / (gamma05 + 1.f); unit->m_coefs[5] = (gamma06 - 1.f) / (gamma06 + 1.f); unit->m_coefs[6] = (gamma07 - 1.f) / (gamma07 + 1.f); unit->m_coefs[7] = (gamma08 - 1.f) / (gamma08 + 1.f); unit->m_coefs[8] = (gamma09 - 1.f) / (gamma09 + 1.f); unit->m_coefs[9] = (gamma10 - 1.f) / (gamma10 + 1.f); unit->m_coefs[10] = (gamma11 - 1.f) / (gamma11 + 1.f); unit->m_coefs[11] = (gamma12 - 1.f) / (gamma12 + 1.f); Clear(12, unit->m_y1); FreqShift_next_kk(unit, 1); } void FreqShift_next_kk(FreqShift* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); float phasein = ZIN0(2); float freqin = ZIN0(1); float outcos, outsin; // the sample by sample output of the Hilbert float outsinosc, outsinoscHalfPi; // the samples from the oscil. int32 halfPi = (int32)(unit->m_radtoinc * (0.5 * pi)); double y1[12]; double coefs[12]; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; int32 lomask = unit->m_lomask; int32 phase = unit->m_phase; int32 freq = (int32)(unit->m_cpstoinc * freqin); int32 phaseinc = freq + (int32)(CALCSLOPE(phasein, unit->m_phasein) * unit->m_radtoinc); unit->m_phasein = phasein; // each filter's last sample for (int i = 0; i < 12; ++i) { y1[i] = unit->m_y1[i]; coefs[i] = unit->m_coefs[i]; } double ay1, ay2, ay3, ay4, ay5, ay6; double ay7, ay8, ay9, ay10, ay11, ay12; double y0_1, y0_2, y0_3, y0_4, y0_5, y0_6; double y0_7, y0_8, y0_9, y0_10, y0_11, y0_12; LOOP1(inNumSamples, float thisin = ZXP(in); HILBERT_FILTER outcos = ay6; outsin = ay12; outsinosc = lookupi1(table0, table1, phase, lomask); outsinoscHalfPi = lookupi1(table0, table1, phase + halfPi, lomask); ZXP(out) = (outcos * outsinoscHalfPi) + (outsinosc * outsin); phase += phaseinc;) unit->m_phase = phase; for (int i = 0; i < 12; ++i) unit->m_y1[i] = zapgremlins(y1[i]); } void FreqShift_next_aa(FreqShift* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); float* phasein = ZIN(2); float* freqin = ZIN(1); float outcos, outsin; // the sample by sample output of the Hilbert float outsinosc, outsinoscHalfPi; // the samples from the oscil. int32 halfPi = (int32)(unit->m_radtoinc * (0.5 * pi)); double y1[12]; double coefs[12]; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; int32 lomask = unit->m_lomask; int32 phase = unit->m_phase; // each filter's last sample for (int i = 0; i < 12; ++i) { y1[i] = unit->m_y1[i]; coefs[i] = unit->m_coefs[i]; } double ay1, ay2, ay3, ay4, ay5, ay6; double ay7, ay8, ay9, ay10, ay11, ay12; double y0_1, y0_2, y0_3, y0_4, y0_5, y0_6; double y0_7, y0_8, y0_9, y0_10, y0_11, y0_12; LOOP1(inNumSamples, float thisin = ZXP(in); HILBERT_FILTER outcos = ay6; outsin = ay12; int32 phaseoffset = phase + (int32)(unit->m_radtoinc * ZXP(phasein)); outsinosc = lookupi1(table0, table1, phaseoffset, lomask); outsinoscHalfPi = lookupi1(table0, table1, phaseoffset + halfPi, lomask); phase += (int32)(unit->m_cpstoinc * ZXP(freqin)); ZXP(out) = (outcos * outsinoscHalfPi) + (outsinosc * outsin);) unit->m_phase = phase; for (int i = 0; i < 12; ++i) unit->m_y1[i] = zapgremlins(y1[i]); } void FreqShift_next_ak(FreqShift* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); float phasein = ZIN0(2); float* freqin = ZIN(1); float outcos, outsin; // the sample by sample output of the Hilbert float outsinosc, outsinoscHalfPi; // the samples from the oscil. int32 halfPi = (int32)(unit->m_radtoinc * (0.5 * pi)); double y1[12]; double coefs[12]; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; int32 lomask = unit->m_lomask; int32 phase = unit->m_phase; float phasemod = unit->m_phasein; float phaseslope = CALCSLOPE(phasein, phasemod); // each filter's last sample for (int i = 0; i < 12; ++i) { y1[i] = unit->m_y1[i]; coefs[i] = unit->m_coefs[i]; } double ay1, ay2, ay3, ay4, ay5, ay6; double ay7, ay8, ay9, ay10, ay11, ay12; double y0_1, y0_2, y0_3, y0_4, y0_5, y0_6; double y0_7, y0_8, y0_9, y0_10, y0_11, y0_12; LOOP1(inNumSamples, float thisin = ZXP(in); HILBERT_FILTER outcos = ay6; outsin = ay12; int32 pphase = phase + (int32)(unit->m_radtoinc * phasemod); phasemod += phaseslope; outsinosc = lookupi1(table0, table1, pphase, lomask); outsinoscHalfPi = lookupi1(table0, table1, pphase + halfPi, lomask); phase += (int32)(unit->m_cpstoinc * ZXP(freqin)); ZXP(out) = (outcos * outsinoscHalfPi) + (outsinosc * outsin);) unit->m_phase = phase; unit->m_phasein = phasein; for (int i = 0; i < 12; ++i) unit->m_y1[i] = zapgremlins(y1[i]); } void FreqShift_next_ka(FreqShift* unit, int inNumSamples) { float* in = ZIN(0); float* out = ZOUT(0); float* phasein = ZIN(2); float freqin = ZIN0(1); float outcos, outsin; // the sample by sample output of the Hilbert float outsinosc, outsinoscHalfPi; // the samples from the oscil. int32 halfPi = (int32)(unit->m_radtoinc * (0.5 * pi)); double y1[12]; double coefs[12]; float* table0 = ft->mSineWavetable; float* table1 = table0 + 1; int32 lomask = unit->m_lomask; int32 phase = unit->m_phase; int32 freq = (int32)(unit->m_cpstoinc * freqin); // each filter's last sample for (int i = 0; i < 12; ++i) { y1[i] = unit->m_y1[i]; coefs[i] = unit->m_coefs[i]; } double ay1, ay2, ay3, ay4, ay5, ay6; double ay7, ay8, ay9, ay10, ay11, ay12; double y0_1, y0_2, y0_3, y0_4, y0_5, y0_6; double y0_7, y0_8, y0_9, y0_10, y0_11, y0_12; LOOP1(inNumSamples, float thisin = ZXP(in); HILBERT_FILTER outcos = ay6; outsin = ay12; int32 phaseoffset = phase + (int32)(unit->m_radtoinc * ZXP(phasein)); outsinosc = lookupi1(table0, table1, phaseoffset, lomask); outsinoscHalfPi = lookupi1(table0, table1, phaseoffset + halfPi, lomask); phase += freq; ZXP(out) = (outcos * outsinoscHalfPi) + (outsinosc * outsin);) unit->m_phase = phase; for (int i = 0; i < 12; ++i) unit->m_y1[i] = zapgremlins(y1[i]); } /** "MoogFF" - Moog VCF digital implementation. As described in the paper entitled "Preserving the Digital Structure of the Moog VCF" by Federico Fontana appeared in the Proc. ICMC07, Copenhagen, 25-31 August 2007 Original Java code Copyright F. Fontana - August 2007 federico.fontana@univr.it Ported to C++ for SuperCollider by Dan Stowell - August 2007 http://www.mcld.co.uk/ 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 */ ////////////////////////////////////////////////////////////////// void MoogFF_Ctor(MoogFF* unit) { SETCALC(MoogFF_next); // initialize the unit generator state variables. unit->m_freq = uninitializedControl; unit->m_k = IN0(2); unit->m_s1 = 0.f; unit->m_s2 = 0.f; unit->m_s3 = 0.f; unit->m_s4 = 0.f; // calculate one sample of output. MoogFF_next(unit, 1); } void MoogFF_next(MoogFF* unit, int inNumSamples) { float k = IN0(2); k = sc_clip(k, 0.f, 4.f); // Load state from the struct double s1 = unit->m_s1; double s2 = unit->m_s2; double s3 = unit->m_s3; double s4 = unit->m_s4; // Reset filter state if requested if (IN0(3) > 0) s1 = s2 = s3 = s4 = 0.f; double a1 = unit->m_a1, b0 = unit->m_b0; // Filter coefficient parameters // Update filter coefficients, but only if freq changes since it involves some expensive operations float freqIn = IN0(1); if (unit->m_freq != freqIn) { // Print("Updated freq to %g\n", freq); double T = SAMPLEDUR; double wcD = 2.0 * tan(T * PI * freqIn) * SAMPLERATE; if (wcD < 0) wcD = 0; // Protect against negative cutoff freq double TwcD = T * wcD; b0 = TwcD / (TwcD + 2.); a1 = (TwcD - 2.) / (TwcD + 2.); unit->m_freq = freqIn; unit->m_b0 = b0; unit->m_a1 = a1; } float* out = ZOUT(0); float* in = ZIN(0); if (unit->m_k == k) { LOOP1(inNumSamples, // compute loop values double o = s4 + b0 * (s3 + b0 * (s2 + b0 * s1)); double ins = ZXP(in); double outs = (b0 * b0 * b0 * b0 * ins + o) * sc_reciprocal(1.0 + b0 * b0 * b0 * b0 * k); ZXP(out) = outs; double u = ins - k * outs; // update 1st order filter states double past = u; double future = b0 * past + s1; s1 = b0 * past - a1 * future; past = future; future = b0 * past + s2; s2 = b0 * past - a1 * future; past = future; future = b0 * past + s3; s3 = b0 * past - a1 * future; s4 = b0 * future - a1 * outs;) } else { float new_k = k; float old_k = unit->m_k; float slope_k = CALCSLOPE(new_k, old_k); k = old_k; LOOP1(inNumSamples, // compute loop values double o = s4 + b0 * (s3 + b0 * (s2 + b0 * s1)); double ins = ZXP(in); double outs = (b0 * b0 * b0 * b0 * ins + o) * sc_reciprocal(1.0 + b0 * b0 * b0 * b0 * k); ZXP(out) = outs; double u = ins - k * outs; // update 1st order filter states double past = u; double future = b0 * past + s1; s1 = b0 * past - a1 * future; past = future; future = b0 * past + s2; s2 = b0 * past - a1 * future; past = future; future = b0 * past + s3; s3 = b0 * past - a1 * future; s4 = b0 * future - a1 * outs; k += slope_k;); unit->m_k = new_k; } // Store state unit->m_s1 = zapgremlins(s1); unit->m_s2 = zapgremlins(s2); unit->m_s3 = zapgremlins(s3); unit->m_s4 = zapgremlins(s4); } /* BEQSuite */ static void inline BPerformFilterLoop(const Unit* unit, float* out, const float* in, double& y1, double& y2, double a0, double a1, double a2, double b1, double b2) { LOOP(unit->mRate->mFilterLoops, double in0 = ZXP(in); double in1 = ZXP(in); double in2 = ZXP(in); double y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, double y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0;); } static void inline BPerformFilterLoop(const Unit* unit, float* out, const float* in, double& y1, double& y2, double a0, double a1, double a2, double b1, double b2, double a0slope, double a1slope, double a2slope, double b1slope, double b2slope) { LOOP(unit->mRate->mFilterLoops, double in0 = ZXP(in); double in1 = ZXP(in); double in2 = ZXP(in); double y0 = in0 + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = in1 + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = in2 + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0; a0 += a0slope; a1 += a1slope; a2 += a2slope; b1 += b1slope; b2 += b2slope;); LOOP(unit->mRate->mFilterRemain, double y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0;); } struct BLowPass : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rq; }; extern "C" { void BLowPass_next_ii(BLowPass* unit, int inNumSamples); void BLowPass_next_kk(BLowPass* unit, int inNumSamples); void BLowPass_next_aa(BLowPass* unit, int inNumSamples); void BLowPass_Ctor(BLowPass* unit); } void BLowPass_Ctor(BLowPass* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate)) SETCALC(BLowPass_next_aa); else { if ((INRATE(1) == calc_ScalarRate) && (INRATE(2) == calc_ScalarRate)) SETCALC(BLowPass_next_ii); else SETCALC(BLowPass_next_kk); } float rq = unit->m_rq = ZIN0(2); float freq = unit->m_freq = ZIN0(1); double w0 = twopi * (double)freq * SAMPLEDUR; double cosw0 = cos(w0); double i = 1. - cosw0; double alpha = sin(w0) * 0.5 * (double)rq; double b0rz = 1. / (1. + alpha); double a0 = unit->m_a0 = i * 0.5 * b0rz; unit->m_a1 = i * b0rz; unit->m_a2 = a0; unit->m_b1 = cosw0 * 2. * b0rz; unit->m_b2 = (1. - alpha) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BLowPass_next_kk(unit, 1); POP_LOOPVALS } void BLowPass_next_aa(BLowPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rq = ZIN(2); double a0, a1, a2, b1, b2, w0, cosw0, i, alpha, b0rz; double y0, y1, y2; float nextfreq, nextrq; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrq = ZXP(rq); if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { w0 = twopi * (double)nextfreq * SAMPLEDUR; cosw0 = cos(w0); i = 1. - cosw0; alpha = sin(w0) * 0.5 * (double)nextrq; b0rz = 1. / (1. + alpha); a0 = i * 0.5 * b0rz; a1 = i * b0rz; a2 = a0; b1 = cosw0 * 2. * b0rz; b2 = (1. - alpha) * -b0rz; unit->m_freq = nextfreq; unit->m_rq = nextrq; } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = ZXP(freq); unit->m_rq = ZXP(rq);); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BLowPass_next_kk(BLowPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrq = ZIN0(2); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2, next_w0, next_cosw0, next_i, next_alpha, next_b0rz; next_w0 = twopi * (double)nextfreq * SAMPLEDUR; next_cosw0 = cos(next_w0); next_i = 1. - next_cosw0; next_alpha = sin(next_w0) * 0.5 * (double)nextrq; next_b0rz = 1. / (1. + next_alpha); next_a0 = next_i * 0.5 * next_b0rz; next_a1 = next_i * next_b0rz; next_a2 = next_a0; next_b1 = next_cosw0 * 2. * next_b0rz; next_b2 = ((1. - next_alpha) * -next_b0rz); a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; unit->m_freq = nextfreq; unit->m_rq = nextrq; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BLowPass_next_ii(BLowPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } struct BHiPass : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rq; }; extern "C" { void BHiPass_next_ii(BHiPass* unit, int inNumSamples); void BHiPass_next_kk(BHiPass* unit, int inNumSamples); void BHiPass_next_aa(BHiPass* unit, int inNumSamples); void BHiPass_Ctor(BHiPass* unit); } void BHiPass_Ctor(BHiPass* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate)) SETCALC(BHiPass_next_aa); else { if ((INRATE(1) == calc_ScalarRate) && (INRATE(2) == calc_ScalarRate)) SETCALC(BHiPass_next_ii); else SETCALC(BHiPass_next_kk); } float freq = unit->m_freq = ZIN0(1); float rq = unit->m_rq = ZIN0(2); double w0 = twopi * (double)freq * SAMPLEDUR; double cosw0 = cos(w0); double i = 1. + cosw0; double alpha = sin(w0) * 0.5 * (double)rq; double b0rz = 1. / (1. + alpha); double a0 = unit->m_a0 = i * 0.5 * b0rz; unit->m_a1 = -i * b0rz; unit->m_a2 = a0; unit->m_b1 = cosw0 * 2. * b0rz; unit->m_b2 = (1. - alpha) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BHiPass_next_kk(unit, 1); POP_LOOPVALS } void BHiPass_next_aa(BHiPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rq = ZIN(2); double a0, a1, a2, b1, b2, w0, cosw0, i, alpha, b0rz; double y0, y1, y2; float nextfreq, nextrq; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrq = ZXP(rq); if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { w0 = twopi * (double)nextfreq * SAMPLEDUR; cosw0 = cos(w0); i = 1. + cosw0; alpha = sin(w0) * 0.5 * (double)nextrq; b0rz = 1. / (1. + alpha); a0 = i * 0.5 * b0rz; a1 = -i * b0rz; a2 = a0; b1 = cosw0 * 2. * b0rz; b2 = (1. - alpha) * -b0rz; unit->m_freq = nextfreq; unit->m_rq = nextrq; } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0;); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BHiPass_next_kk(BHiPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrq = ZIN0(2); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2, next_w0, next_cosw0, next_i, next_alpha, next_b0rz; next_w0 = twopi * (double)nextfreq * SAMPLEDUR; next_cosw0 = cos(next_w0); next_i = 1. + next_cosw0; next_alpha = sin(next_w0) * 0.5 * (double)nextrq; next_b0rz = 1. / (1. + next_alpha); next_a0 = next_i * 0.5 * next_b0rz; next_a1 = -next_i * next_b0rz; next_a2 = next_a0; next_b1 = next_cosw0 * 2. * next_b0rz; next_b2 = (1. - next_alpha) * -next_b0rz; a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_rq = nextrq; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BHiPass_next_ii(BHiPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BBandPass */ struct BBandPass : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_bw; }; extern "C" { void BBandPass_next_kk(BBandPass* unit, int inNumSamples); void BBandPass_next_aa(BBandPass* unit, int inNumSamples); void BBandPass_Ctor(BBandPass* unit); } void BBandPass_Ctor(BBandPass* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate)) SETCALC(BBandPass_next_aa); else SETCALC(BBandPass_next_kk); float freq = unit->m_freq = ZIN0(1); float bw = unit->m_bw = ZIN0(2); double w0 = twopi * (double)freq * SAMPLEDUR; double sinw0 = sin(w0); double alpha = sinw0 * (sinh((0.34657359027997 * (double)bw * w0) / sinw0)); double b0rz = 1. / (1. + alpha); double a0 = unit->m_a0 = alpha * b0rz; unit->m_a1 = 0.0f; unit->m_a2 = -a0; unit->m_b1 = cos(w0) * 2. * b0rz; unit->m_b2 = (1. - alpha) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BBandPass_next_kk(unit, 1); POP_LOOPVALS } void BBandPass_next_aa(BBandPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* bw = ZIN(2); double a0, a1, a2, b1, b2, w0, sinw0, alpha, b0rz; double y0, y1, y2; float nextfreq, nextbw; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextbw = ZXP(bw); if ((unit->m_freq != nextfreq) || (unit->m_bw != nextbw)) { w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); alpha = sinw0 * (sinh((0.34657359027997 * (double)nextbw * w0) / sinw0)); b0rz = 1. / (1. + alpha); a0 = alpha * b0rz; a1 = 0.0f; a2 = -a0; b1 = cos(w0) * 2. * b0rz; b2 = (1. - alpha) * -b0rz; unit->m_freq = ZXP(freq); unit->m_bw = ZXP(bw); } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = nextfreq; unit->m_bw = nextbw;); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BBandPass_next_kk(BBandPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextbw = ZIN0(2); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_bw != nextbw)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2, next_w0, next_alpha, next_b0rz; next_w0 = twopi * (double)nextfreq * SAMPLEDUR; next_alpha = sin(next_w0) * (sinh((0.34657359027997 * (double)nextbw * next_w0) / sin(next_w0))); next_b0rz = 1. / (1. + next_alpha); next_a0 = next_alpha * next_b0rz; next_a1 = 0.; next_a2 = -next_a0; next_b1 = cos(next_w0) * 2. * next_b0rz; next_b2 = ((1. - next_alpha) * -next_b0rz); a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_bw = nextbw; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BBandStop */ struct BBandStop : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_bw; }; extern "C" { void BBandStop_next_kk(BBandStop* unit, int inNumSamples); void BBandStop_next_aa(BBandStop* unit, int inNumSamples); void BBandStop_Ctor(BBandStop* unit); } void BBandStop_Ctor(BBandStop* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate)) SETCALC(BBandStop_next_aa); else SETCALC(BBandStop_next_kk); float freq = unit->m_freq = ZIN0(1); float bw = unit->m_bw = ZIN0(2); double w0 = twopi * (double)freq * SAMPLEDUR; double sinw0 = sin(w0); double alpha = sinw0 * (sinh((0.34657359027997 * (double)bw * w0) / sinw0)); double b0rz = 1. / (1. + alpha); double b1 = unit->m_b1 = 2. * b0rz * cos(w0); unit->m_a0 = b0rz; unit->m_a1 = -b1; unit->m_a2 = b0rz; unit->m_b2 = (1. - alpha) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BBandStop_next_kk(unit, 1); POP_LOOPVALS } void BBandStop_next_aa(BBandStop* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* bw = ZIN(2); double a0, a1, a2, b1, b2, w0, sinw0, alpha, b0rz; double y0, y1, y2; float nextfreq, nextbw; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextbw = ZXP(bw); if ((unit->m_freq != nextfreq) || (unit->m_bw != nextbw)) { w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); alpha = sinw0 * (sinh((0.34657359027997 * (double)nextbw * w0) / sinw0)); b0rz = 1. / (1. + alpha); b1 = 2. * b0rz * cos(w0); a0 = b0rz; a1 = -b1; a2 = b0rz; b2 = (1. - alpha) * -b0rz; unit->m_freq = ZXP(freq); unit->m_bw = ZXP(bw); } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = nextfreq; unit->m_bw = nextbw;); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BBandStop_next_kk(BBandStop* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextbw = ZIN0(2); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_bw != nextbw)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2, next_w0, next_alpha, next_b0rz; next_w0 = twopi * (double)nextfreq * SAMPLEDUR; next_alpha = sin(next_w0) * (sinh((0.34657359027997 * (double)nextbw * next_w0) / sin(next_w0))); next_b0rz = 1. / (1. + next_alpha); next_b1 = cos(next_w0) * 2. * next_b0rz; next_a0 = next_b0rz; next_a1 = -next_b1; next_a2 = next_b0rz; next_b2 = ((1. - next_alpha) * -next_b0rz); a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_bw = nextbw; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BPeakEQ */ struct BPeakEQ : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rq, m_db; }; extern "C" { void BPeakEQ_next_kkk(BPeakEQ* unit, int inNumSamples); void BPeakEQ_next_aaa(BPeakEQ* unit, int inNumSamples); void BPeakEQ_Ctor(BPeakEQ* unit); } void BPeakEQ_Ctor(BPeakEQ* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate) && (INRATE(3) == calc_FullRate)) SETCALC(BPeakEQ_next_aaa); else SETCALC(BPeakEQ_next_kkk); float freq = unit->m_freq = ZIN0(1); float rq = unit->m_rq = ZIN0(2); float db = unit->m_db = ZIN0(3); double a = pow(10., (double)db * 0.025); double w0 = twopi * (double)freq * SAMPLEDUR; double alpha = sin(w0) * 0.5 * (double)rq; double b0rz = 1. / (1. + (alpha / a)); double b1 = unit->m_b1 = 2. * b0rz * cos(w0); unit->m_a0 = (1. + (alpha * a)) * b0rz; unit->m_a1 = -b1; unit->m_a2 = (1. - (alpha * a)) * b0rz; unit->m_b2 = (1. - (alpha / a)) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BPeakEQ_next_kkk(unit, 1); POP_LOOPVALS } void BPeakEQ_next_aaa(BPeakEQ* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rq = ZIN(2); float* db = ZIN(3); double a0, a1, a2, b1, b2, a, w0, alpha, b0rz; double y0, y1, y2; float nextfreq, nextrq, nextdb; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrq = ZXP(rq); nextdb = ZXP(db); if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq) || (unit->m_db != nextdb)) { a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; alpha = sin(w0) * 0.5 * (double)nextrq; b0rz = 1. / (1. + (alpha / a)); b1 = 2. * b0rz * cos(w0); a0 = (1. + (alpha * a)) * b0rz; a1 = -b1; a2 = (1. - (alpha * a)) * b0rz; b2 = (1. - (alpha / a)) * -b0rz; unit->m_freq = nextfreq; unit->m_rq = nextrq; unit->m_db = nextdb; } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = ZXP(freq); unit->m_rq = ZXP(rq); unit->m_db = ZXP(db);); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BPeakEQ_next_kkk(BPeakEQ* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrq = ZIN0(2); float nextdb = ZIN0(3); double a0, a1, a2, b1, b2, a, w0, alpha, b0rz; double y1, y2; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq) || (unit->m_db != nextdb)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2; a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; alpha = sin(w0) * 0.5 * (double)nextrq; b0rz = 1. / (1. + (alpha / a)); next_b1 = 2. * b0rz * cos(w0); next_a0 = (1. + (alpha * a)) * b0rz; next_a1 = -next_b1; next_a2 = (1. - (alpha * a)) * b0rz; next_b2 = (1. - (alpha / a)) * -b0rz; a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_db = nextdb; unit->m_rq = nextrq; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BAllPass */ struct BAllPass : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rq; }; extern "C" { void BAllPass_next_kk(BAllPass* unit, int inNumSamples); void BAllPass_next_aa(BAllPass* unit, int inNumSamples); void BAllPass_Ctor(BAllPass* unit); } void BAllPass_Ctor(BAllPass* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate)) SETCALC(BAllPass_next_aa); else SETCALC(BAllPass_next_kk); float freq = unit->m_freq = ZIN0(1); float rq = unit->m_rq = ZIN0(2); double w0 = twopi * (double)freq * SAMPLEDUR; double alpha = sin(w0) * 0.5 * (double)rq; double b0rz = 1. / (1. + alpha); double a0 = unit->m_a0 = (1. - alpha) * b0rz; double b1 = unit->m_b1 = 2. * b0rz * cos(w0); unit->m_a1 = -b1; unit->m_a2 = 1.; unit->m_b2 = -a0; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BAllPass_next_kk(unit, 1); POP_LOOPVALS } void BAllPass_next_aa(BAllPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rq = ZIN(2); double a0, a1, a2, b1, b2, w0, alpha, b0rz; double y0, y1, y2; float nextfreq, nextrq; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrq = ZXP(rq); if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { w0 = twopi * (double)nextfreq * SAMPLEDUR; alpha = sin(w0) * (double)nextrq * 0.5; b0rz = 1. / (1. + alpha); b1 = 2. * b0rz * cos(w0); a0 = (1. - alpha) * b0rz; a1 = -b1; a2 = 1.; b2 = -a0; unit->m_freq = nextfreq; unit->m_rq = nextrq; } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = ZXP(freq); unit->m_rq = ZXP(rq);); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BAllPass_next_kk(BAllPass* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrq = ZIN0(2); double a0, a1, a2, b1, b2; double y1 = unit->m_y1; double y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rq != nextrq)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2, next_w0, next_alpha, next_b0rz; next_w0 = twopi * (double)nextfreq * SAMPLEDUR; next_alpha = sin(next_w0) * 0.5 * (double)nextrq; next_b0rz = 1. / (1. + next_alpha); next_b1 = cos(next_w0) * 2. * next_b0rz; next_a0 = (1. - next_alpha) * next_b0rz; next_a1 = -next_b1; next_a2 = 1.; next_b2 = -next_a0; a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; unit->m_freq = nextfreq; unit->m_rq = nextrq; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BLowShelf */ struct BLowShelf : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rs, m_db; }; extern "C" { void BLowShelf_next_kkk(BLowShelf* unit, int inNumSamples); void BLowShelf_next_aaa(BLowShelf* unit, int inNumSamples); void BLowShelf_Ctor(BLowShelf* unit); } void BLowShelf_Ctor(BLowShelf* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate) && (INRATE(3) == calc_FullRate)) SETCALC(BLowShelf_next_aaa); else SETCALC(BLowShelf_next_kkk); float freq = unit->m_freq = ZIN0(1); float rs = unit->m_rs = ZIN0(2); float db = unit->m_db = ZIN0(3); double a = pow(10., (double)db * 0.025); double w0 = twopi * (double)freq * SAMPLEDUR; double cosw0 = cos(w0); double sinw0 = sin(w0); double alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)rs - 1.) + 2.); double i = (a + 1.) * cosw0; double j = (a - 1.) * cosw0; double k = 2. * sqrt(a) * alpha; double b0rz = 1. / ((a + 1.) + j + k); unit->m_a0 = a * ((a + 1.) - j + k) * b0rz; unit->m_a1 = 2. * a * ((a - 1.) - i) * b0rz; unit->m_a2 = a * ((a + 1.) - j - k) * b0rz; unit->m_b1 = 2. * ((a - 1.) + i) * b0rz; unit->m_b2 = ((a + 1.) + j - k) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BLowShelf_next_kkk(unit, 1); POP_LOOPVALS } void BLowShelf_next_aaa(BLowShelf* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rs = ZIN(2); float* db = ZIN(3); double a0, a1, a2, b1, b2, a, w0, cosw0, sinw0, alpha, i, j, k, b0rz; double y0, y1, y2; float nextfreq, nextrs, nextdb; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrs = ZXP(rs); nextdb = ZXP(db); if ((unit->m_freq != nextfreq) || (unit->m_rs != nextrs) || (unit->m_db != nextdb)) { a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); cosw0 = cos(w0); alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)nextrs - 1.) + 2.); i = (a + 1.) * cosw0; j = (a - 1.) * cosw0; k = 2. * sqrt(a) * alpha; b0rz = 1. / ((a + 1.) + j + k); a0 = a * ((a + 1.) - j + k) * b0rz; a1 = 2. * a * ((a - 1.) - i) * b0rz; a2 = a * ((a + 1.) - j - k) * b0rz; b1 = 2. * ((a - 1.) + i) * b0rz; b2 = ((a + 1.) + j - k) * -b0rz; unit->m_freq = nextfreq; unit->m_rs = nextrs; unit->m_db = nextdb; } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = ZXP(freq); unit->m_rs = ZXP(rs); unit->m_db = ZXP(db);); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BLowShelf_next_kkk(BLowShelf* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrs = ZIN0(2); float nextdb = ZIN0(3); double a0, a1, a2, b1, b2, a, w0, cosw0, sinw0, alpha, i, j, k, b0rz; double y1, y2; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rs != nextrs) || (unit->m_db != nextdb)) { double a0slope, a1slope, a2slope, b1slope, b2slope, nexta0, nexta1, nexta2, nextb1, nextb2; a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); cosw0 = cos(w0); alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)nextrs - 1.) + 2.); i = (a + 1.) * cosw0; j = (a - 1.) * cosw0; k = 2. * sqrt(a) * alpha; b0rz = 1. / ((a + 1.) + j + k); nexta0 = a * ((a + 1.) - j + k) * b0rz; nexta1 = 2. * a * ((a - 1.) - i) * b0rz; nexta2 = a * ((a + 1.) - j - k) * b0rz; nextb1 = 2. * ((a - 1.) + i) * b0rz; nextb2 = ((a + 1.) + j - k) * -b0rz; a0slope = (nexta0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (nexta1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (nexta2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (nextb1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (nextb2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_db = nextdb; unit->m_rs = nextrs; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = nexta0; unit->m_a1 = nexta1; unit->m_a2 = nexta2; unit->m_b1 = nextb1; unit->m_b2 = nextb2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } /* BHiShelf */ struct BHiShelf : public Unit { double m_y1, m_y2, m_a0, m_a1, m_a2, m_b1, m_b2; float m_freq, m_rs, m_db; }; extern "C" { void BHiShelf_next_kkk(BHiShelf* unit, int inNumSamples); void BHiShelf_next_aaa(BHiShelf* unit, int inNumSamples); void BHiShelf_Ctor(BHiShelf* unit); } void BHiShelf_Ctor(BHiShelf* unit) { if ((INRATE(1) == calc_FullRate) && (INRATE(2) == calc_FullRate) && (INRATE(3) == calc_FullRate)) SETCALC(BHiShelf_next_aaa); else SETCALC(BHiShelf_next_kkk); float freq = unit->m_freq = ZIN0(1); float rs = unit->m_rs = ZIN0(2); float db = unit->m_db = ZIN0(3); double a = pow(10., (double)db * 0.025); double w0 = twopi * (double)freq * SAMPLEDUR; double cosw0 = cos(w0); double sinw0 = sin(w0); double alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)rs - 1.) + 2.); double i = (a + 1.) * cosw0; double j = (a - 1.) * cosw0; double k = 2. * sqrt(a) * alpha; double b0rz = 1. / ((a + 1.) - j + k); unit->m_a0 = a * ((a + 1.) + j + k) * b0rz; unit->m_a1 = -2. * a * ((a - 1.) + i) * b0rz; unit->m_a2 = a * ((a + 1.) + j - k) * b0rz; unit->m_b1 = -2. * ((a - 1.) - i) * b0rz; unit->m_b2 = ((a + 1.) - j - k) * -b0rz; unit->m_y1 = 0.; unit->m_y2 = 0.; PUSH_LOOPVALS BHiShelf_next_kkk(unit, 1); POP_LOOPVALS } void BHiShelf_next_aaa(BHiShelf* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float* freq = ZIN(1); float* rs = ZIN(2); float* db = ZIN(3); double a0, a1, a2, b1, b2, a, w0, cosw0, sinw0, alpha, i, j, k, b0rz; double y0, y1, y2; float nextfreq, nextrs, nextdb; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; LOOP( unit->mRate->mFilterLoops, nextfreq = ZXP(freq); nextrs = ZXP(rs); nextdb = ZXP(db); if ((unit->m_freq != nextfreq) || (unit->m_rs != nextrs) || (unit->m_db != nextdb)) { a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); cosw0 = cos(w0); alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)nextrs - 1.) + 2.); i = (a + 1.) * cosw0; j = (a - 1.) * cosw0; k = 2. * sqrt(a) * alpha; b0rz = 1. / ((a + 1.) - j + k); a0 = a * ((a + 1.) + j + k) * b0rz; a1 = -2. * a * ((a - 1.) + i) * b0rz; a2 = a * ((a + 1.) + j - k) * b0rz; b1 = -2. * ((a - 1.) - i) * b0rz; b2 = ((a + 1.) - j - k) * -b0rz; unit->m_freq = ZXP(freq); unit->m_rs = ZXP(rs); unit->m_db = ZXP(db); } y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = ZXP(in) + b1 * y0 + b2 * y1; ZXP(out) = a0 * y2 + a1 * y0 + a2 * y1; y1 = ZXP(in) + b1 * y2 + b2 * y0; ZXP(out) = a0 * y1 + a1 * y2 + a2 * y0;); LOOP(unit->mRate->mFilterRemain, y0 = ZXP(in) + b1 * y1 + b2 * y2; ZXP(out) = a0 * y0 + a1 * y1 + a2 * y2; y2 = y1; y1 = y0; unit->m_freq = ZXP(freq); unit->m_rs = ZXP(rs); unit->m_db = ZXP(db);); unit->m_a0 = a0; unit->m_a1 = a1; unit->m_a2 = a2; unit->m_b1 = b1; unit->m_b2 = b2; unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } void BHiShelf_next_kkk(BHiShelf* unit, int inNumSamples) { float* out = ZOUT(0); float* in = ZIN(0); float nextfreq = ZIN0(1); float nextrs = ZIN0(2); float nextdb = ZIN0(3); double a0, a1, a2, b1, b2, a, w0, cosw0, sinw0, alpha, i, j, k, b0rz; double y1, y2; y1 = unit->m_y1; y2 = unit->m_y2; a0 = unit->m_a0; a1 = unit->m_a1; a2 = unit->m_a2; b1 = unit->m_b1; b2 = unit->m_b2; if ((unit->m_freq != nextfreq) || (unit->m_rs != nextrs) || (unit->m_db != nextdb)) { double a0slope, a1slope, a2slope, b1slope, b2slope; double next_a0, next_a1, next_a2, next_b1, next_b2; a = pow(10., (double)nextdb * 0.025); w0 = twopi * (double)nextfreq * SAMPLEDUR; sinw0 = sin(w0); cosw0 = cos(w0); alpha = sinw0 * 0.5 * sqrt((a + (1. / a)) * ((double)nextrs - 1.) + 2.); i = (a + 1.) * cosw0; j = (a - 1.) * cosw0; k = 2. * sqrt(a) * alpha; b0rz = 1. / ((a + 1.) - j + k); next_a0 = a * ((a + 1.) + j + k) * b0rz; next_a1 = -2. * a * ((a - 1.) + i) * b0rz; next_a2 = a * ((a + 1.) + j - k) * b0rz; next_b1 = -2. * ((a - 1.) - i) * b0rz; next_b2 = ((a + 1.) - j - k) * -b0rz; a0slope = (next_a0 - a0) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta0, a0); a1slope = (next_a1 - a1) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta1, a1); a2slope = (next_a2 - a2) * unit->mRate->mFilterSlope; // CALCSLOPE(nexta2, a2); b1slope = (next_b1 - b1) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb1, b1); b2slope = (next_b2 - b2) * unit->mRate->mFilterSlope; // CALCSLOPE(nextb2, b2); unit->m_freq = nextfreq; unit->m_db = nextdb; unit->m_rs = nextrs; BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2, a0slope, a1slope, a2slope, b1slope, b2slope); unit->m_a0 = next_a0; unit->m_a1 = next_a1; unit->m_a2 = next_a2; unit->m_b1 = next_b1; unit->m_b2 = next_b2; } else BPerformFilterLoop(unit, out, in, y1, y2, a0, a1, a2, b1, b2); unit->m_y1 = zapgremlins(y1); unit->m_y2 = zapgremlins(y2); } //////////////////////////////////////////////////////////////////////////////////////////////////////// PluginLoad(Filter) { ft = inTable; DefineSimpleUnit(Ramp); DefineSimpleUnit(Lag); DefineSimpleUnit(Lag2); DefineSimpleUnit(Lag3); DefineSimpleUnit(LagUD); DefineSimpleUnit(Lag2UD); DefineSimpleUnit(Lag3UD); DefineSimpleUnit(VarLag); DefineSimpleUnit(OnePole); DefineSimpleUnit(OneZero); DefineSimpleUnit(TwoPole); DefineSimpleUnit(TwoZero); DefineSimpleUnit(Decay); DefineSimpleUnit(Decay2); DefineSimpleUnit(Flip); DefineSimpleUnit(Delay1); DefineSimpleUnit(Delay2); DefineSimpleUnit(Integrator); DefineSimpleUnit(LeakDC); DefineSimpleUnit(LPZ1); DefineSimpleUnit(HPZ1); DefineSimpleUnit(LPZ2); DefineSimpleUnit(HPZ2); DefineSimpleUnit(BPZ2); DefineSimpleUnit(BRZ2); DefineSimpleUnit(APF); DefineSimpleUnit(LPF); DefineSimpleUnit(HPF); DefineSimpleUnit(BPF); DefineSimpleUnit(BRF); DefineSimpleUnit(RLPF); DefineSimpleUnit(RHPF); DefineSimpleUnit(Slew); DefineSimpleUnit(Slope); DefineSimpleUnit(MidEQ); DefineSimpleUnit(Median); DefineSimpleUnit(Resonz); DefineSimpleUnit(Ringz); DefineSimpleUnit(Formlet); DefineSimpleUnit(FOS); DefineSimpleUnit(SOS); DefineSimpleUnit(Compander); DefineDtorUnit(Limiter); DefineDtorUnit(Normalizer); DefineSimpleUnit(Amplitude); DefineSimpleUnit(DetectSilence); DefineSimpleUnit(Hilbert); DefineSimpleUnit(FreqShift); DefineSimpleUnit(MoogFF); /* BEQSuite UGens */ DefineSimpleUnit(BLowPass); DefineSimpleUnit(BHiPass); DefineSimpleUnit(BBandPass); DefineSimpleUnit(BBandStop); DefineSimpleUnit(BPeakEQ); DefineSimpleUnit(BAllPass); DefineSimpleUnit(BLowShelf); DefineSimpleUnit(BHiShelf); } //////////////////////////////////////////////////////////////////////////////////////////////////
174,090
C++
.cpp
4,462
32.602869
120
0.518877
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