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.

479 lines
15KB

  1. #pragma once
  2. #include <vector>
  3. #include <jansson.h>
  4. #include <common.hpp>
  5. #include <string.hpp>
  6. #include <plugin/Model.hpp>
  7. #include <engine/Param.hpp>
  8. #include <engine/Port.hpp>
  9. #include <engine/Light.hpp>
  10. #include <engine/ParamQuantity.hpp>
  11. #include <engine/PortInfo.hpp>
  12. #include <engine/LightInfo.hpp>
  13. namespace rack {
  14. namespace plugin {
  15. struct Model;
  16. }
  17. namespace engine {
  18. /** DSP processor instance for your module. */
  19. struct Module {
  20. struct Internal;
  21. Internal* internal;
  22. /** Not owned. */
  23. plugin::Model* model = NULL;
  24. /** Unique ID for referring to the module in the engine.
  25. Between 0 and 2^53-1 since the number is serialized with JSON.
  26. Assigned when added to the engine.
  27. */
  28. int64_t id = -1;
  29. /** Arrays of components.
  30. Initialized using config().
  31. It is recommended to call getParam(), getInput(), etc. instead of accessing these directly.
  32. */
  33. std::vector<Param> params;
  34. std::vector<Input> inputs;
  35. std::vector<Output> outputs;
  36. std::vector<Light> lights;
  37. /** Arrays of component metadata.
  38. Initialized using configParam(), configInput(), configOutput(), and configLight().
  39. LightInfos are initialized to null unless configLight() is called.
  40. It is recommended to call getParamQuantity(), getInputInfo(), etc. instead of accessing these directly.
  41. */
  42. std::vector<ParamQuantity*> paramQuantities;
  43. std::vector<PortInfo*> inputInfos;
  44. std::vector<PortInfo*> outputInfos;
  45. std::vector<LightInfo*> lightInfos;
  46. /** Represents a message-passing channel for an adjacent module. */
  47. struct Expander {
  48. /** ID of the expander module, or -1 if nonexistent. */
  49. int64_t moduleId = -1;
  50. /** Pointer to the expander Module, or NULL if nonexistent. */
  51. Module* module = NULL;
  52. /** Double buffer for receiving messages from the expander module.
  53. If you intend to receive messages from an expander, allocate both message buffers with identical blocks of memory (arrays, structs, etc).
  54. Remember to free the buffer in the Module destructor.
  55. Example:
  56. rightExpander.producerMessage = new MyExpanderMessage;
  57. rightExpander.consumerMessage = new MyExpanderMessage;
  58. You must check the expander module's `model` before attempting to write its message buffer.
  59. Once the module is checked, you can reinterpret_cast its producerMessage at no performance cost.
  60. Producer messages are intended to be write-only.
  61. Consumer messages are intended to be read-only.
  62. Once you write a message, set messageFlipRequested to true to request that the messages are flipped at the end of the timestep.
  63. This means that message-passing has 1-sample latency.
  64. You may choose for your Module to instead write to its own message buffer for consumption by other modules, i.e. the expander "pulls" rather than this module "pushing".
  65. As long as this convention is followed by the other module, this is fine.
  66. */
  67. void* producerMessage = NULL;
  68. void* consumerMessage = NULL;
  69. bool messageFlipRequested = false;
  70. void requestMessageFlip() {
  71. messageFlipRequested = true;
  72. }
  73. };
  74. Expander leftExpander;
  75. Expander rightExpander;
  76. struct BypassRoute {
  77. int inputId = -1;
  78. int outputId = -1;
  79. };
  80. std::vector<BypassRoute> bypassRoutes;
  81. /** Constructs a Module with no params, inputs, outputs, and lights. */
  82. Module();
  83. /** Use config() instead. */
  84. DEPRECATED Module(int numParams, int numInputs, int numOutputs, int numLights = 0) : Module() {
  85. config(numParams, numInputs, numOutputs, numLights);
  86. }
  87. virtual ~Module();
  88. /** Configures the number of Params, Outputs, Inputs, and Lights.
  89. Should only be called from a Module subclass's constructor.
  90. */
  91. void config(int numParams, int numInputs, int numOutputs, int numLights = 0);
  92. /** Helper for creating a ParamQuantity and setting its properties.
  93. See ParamQuantity for documentation of arguments.
  94. Should only be called from a Module subclass's constructor.
  95. */
  96. template <class TParamQuantity = ParamQuantity>
  97. TParamQuantity* configParam(int paramId, float minValue, float maxValue, float defaultValue, std::string name = "", std::string unit = "", float displayBase = 0.f, float displayMultiplier = 1.f, float displayOffset = 0.f) {
  98. assert(paramId < (int) params.size() && paramId < (int) paramQuantities.size());
  99. if (paramQuantities[paramId])
  100. delete paramQuantities[paramId];
  101. TParamQuantity* q = new TParamQuantity;
  102. q->ParamQuantity::module = this;
  103. q->ParamQuantity::paramId = paramId;
  104. q->ParamQuantity::minValue = minValue;
  105. q->ParamQuantity::maxValue = maxValue;
  106. q->ParamQuantity::defaultValue = defaultValue;
  107. q->ParamQuantity::name = name;
  108. q->ParamQuantity::unit = unit;
  109. q->ParamQuantity::displayBase = displayBase;
  110. q->ParamQuantity::displayMultiplier = displayMultiplier;
  111. q->ParamQuantity::displayOffset = displayOffset;
  112. paramQuantities[paramId] = q;
  113. Param* p = &params[paramId];
  114. p->value = q->getDefaultValue();
  115. return q;
  116. }
  117. /** Helper for creating a SwitchQuantity and setting its label strings.
  118. See ParamQuantity and SwitchQuantity for documentation of arguments.
  119. Should only be called from a Module subclass's constructor.
  120. */
  121. template <class TSwitchQuantity = SwitchQuantity>
  122. TSwitchQuantity* configSwitch(int paramId, float minValue, float maxValue, float defaultValue, std::string name = "", std::vector<std::string> labels = {}) {
  123. TSwitchQuantity* sq = configParam<TSwitchQuantity>(paramId, minValue, maxValue, defaultValue, name);
  124. sq->ParamQuantity::snapEnabled = true;
  125. sq->ParamQuantity::smoothEnabled = false;
  126. sq->SwitchQuantity::labels = labels;
  127. return sq;
  128. }
  129. /** Helper for creating a SwitchQuantity with no label.
  130. Should only be called from a Module subclass's constructor.
  131. */
  132. template <class TSwitchQuantity = SwitchQuantity>
  133. TSwitchQuantity* configButton(int paramId, std::string name = "") {
  134. TSwitchQuantity* sq = configParam<TSwitchQuantity>(paramId, 0.f, 1.f, 0.f, name);
  135. sq->ParamQuantity::snapEnabled = true;
  136. sq->ParamQuantity::smoothEnabled = false;
  137. sq->ParamQuantity::randomizeEnabled = false;
  138. return sq;
  139. }
  140. /** Helper for creating a PortInfo for an input port and setting its properties.
  141. See PortInfo for documentation of arguments.
  142. Should only be called from a Module subclass's constructor.
  143. */
  144. template <class TPortInfo = PortInfo>
  145. TPortInfo* configInput(int portId, std::string name = "") {
  146. assert(portId < (int) inputs.size() && portId < (int) inputInfos.size());
  147. if (inputInfos[portId])
  148. delete inputInfos[portId];
  149. TPortInfo* info = new TPortInfo;
  150. info->PortInfo::module = this;
  151. info->PortInfo::type = Port::INPUT;
  152. info->PortInfo::portId = portId;
  153. info->PortInfo::name = name;
  154. inputInfos[portId] = info;
  155. return info;
  156. }
  157. /** Helper for creating a PortInfo for an output port and setting its properties.
  158. See PortInfo for documentation of arguments.
  159. Should only be called from a Module subclass's constructor.
  160. */
  161. template <class TPortInfo = PortInfo>
  162. TPortInfo* configOutput(int portId, std::string name = "") {
  163. assert(portId < (int) outputs.size() && portId < (int) outputInfos.size());
  164. if (outputInfos[portId])
  165. delete outputInfos[portId];
  166. TPortInfo* info = new TPortInfo;
  167. info->PortInfo::module = this;
  168. info->PortInfo::type = Port::OUTPUT;
  169. info->PortInfo::portId = portId;
  170. info->PortInfo::name = name;
  171. outputInfos[portId] = info;
  172. return info;
  173. }
  174. /** Helper for creating a LightInfo and setting its properties.
  175. For multi-colored lights, use the first lightId.
  176. See LightInfo for documentation of arguments.
  177. Should only be called from a Module subclass's constructor.
  178. */
  179. template <class TLightInfo = LightInfo>
  180. TLightInfo* configLight(int lightId, std::string name = "") {
  181. assert(lightId < (int) lights.size() && lightId < (int) lightInfos.size());
  182. if (lightInfos[lightId])
  183. delete lightInfos[lightId];
  184. TLightInfo* info = new TLightInfo;
  185. info->LightInfo::module = this;
  186. info->LightInfo::lightId = lightId;
  187. info->LightInfo::name = name;
  188. lightInfos[lightId] = info;
  189. return info;
  190. }
  191. /** Adds a direct route from an input to an output when the module is bypassed.
  192. Should only be called from a Module subclass's constructor.
  193. */
  194. void configBypass(int inputId, int outputId) {
  195. assert(inputId < (int) inputs.size());
  196. assert(outputId < (int) outputs.size());
  197. // Check that output is not yet routed
  198. for (BypassRoute& br : bypassRoutes) {
  199. // Prevent unused variable warning for compilers that ignore assert()
  200. (void) br;
  201. assert(br.outputId != outputId);
  202. }
  203. BypassRoute br;
  204. br.inputId = inputId;
  205. br.outputId = outputId;
  206. bypassRoutes.push_back(br);
  207. }
  208. /** Creates and returns the module's patch storage directory path.
  209. Do not call this method in process() since filesystem operations block the audio thread.
  210. Throws an Exception if Module is not yet added to the Engine.
  211. Therefore, you may not call these methods in your Module constructor.
  212. Instead, load patch storage files in onAdd() and save them in onSave().
  213. Patch storage files of deleted modules are garbage collected when user saves the patch.
  214. To allow the Undo feature to restore patch storage if the module is accidentally deleted, it is recommended to not delete patch storage in onRemove().
  215. */
  216. std::string createPatchStorageDirectory();
  217. std::string getPatchStorageDirectory();
  218. /** Getters for members */
  219. plugin::Model* getModel() {
  220. return model;
  221. }
  222. int64_t getId() {
  223. return id;
  224. }
  225. int getNumParams() {
  226. return params.size();
  227. }
  228. Param& getParam(int index) {
  229. return params[index];
  230. }
  231. int getNumInputs() {
  232. return inputs.size();
  233. }
  234. Input& getInput(int index) {
  235. return inputs[index];
  236. }
  237. int getNumOutputs() {
  238. return outputs.size();
  239. }
  240. Output& getOutput(int index) {
  241. return outputs[index];
  242. }
  243. int getNumLights() {
  244. return lights.size();
  245. }
  246. Light& getLight(int index) {
  247. return lights[index];
  248. }
  249. ParamQuantity* getParamQuantity(int index) {
  250. return paramQuantities[index];
  251. }
  252. PortInfo* getInputInfo(int index) {
  253. return inputInfos[index];
  254. }
  255. PortInfo* getOutputInfo(int index) {
  256. return outputInfos[index];
  257. }
  258. LightInfo* getLightInfo(int index) {
  259. return lightInfos[index];
  260. }
  261. Expander& getLeftExpander() {
  262. return leftExpander;
  263. }
  264. Expander& getRightExpander() {
  265. return rightExpander;
  266. }
  267. /** Returns the left Expander for `side = 0` and the right Expander for `side = 1`. */
  268. Expander& getExpander(uint8_t side) {
  269. return side ? rightExpander : leftExpander;
  270. }
  271. // Virtual methods
  272. struct ProcessArgs {
  273. /** The current sample rate in Hz. */
  274. float sampleRate;
  275. /** The timestep of process() in seconds.
  276. Defined by `1 / sampleRate`.
  277. */
  278. float sampleTime;
  279. /** Number of audio samples since the Engine's first sample. */
  280. int64_t frame;
  281. };
  282. /** Advances the module by one audio sample.
  283. Override this method to read Inputs and Params and to write Outputs and Lights.
  284. */
  285. virtual void process(const ProcessArgs& args) {
  286. step();
  287. }
  288. /** DEPRECATED. Override `process(const ProcessArgs& args)` instead. */
  289. virtual void step() {}
  290. /** Called instead of process() when Module is bypassed.
  291. Typically you do not need to override this. Use configBypass() instead.
  292. If you do override it, avoid reading param values, since the state of the module should have no effect on routing.
  293. */
  294. virtual void processBypass(const ProcessArgs& args);
  295. /** Usually you should override dataToJson() instead.
  296. There are very few reasons you should override this (perhaps to lock a mutex while serialization is occurring).
  297. */
  298. virtual json_t* toJson();
  299. /** This is virtual only for the purpose of unserializing legacy data when you could set properties of the `.modules[]` object itself.
  300. Normally you should override dataFromJson().
  301. Remember to call `Module::fromJson(rootJ)` within your overridden method.
  302. */
  303. virtual void fromJson(json_t* rootJ);
  304. /** Serializes the "params" object. */
  305. virtual json_t* paramsToJson();
  306. virtual void paramsFromJson(json_t* rootJ);
  307. /** Override to store extra internal data in the "data" property of the module's JSON object. */
  308. virtual json_t* dataToJson() {
  309. return NULL;
  310. }
  311. /** Override to load internal data from the "data" property of the module's JSON object.
  312. Not called if "data" property is not present.
  313. */
  314. virtual void dataFromJson(json_t* rootJ) {}
  315. ///////////////////////
  316. // Events
  317. ///////////////////////
  318. // All of these events are thread-safe with process().
  319. struct AddEvent {};
  320. /** Called after adding the module to the Engine.
  321. */
  322. virtual void onAdd(const AddEvent& e) {
  323. // Call deprecated event method by default
  324. onAdd();
  325. }
  326. struct RemoveEvent {};
  327. /** Called before removing the module from the Engine.
  328. */
  329. virtual void onRemove(const RemoveEvent& e) {
  330. // Call deprecated event method by default
  331. onRemove();
  332. }
  333. struct BypassEvent {};
  334. /** Called after bypassing the module.
  335. */
  336. virtual void onBypass(const BypassEvent& e) {}
  337. struct UnBypassEvent {};
  338. /** Called after enabling the module.
  339. */
  340. virtual void onUnBypass(const UnBypassEvent& e) {}
  341. struct PortChangeEvent {
  342. /** True if connecting, false if disconnecting. */
  343. bool connecting;
  344. /** Port::INPUT or Port::OUTPUT */
  345. Port::Type type;
  346. int portId;
  347. };
  348. /** Called after a cable connects to or disconnects from a port.
  349. This event is not called for output ports if a stackable cable was added/removed and did not change the port's connected state.
  350. */
  351. virtual void onPortChange(const PortChangeEvent& e) {}
  352. struct SampleRateChangeEvent {
  353. float sampleRate;
  354. float sampleTime;
  355. };
  356. /** Called when the Engine sample rate changes, and when the Module is added to the Engine.
  357. */
  358. virtual void onSampleRateChange(const SampleRateChangeEvent& e) {
  359. // Call deprecated event method by default
  360. onSampleRateChange();
  361. }
  362. struct ExpanderChangeEvent {
  363. /** 0 for left, 1 for right. */
  364. uint8_t side;
  365. };
  366. /** Called after an expander is added, removed, or changed on either the left or right side of the Module.
  367. */
  368. virtual void onExpanderChange(const ExpanderChangeEvent& e) {}
  369. struct ResetEvent {};
  370. /** Called when the user resets (initializes) the module.
  371. The default implementation resets all parameters to their default value, so you must call `Module::onReset(e)` in your overridden method if you want to keep this behavior.
  372. */
  373. virtual void onReset(const ResetEvent& e);
  374. struct RandomizeEvent {};
  375. /** Called when the user randomizes the module.
  376. The default implementation randomizes all parameters by default, so you must call `Module::onRandomize(e)` in your overridden method if you want to keep this behavior.
  377. */
  378. virtual void onRandomize(const RandomizeEvent& e);
  379. struct SaveEvent {};
  380. /** Called when the user saves the patch to a file.
  381. If your module uses patch asset storage, make sure all files are saved in this event.
  382. */
  383. virtual void onSave(const SaveEvent& e) {}
  384. struct SetMasterEvent {};
  385. virtual void onSetMaster(const SetMasterEvent& e) {}
  386. struct UnsetMasterEvent {};
  387. virtual void onUnsetMaster(const UnsetMasterEvent& e) {}
  388. /** DEPRECATED. Override `onAdd(e)` instead. */
  389. virtual void onAdd() {}
  390. /** DEPRECATED. Override `onRemove(e)` instead. */
  391. virtual void onRemove() {}
  392. /** DEPRECATED. Override `onReset(e)` instead. */
  393. virtual void onReset() {}
  394. /** DEPRECATED. Override `onRandomize(e)` instead. */
  395. virtual void onRandomize() {}
  396. /** DEPRECATED. Override `onSampleRateChange(e)` instead. */
  397. virtual void onSampleRateChange() {}
  398. bool isBypassed();
  399. PRIVATE void setBypassed(bool bypassed);
  400. PRIVATE const float* meterBuffer();
  401. PRIVATE int meterLength();
  402. PRIVATE int meterIndex();
  403. PRIVATE void doProcess(const ProcessArgs& args);
  404. PRIVATE static void jsonStripIds(json_t* rootJ);
  405. /** Sets module of expander and dispatches ExpanderChangeEvent if changed. */
  406. PRIVATE void setExpanderModule(Module* module, uint8_t side);
  407. };
  408. } // namespace engine
  409. } // namespace rack