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.

371 lines
11KB

  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. std::string SC_VcvPrototypeClient::buildScProcessBlockString(const ProcessBlock* block) const noexcept {
  132. std::ostringstream builder;
  133. // TODO so expensive
  134. builder << std::fixed; // to ensure floats aren't actually treated as Integers
  135. builder << "^~vcv_process.(VcvPrototypeProcessBlock.new("
  136. << block->sampleRate << ','
  137. << block->sampleTime << ','
  138. << block->bufferSize << ',';
  139. // after this, all floats are printed in float arrays, so we don't need to worry about misinterpreting
  140. builder << std::defaultfloat;
  141. auto&& appendInOutArray = [&builder](const int bufferSize, const float (&data)[NUM_ROWS][MAX_BUFFER_SIZE]) {
  142. builder << '[';
  143. for (int i = 0; i < NUM_ROWS; ++i) {
  144. builder << "FloatArray[";
  145. for (int j = 0; j < bufferSize; ++j) {
  146. builder << data[i][j];
  147. if (j != bufferSize - 1)
  148. builder << ',';
  149. }
  150. builder << ']';
  151. if (i != NUM_ROWS - 1)
  152. builder << ',';
  153. }
  154. builder << ']';
  155. };
  156. appendInOutArray(block->bufferSize, block->inputs);
  157. builder << ',';
  158. appendInOutArray(block->bufferSize, block->outputs);
  159. builder << ',';
  160. // knobs
  161. builder << "FloatArray[";
  162. for (int i = 0; i < NUM_ROWS; ++i) {
  163. builder << block->knobs[i];
  164. if (i != NUM_ROWS - 1)
  165. builder << ',';
  166. }
  167. builder << "],";
  168. // switches
  169. builder << '[' << std::boolalpha;
  170. for (int i = 0; i < NUM_ROWS; ++i) {
  171. builder << block->switches[i];
  172. if (i != NUM_ROWS - 1)
  173. builder << ',';
  174. }
  175. builder << "],";
  176. // lights, switchlights
  177. auto&& appendLightsArray = [&builder](const float (&array)[NUM_ROWS][3]) {
  178. builder << '[';
  179. for (int i = 0; i < NUM_ROWS; ++i) {
  180. builder << "FloatArray[" << array[i][0] << ',' << array[i][1] << ',' << array[i][2] << ']';
  181. if (i != NUM_ROWS - 1)
  182. builder << ',';
  183. }
  184. builder << ']';
  185. };
  186. appendLightsArray(block->lights);
  187. builder << ',';
  188. appendLightsArray(block->switchLights);
  189. builder << "));\n";
  190. return builder.str();
  191. }
  192. bool SC_VcvPrototypeClient::isVcvPrototypeProcessBlock(const PyrSlot* slot) const noexcept {
  193. if (NotObj(slot))
  194. return false;
  195. auto* klass = slotRawObject(slot)->classptr;
  196. auto* klassNameSymbol = slotRawSymbol(&klass->name);
  197. return klassNameSymbol == getsym("VcvPrototypeProcessBlock");
  198. }
  199. template <typename Array>
  200. bool SC_VcvPrototypeClient::copyArrayOfFloatArrays(const PyrSlot& inSlot, const char* context, Array& outArray, int size) noexcept
  201. {
  202. // OUTPUTS
  203. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_array)) {
  204. fail(std::string(context) + " must be a Array");
  205. return false;
  206. }
  207. auto* inObj = slotRawObject(&inSlot);
  208. if (inObj->size != NUM_ROWS) {
  209. fail(std::string(context) + " must be of size " + std::to_string(NUM_ROWS));
  210. return false;
  211. }
  212. const auto subContext = std::string(context) + " subarray";
  213. for (int i = 0; i < NUM_ROWS; ++i) {
  214. if (!copyFloatArray(inObj->slots[i], subContext.c_str(), outArray[i], size)) {
  215. return false;
  216. }
  217. }
  218. return true;
  219. }
  220. bool SC_VcvPrototypeClient::copyFloatArray(const PyrSlot& inSlot, const char* context, float* outArray, int size) noexcept
  221. {
  222. if (!isKindOfSlot(const_cast<PyrSlot*>(&inSlot), class_floatarray)) {
  223. fail(std::string(context) + " must be a FloatArray");
  224. return false;
  225. }
  226. auto* floatArrayObj = slotRawObject(&inSlot);
  227. if (floatArrayObj->size != size) {
  228. fail(std::string(context) + " must be of size " + std::to_string(size));
  229. return false;
  230. }
  231. auto* floatArray = reinterpret_cast<const PyrFloatArray*>(floatArrayObj);
  232. auto* rawArray = static_cast<const float*>(floatArray->f);
  233. for (int i = 0; i < size; ++i) {
  234. outArray[i] = rawArray[i];
  235. }
  236. return true;
  237. }
  238. void SC_VcvPrototypeClient::readScProcessBlockResult(ProcessBlock* block) noexcept {
  239. auto* resultSlot = &scGlobals()->result;
  240. if (!isVcvPrototypeProcessBlock(resultSlot)) {
  241. fail("Result of ~vcv_process must be an instance of VcvPrototypeProcessBlock");
  242. return;
  243. }
  244. // See .sc object definition
  245. constexpr unsigned outputsSlotIndex = 4;
  246. constexpr unsigned knobsSlotIndex = 5;
  247. constexpr unsigned lightsSlotIndex = 7;
  248. constexpr unsigned switchLightsSlotIndex = 8;
  249. PyrObject* object = slotRawObject(resultSlot);
  250. auto* rawSlots = static_cast<PyrSlot*>(object->slots);
  251. if (!copyArrayOfFloatArrays(rawSlots[outputsSlotIndex], "outputs", block->outputs, block->bufferSize))
  252. return;
  253. if (!copyArrayOfFloatArrays(rawSlots[lightsSlotIndex], "lights", block->lights, 3))
  254. return;
  255. if (!copyArrayOfFloatArrays(rawSlots[switchLightsSlotIndex], "switchLights", block->switchLights, 3))
  256. return;
  257. if (!copyFloatArray(rawSlots[knobsSlotIndex], "knobs", block->knobs, NUM_ROWS))
  258. return;
  259. }
  260. void SC_VcvPrototypeClient::fail(const std::string& msg) noexcept {
  261. _engine->display(msg);
  262. _ok = false;
  263. }
  264. // TODO test code
  265. static long long int gmax = 0;
  266. static constexpr unsigned int nTimes = 1024;
  267. static long long int times[nTimes] = {};
  268. static unsigned int timesIndex = 0;
  269. void SC_VcvPrototypeClient::evaluateProcessBlock(ProcessBlock* block) noexcept {
  270. // TODO timing test code
  271. auto start = std::chrono::high_resolution_clock::now();
  272. auto&& string = buildScProcessBlockString(block);
  273. interpret(string.c_str());
  274. readScProcessBlockResult(block);
  275. auto end = std::chrono::high_resolution_clock::now();
  276. auto ticks = (end - start).count();
  277. times[timesIndex] = ticks;
  278. timesIndex++;
  279. timesIndex %= nTimes;
  280. if (gmax < ticks)
  281. {
  282. gmax = ticks;
  283. printf("MAX TIME %lld\n", ticks);
  284. }
  285. if (timesIndex == 0)
  286. {
  287. printf("AVG TIME %lld\n", std::accumulate(std::begin(times), std::end(times), 0ull) / nTimes);
  288. }
  289. }
  290. int SC_VcvPrototypeClient::getResultAsInt(const char* text) noexcept {
  291. interpret(text);
  292. auto* resultSlot = &scGlobals()->result;
  293. if (IsInt(resultSlot)) {
  294. auto intResult = slotRawInt(resultSlot);
  295. if (intResult > 0) {
  296. return intResult;
  297. } else {
  298. fail(std::string("Result of '") + text + "' should be > 0");
  299. return -1;
  300. }
  301. } else {
  302. fail(std::string("Result of '") + text + "' should be Integer");
  303. return -1;
  304. }
  305. }
  306. __attribute__((constructor(1000)))
  307. static void constructor() {
  308. addScriptEngine<SuperColliderEngine>("sc");
  309. addScriptEngine<SuperColliderEngine>("scd");
  310. }