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.

379 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. * This is currently a work in progress. The idea is that the user writes a script
  17. * that defines a couple environment variables:
  18. *
  19. * ~vcv_frameDivider: Integer
  20. * ~vcv_bufferSize: Integer
  21. * ~vcv_process: Function (VcvPrototypeProcessBlock -> VcvPrototypeProcessBlock)
  22. *
  23. * ~vcv_process is invoked once per process block. Ideally, users should not manipulate
  24. * the block object in any way other than by writing directly to the arrays in `outputs`,
  25. * `knobs`, `lights`, and `switchLights`.
  26. */
  27. extern rack::plugin::Plugin* pluginInstance; // plugin's version of 'this'
  28. class SuperColliderEngine;
  29. class SC_VcvPrototypeClient final : public SC_LanguageClient {
  30. public:
  31. SC_VcvPrototypeClient(SuperColliderEngine* engine);
  32. ~SC_VcvPrototypeClient();
  33. // These will invoke the interpreter
  34. void interpret(const char * text) noexcept;
  35. void evaluateProcessBlock(ProcessBlock* block) noexcept;
  36. void setNumRows() noexcept {
  37. std::string&& command = "VcvPrototypeProcessBlock.numRows = " + std::to_string(NUM_ROWS);
  38. interpret(command.c_str());
  39. }
  40. int getFrameDivider() noexcept { return getResultAsInt("^~vcv_frameDivider"); }
  41. int getBufferSize() noexcept { return getResultAsInt("^~vcv_bufferSize"); }
  42. bool isOk() const noexcept { return _ok; }
  43. void postText(const char* str, size_t len) override;
  44. // No concept of flushing or stdout vs stderr
  45. void postFlush(const char* str, size_t len) override { postText(str, len); }
  46. void postError(const char* str, size_t len) override { postText(str, len); }
  47. void flush() override {}
  48. private:
  49. std::string buildScProcessBlockString(const ProcessBlock* block) const noexcept;
  50. int getResultAsInt(const char* text) noexcept;
  51. bool isVcvPrototypeProcessBlock(const PyrSlot* slot) const noexcept;
  52. void fail(const std::string& msg) noexcept;
  53. // converts top of stack back to ProcessBlock data
  54. void readScProcessBlockResult(ProcessBlock* block) noexcept;
  55. // helpers for copying SC info back into process block's arrays
  56. template <typename Array>
  57. bool copyArrayOfFloatArrays(const PyrSlot& inSlot, const char* context, Array& array, int size) noexcept;
  58. bool copyFloatArray(const PyrSlot& inSlot, const char* context, float* outArray, int size) noexcept;
  59. SuperColliderEngine* _engine;
  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. }
  118. SC_VcvPrototypeClient::~SC_VcvPrototypeClient() {
  119. shutdownLibrary();
  120. shutdownRuntime();
  121. }
  122. void SC_VcvPrototypeClient::interpret(const char* text) noexcept {
  123. setCmdLine(text);
  124. interpretCmdLine();
  125. }
  126. void SC_VcvPrototypeClient::postText(const char* str, size_t len) {
  127. // Ensure the last message logged (presumably an error) stays onscreen.
  128. if (_ok)
  129. _engine->display(std::string(str, len));
  130. }
  131. constexpr unsigned overhead = 512;
  132. constexpr unsigned floatSize = 10;
  133. constexpr unsigned insOutsSize = MAX_BUFFER_SIZE * NUM_ROWS * 2 * floatSize;
  134. constexpr unsigned otherArraysSize = floatSize * NUM_ROWS * 8;
  135. constexpr unsigned bufferSize = insOutsSize + otherArraysSize + overhead;
  136. static char scratchBuf[bufferSize];
  137. std::string SC_VcvPrototypeClient::buildScProcessBlockString(const ProcessBlock* block) const noexcept {
  138. std::ostringstream builder;
  139. // TODO so expensive
  140. builder << std::fixed; // to ensure floats aren't actually treated as Integers
  141. builder << "^~vcv_process.(VcvPrototypeProcessBlock.new("
  142. << block->sampleRate << ','
  143. << block->sampleTime << ','
  144. << block->bufferSize << ',';
  145. // after this, all floats are printed in float arrays, so we don't need to worry about misinterpreting
  146. builder << std::defaultfloat;
  147. auto&& appendInOutArray = [&builder](const int bufferSize, const float (&data)[NUM_ROWS][MAX_BUFFER_SIZE]) {
  148. builder << '[';
  149. for (int i = 0; i < NUM_ROWS; ++i) {
  150. builder << "FloatArray[";
  151. for (int j = 0; j < bufferSize; ++j) {
  152. builder << data[i][j];
  153. if (j != bufferSize - 1)
  154. builder << ',';
  155. }
  156. builder << ']';
  157. if (i != NUM_ROWS - 1)
  158. builder << ',';
  159. }
  160. builder << ']';
  161. };
  162. appendInOutArray(block->bufferSize, block->inputs);
  163. builder << ',';
  164. appendInOutArray(block->bufferSize, block->outputs);
  165. builder << ',';
  166. // knobs
  167. builder << "FloatArray[";
  168. for (int i = 0; i < NUM_ROWS; ++i) {
  169. builder << block->knobs[i];
  170. if (i != NUM_ROWS - 1)
  171. builder << ',';
  172. }
  173. builder << "],";
  174. // switches
  175. builder << '[' << std::boolalpha;
  176. for (int i = 0; i < NUM_ROWS; ++i) {
  177. builder << block->switches[i];
  178. if (i != NUM_ROWS - 1)
  179. builder << ',';
  180. }
  181. builder << "],";
  182. // lights, switchlights
  183. auto&& appendLightsArray = [&builder](const float (&array)[NUM_ROWS][3]) {
  184. builder << '[';
  185. for (int i = 0; i < NUM_ROWS; ++i) {
  186. builder << "FloatArray[" << array[i][0] << ',' << array[i][1] << ',' << array[i][2] << ']';
  187. if (i != NUM_ROWS - 1)
  188. builder << ',';
  189. }
  190. builder << ']';
  191. };
  192. appendLightsArray(block->lights);
  193. builder << ',';
  194. appendLightsArray(block->switchLights);
  195. builder << "));\n";
  196. return builder.str();
  197. }
  198. bool SC_VcvPrototypeClient::isVcvPrototypeProcessBlock(const PyrSlot* slot) const noexcept {
  199. if (NotObj(slot))
  200. return false;
  201. auto* klass = slotRawObject(slot)->classptr;
  202. auto* klassNameSymbol = slotRawSymbol(&klass->name);
  203. return klassNameSymbol == getsym("VcvPrototypeProcessBlock");
  204. }
  205. template <typename Array>
  206. bool SC_VcvPrototypeClient::copyArrayOfFloatArrays(const PyrSlot& inSlot, const char* context, Array& outArray, int size) noexcept
  207. {
  208. // OUTPUTS
  209. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_array)) {
  210. fail(std::string(context) + " must be a Array");
  211. return false;
  212. }
  213. auto* inObj = slotRawObject(&inSlot);
  214. if (inObj->size != NUM_ROWS) {
  215. fail(std::string(context) + " must be of size " + std::to_string(NUM_ROWS));
  216. return false;
  217. }
  218. const auto subContext = std::string(context) + " subarray";
  219. for (int i = 0; i < NUM_ROWS; ++i) {
  220. if (!copyFloatArray(inObj->slots[i], subContext.c_str(), outArray[i], size)) {
  221. return false;
  222. }
  223. }
  224. return true;
  225. }
  226. bool SC_VcvPrototypeClient::copyFloatArray(const PyrSlot& inSlot, const char* context, float* outArray, int size) noexcept
  227. {
  228. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_floatarray)) {
  229. fail(std::string(context) + " must be a FloatArray");
  230. return false;
  231. }
  232. auto* floatArrayObj = slotRawObject(&inSlot);
  233. if (floatArrayObj->size != size) {
  234. fail(std::string(context) + " must be of size " + std::to_string(size));
  235. return false;
  236. }
  237. auto* floatArray = reinterpret_cast<const PyrFloatArray*>(floatArrayObj);
  238. auto* rawArray = static_cast<const float*>(floatArray->f);
  239. for (int i = 0; i < size; ++i) {
  240. outArray[i] = rawArray[i];
  241. }
  242. return true;
  243. }
  244. void SC_VcvPrototypeClient::readScProcessBlockResult(ProcessBlock* block) noexcept {
  245. auto* resultSlot = &scGlobals()->result;
  246. if (!isVcvPrototypeProcessBlock(resultSlot)) {
  247. fail("Result of ~vcv_process must be an instance of VcvPrototypeProcessBlock");
  248. return;
  249. }
  250. // See .sc object definition
  251. constexpr unsigned outputsSlotIndex = 4;
  252. constexpr unsigned knobsSlotIndex = 5;
  253. constexpr unsigned lightsSlotIndex = 7;
  254. constexpr unsigned switchLightsSlotIndex = 8;
  255. PyrObject* object = slotRawObject(resultSlot);
  256. auto* rawSlots = static_cast<PyrSlot*>(object->slots);
  257. if (!copyArrayOfFloatArrays(rawSlots[outputsSlotIndex], "outputs", block->outputs, block->bufferSize))
  258. return;
  259. if (!copyArrayOfFloatArrays(rawSlots[lightsSlotIndex], "lights", block->lights, 3))
  260. return;
  261. if (!copyArrayOfFloatArrays(rawSlots[switchLightsSlotIndex], "switchLights", block->switchLights, 3))
  262. return;
  263. if (!copyFloatArray(rawSlots[knobsSlotIndex], "knobs", block->knobs, NUM_ROWS))
  264. return;
  265. }
  266. void SC_VcvPrototypeClient::fail(const std::string& msg) noexcept {
  267. _engine->display(msg);
  268. _ok = false;
  269. }
  270. // TODO test code
  271. static long long int gmax = 0;
  272. static constexpr unsigned int nTimes = 1024;
  273. static long long int times[nTimes] = {};
  274. static unsigned int timesIndex = 0;
  275. void SC_VcvPrototypeClient::evaluateProcessBlock(ProcessBlock* block) noexcept {
  276. // TODO timing test code
  277. auto start = std::chrono::high_resolution_clock::now();
  278. auto&& string = buildScProcessBlockString(block);
  279. interpret(string.c_str());
  280. readScProcessBlockResult(block);
  281. auto end = std::chrono::high_resolution_clock::now();
  282. auto ticks = (end - start).count();
  283. times[timesIndex] = ticks;
  284. timesIndex++;
  285. timesIndex %= nTimes;
  286. if (gmax < ticks)
  287. {
  288. gmax = ticks;
  289. printf("MAX TIME %lld\n", ticks);
  290. }
  291. if (timesIndex == 0)
  292. {
  293. printf("AVG TIME %lld\n", std::accumulate(std::begin(times), std::end(times), 0ull) / nTimes);
  294. }
  295. }
  296. int SC_VcvPrototypeClient::getResultAsInt(const char* text) noexcept {
  297. interpret(text);
  298. auto* resultSlot = &scGlobals()->result;
  299. if (IsInt(resultSlot)) {
  300. auto intResult = slotRawInt(resultSlot);
  301. if (intResult > 0) {
  302. return intResult;
  303. } else {
  304. fail(std::string("Result of '") + text + "' should be > 0");
  305. return -1;
  306. }
  307. } else {
  308. fail(std::string("Result of '") + text + "' should be Integer");
  309. return -1;
  310. }
  311. }
  312. __attribute__((constructor(1000)))
  313. static void constructor() {
  314. addScriptEngine<SuperColliderEngine>("sc");
  315. addScriptEngine<SuperColliderEngine>("scd");
  316. }