You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

366 lines
12KB

  1. #include "ScriptEngine.hpp"
  2. #include "lang/SC_LanguageClient.h"
  3. #include "LangSource/SC_LanguageConfig.hpp"
  4. #include "LangSource/SCBase.h"
  5. #include "LangSource/VMGlobals.h"
  6. #include "LangSource/PyrObject.h"
  7. #include "LangSource/PyrKernel.h"
  8. #include <thread>
  9. #include <atomic>
  10. #include <numeric>
  11. #include <unistd.h> // getcwd
  12. // SuperCollider script engine for VCV-Prototype
  13. // Original author: Brian Heim <brianlheim@gmail.com>
  14. /* DESIGN
  15. *
  16. * The idea is that the user writes a script that defines a couple environment variables:
  17. *
  18. * ~vcv_frameDivider: Integer
  19. * ~vcv_bufferSize: Integer
  20. * ~vcv_process: Function (VcvPrototypeProcessBlock -> VcvPrototypeProcessBlock)
  21. *
  22. * ~vcv_process is invoked once per process block. Users should not manipulate
  23. * the block object in any way other than by writing directly to the arrays in `outputs`,
  24. * `knobs`, `lights`, and `switchLights`.
  25. */
  26. extern rack::plugin::Plugin* pluginInstance; // plugin's version of 'this'
  27. class SuperColliderEngine;
  28. class SC_VcvPrototypeClient final : public SC_LanguageClient {
  29. public:
  30. SC_VcvPrototypeClient(SuperColliderEngine* engine);
  31. ~SC_VcvPrototypeClient();
  32. // These will invoke the interpreter
  33. void interpret(const char * text) noexcept;
  34. void evaluateProcessBlock(ProcessBlock* block) noexcept;
  35. void setNumRows() noexcept {
  36. std::string&& command = "VcvPrototypeProcessBlock.numRows = " + std::to_string(NUM_ROWS);
  37. interpret(command.c_str());
  38. }
  39. int getFrameDivider() noexcept { return getResultAsInt("^~vcv_frameDivider"); }
  40. int getBufferSize() noexcept { return getResultAsInt("^~vcv_bufferSize"); }
  41. bool isOk() const noexcept { return _ok; }
  42. void postText(const char* str, size_t len) override;
  43. // No concept of flushing or stdout vs stderr
  44. void postFlush(const char* str, size_t len) override { postText(str, len); }
  45. void postError(const char* str, size_t len) override { postText(str, len); }
  46. void flush() override {}
  47. private:
  48. const char* buildScProcessBlockString(const ProcessBlock* block) const noexcept;
  49. int getResultAsInt(const char* text) noexcept;
  50. bool isVcvPrototypeProcessBlock(const PyrSlot* slot) const noexcept;
  51. void fail(const std::string& msg) noexcept;
  52. // converts top of stack back to ProcessBlock data
  53. void readScProcessBlockResult(ProcessBlock* block) noexcept;
  54. // helpers for copying SC info back into process block's arrays
  55. template <typename Array>
  56. bool copyArrayOfFloatArrays(const PyrSlot& inSlot, const char* context, Array& array, int size) noexcept;
  57. bool copyFloatArray(const PyrSlot& inSlot, const char* context, float* outArray, int size) noexcept;
  58. SuperColliderEngine* _engine;
  59. PyrSymbol* _vcvPrototypeProcessBlockSym;
  60. bool _ok = true;
  61. };
  62. class SuperColliderEngine final : public ScriptEngine {
  63. public:
  64. ~SuperColliderEngine() noexcept { _clientThread.join(); }
  65. std::string getEngineName() override { return "SuperCollider"; }
  66. int run(const std::string& path, const std::string& script) override {
  67. if (!_clientThread.joinable()) {
  68. _clientThread = std::thread([this, script]() {
  69. _client.reset(new SC_VcvPrototypeClient(this));
  70. _client->setNumRows();
  71. _client->interpret(script.c_str());
  72. setFrameDivider(_client->getFrameDivider());
  73. setBufferSize(_client->getBufferSize());
  74. finishClientLoading();
  75. });
  76. }
  77. return 0;
  78. }
  79. int process() override {
  80. if (waitingOnClient())
  81. return 0;
  82. if (clientHasError())
  83. return 1;
  84. _client->evaluateProcessBlock(getProcessBlock());
  85. return clientHasError() ? 1 : 0;
  86. }
  87. private:
  88. bool waitingOnClient() const noexcept { return !_clientRunning; }
  89. bool clientHasError() const noexcept { return !_client->isOk(); }
  90. void finishClientLoading() noexcept { _clientRunning = true; }
  91. std::unique_ptr<SC_VcvPrototypeClient> _client;
  92. std::thread _clientThread; // used only to start up client
  93. std::atomic_bool _clientRunning{false}; // set to true when client is ready to process data
  94. };
  95. SC_VcvPrototypeClient::SC_VcvPrototypeClient(SuperColliderEngine* engine)
  96. : SC_LanguageClient("SC VCV-Prototype client")
  97. , _engine(engine)
  98. {
  99. using Path = SC_LanguageConfig::Path;
  100. Path sc_lib_root = rack::asset::plugin(pluginInstance, "dep/supercollider/SCClassLibrary");
  101. Path sc_ext_root = rack::asset::plugin(pluginInstance, "dep/supercollider_extensions");
  102. Path sc_yaml_path = rack::asset::plugin(pluginInstance, "dep/supercollider/sclang_vcv_config.yml");
  103. if (!SC_LanguageConfig::defaultLibraryConfig(/* isStandalone */ true))
  104. fail("Failed setting default library config");
  105. if (!gLanguageConfig->addIncludedDirectory(sc_lib_root))
  106. fail("Failed to add main include directory");
  107. if (!gLanguageConfig->addIncludedDirectory(sc_ext_root))
  108. fail("Failed to add extensions include directory");
  109. if (!SC_LanguageConfig::writeLibraryConfigYAML(sc_yaml_path))
  110. fail("Failed to write library config YAML file");
  111. SC_LanguageConfig::setConfigPath(sc_yaml_path);
  112. // TODO allow users to add extensions somehow?
  113. initRuntime();
  114. compileLibrary(/* isStandalone */ true);
  115. if (!isLibraryCompiled())
  116. fail("Error while compiling class library");
  117. _vcvPrototypeProcessBlockSym = getsym("VcvPrototypeProcessBlock");
  118. }
  119. SC_VcvPrototypeClient::~SC_VcvPrototypeClient() {
  120. shutdownLibrary();
  121. shutdownRuntime();
  122. }
  123. void SC_VcvPrototypeClient::interpret(const char* text) noexcept {
  124. setCmdLine(text);
  125. interpretCmdLine();
  126. }
  127. void SC_VcvPrototypeClient::postText(const char* str, size_t len) {
  128. // Ensure the last message logged (presumably an error) stays onscreen.
  129. if (_ok)
  130. _engine->display(std::string(str, len));
  131. }
  132. // This should be well above what we ever need to represent a process block.
  133. constexpr unsigned overhead = 512;
  134. constexpr unsigned floatSize = 10;
  135. constexpr unsigned insOutsSize = MAX_BUFFER_SIZE * NUM_ROWS * 2 * floatSize;
  136. constexpr unsigned otherArraysSize = floatSize * NUM_ROWS * 8;
  137. constexpr unsigned bufferSize = overhead + insOutsSize + otherArraysSize;
  138. // Don't write initial string every time
  139. #define PROCESS_BEGIN_STRING "^~vcv_process.(VcvPrototypeProcessBlock.new("
  140. static char processBlockStringScratchBuf[bufferSize] = PROCESS_BEGIN_STRING;
  141. constexpr unsigned processBeginStringOffset = sizeof(PROCESS_BEGIN_STRING);
  142. #undef PROCESS_BEGIN_STRING
  143. const char* SC_VcvPrototypeClient::buildScProcessBlockString(const ProcessBlock* block) const noexcept {
  144. auto* buf = processBlockStringScratchBuf + processBeginStringOffset - 1;
  145. // Perhaps imprudently assuming snprintf never returns a negative code
  146. buf += std::sprintf(buf, "%.6f,%.6f,%d,", block->sampleRate, block->sampleTime, block->bufferSize);
  147. auto&& appendInOutArray = [&buf](const int bufferSize, const float (&data)[NUM_ROWS][MAX_BUFFER_SIZE]) {
  148. buf += std::sprintf(buf, "[");
  149. for (int i = 0; i < NUM_ROWS; ++i) {
  150. buf += std::sprintf(buf, "Signal[");
  151. for (int j = 0; j < bufferSize; ++j) {
  152. buf += std::sprintf(buf, "%g%c", data[i][j], j == bufferSize - 1 ? ' ' : ',');
  153. }
  154. buf += std::sprintf(buf, "]%c", i == NUM_ROWS - 1 ? ' ' : ',');
  155. }
  156. buf += std::sprintf(buf, "],");
  157. };
  158. appendInOutArray(block->bufferSize, block->inputs);
  159. appendInOutArray(block->bufferSize, block->outputs);
  160. // knobs
  161. buf += std::sprintf(buf, "FloatArray[");
  162. for (int i = 0; i < NUM_ROWS; ++i)
  163. buf += std::sprintf(buf, "%g%c", block->knobs[i], i == NUM_ROWS - 1 ? ' ' : ',');
  164. // switches
  165. buf += std::sprintf(buf, "],[");
  166. for (int i = 0; i < NUM_ROWS; ++i)
  167. buf += std::sprintf(buf, "%s%c", block->switches[i] ? "true" : "false", i == NUM_ROWS - 1 ? ' ' : ',');
  168. buf += std::sprintf(buf, "]");
  169. // lights, switchlights
  170. auto&& appendLightsArray = [&buf](const float (&array)[NUM_ROWS][3]) {
  171. buf += std::sprintf(buf, ",[");
  172. for (int i = 0; i < NUM_ROWS; ++i) {
  173. buf += std::sprintf(buf, "FloatArray[%g,%g,%g]%c", array[i][0], array[i][1], array[i][2],
  174. i == NUM_ROWS - 1 ? ' ' : ',');
  175. }
  176. buf += std::sprintf(buf, "]");
  177. };
  178. appendLightsArray(block->lights);
  179. appendLightsArray(block->switchLights);
  180. buf += std::sprintf(buf, "));");
  181. return processBlockStringScratchBuf;
  182. }
  183. bool SC_VcvPrototypeClient::isVcvPrototypeProcessBlock(const PyrSlot* slot) const noexcept {
  184. if (NotObj(slot))
  185. return false;
  186. auto* klass = slotRawObject(slot)->classptr;
  187. auto* klassNameSymbol = slotRawSymbol(&klass->name);
  188. return klassNameSymbol == _vcvPrototypeProcessBlockSym;
  189. }
  190. template <typename Array>
  191. bool SC_VcvPrototypeClient::copyArrayOfFloatArrays(const PyrSlot& inSlot, const char* context, Array& outArray, int size) noexcept
  192. {
  193. // OUTPUTS
  194. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_array)) {
  195. fail(std::string(context) + " must be a Array");
  196. return false;
  197. }
  198. auto* inObj = slotRawObject(&inSlot);
  199. if (inObj->size != NUM_ROWS) {
  200. fail(std::string(context) + " must be of size " + std::to_string(NUM_ROWS));
  201. return false;
  202. }
  203. for (int i = 0; i < NUM_ROWS; ++i) {
  204. if (!copyFloatArray(inObj->slots[i], "subarray", outArray[i], size)) {
  205. return false;
  206. }
  207. }
  208. return true;
  209. }
  210. bool SC_VcvPrototypeClient::copyFloatArray(const PyrSlot& inSlot, const char* context, float* outArray, int size) noexcept
  211. {
  212. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_floatarray)) {
  213. fail(std::string(context) + " must be a FloatArray");
  214. return false;
  215. }
  216. auto* floatArrayObj = slotRawObject(&inSlot);
  217. if (floatArrayObj->size != size) {
  218. fail(std::string(context) + " must be of size " + std::to_string(size));
  219. return false;
  220. }
  221. auto* floatArray = reinterpret_cast<const PyrFloatArray*>(floatArrayObj);
  222. auto* rawArray = static_cast<const float*>(floatArray->f);
  223. std::memcpy(outArray, rawArray, size * sizeof(float));
  224. return true;
  225. }
  226. void SC_VcvPrototypeClient::readScProcessBlockResult(ProcessBlock* block) noexcept {
  227. auto* resultSlot = &scGlobals()->result;
  228. if (!isVcvPrototypeProcessBlock(resultSlot)) {
  229. fail("Result of ~vcv_process must be an instance of VcvPrototypeProcessBlock");
  230. return;
  231. }
  232. PyrObject* object = slotRawObject(resultSlot);
  233. auto* rawSlots = static_cast<PyrSlot*>(object->slots);
  234. // See .sc object definition
  235. constexpr unsigned outputsSlotIndex = 4;
  236. constexpr unsigned knobsSlotIndex = 5;
  237. constexpr unsigned lightsSlotIndex = 7;
  238. constexpr unsigned switchLightsSlotIndex = 8;
  239. if (!copyArrayOfFloatArrays(rawSlots[outputsSlotIndex], "outputs", block->outputs, block->bufferSize))
  240. return;
  241. if (!copyArrayOfFloatArrays(rawSlots[lightsSlotIndex], "lights", block->lights, 3))
  242. return;
  243. if (!copyArrayOfFloatArrays(rawSlots[switchLightsSlotIndex], "switchLights", block->switchLights, 3))
  244. return;
  245. if (!copyFloatArray(rawSlots[knobsSlotIndex], "knobs", block->knobs, NUM_ROWS))
  246. return;
  247. }
  248. void SC_VcvPrototypeClient::fail(const std::string& msg) noexcept {
  249. _engine->display(msg);
  250. _ok = false;
  251. }
  252. #ifdef SC_VCV_ENGINE_TIMING
  253. static long long int gmax = 0;
  254. static constexpr unsigned int nTimes = 1024;
  255. static long long int times[nTimes] = {};
  256. static unsigned int timesIndex = 0;
  257. #endif
  258. void SC_VcvPrototypeClient::evaluateProcessBlock(ProcessBlock* block) noexcept {
  259. #ifdef SC_VCV_ENGINE_TIMING
  260. auto start = std::chrono::high_resolution_clock::now();
  261. #endif
  262. auto* buf = buildScProcessBlockString(block);
  263. interpret(buf);
  264. readScProcessBlockResult(block);
  265. #ifdef SC_VCV_ENGINE_TIMING
  266. auto end = std::chrono::high_resolution_clock::now();
  267. auto ticks = (end - start).count();
  268. times[timesIndex] = ticks;
  269. timesIndex++;
  270. timesIndex %= nTimes;
  271. if (gmax < ticks)
  272. {
  273. gmax = ticks;
  274. std::printf("MAX TIME %lld\n", ticks);
  275. }
  276. if (timesIndex == 0)
  277. {
  278. std::printf("AVG TIME %lld\n", std::accumulate(std::begin(times), std::end(times), 0ull) / nTimes);
  279. }
  280. #endif
  281. }
  282. int SC_VcvPrototypeClient::getResultAsInt(const char* text) noexcept {
  283. interpret(text);
  284. auto* resultSlot = &scGlobals()->result;
  285. if (IsInt(resultSlot)) {
  286. auto intResult = slotRawInt(resultSlot);
  287. if (intResult > 0) {
  288. return intResult;
  289. } else {
  290. fail(std::string("Result of '") + text + "' should be > 0");
  291. return -1;
  292. }
  293. } else {
  294. fail(std::string("Result of '") + text + "' should be Integer");
  295. return -1;
  296. }
  297. }
  298. __attribute__((constructor(1000)))
  299. static void constructor() {
  300. addScriptEngine<SuperColliderEngine>("sc");
  301. addScriptEngine<SuperColliderEngine>("scd");
  302. }