DISTRHO Plugin Framework
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. /*
  2. * DISTRHO Plugin Framework (DPF)
  3. * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>
  4. * Copyright (C) 2020 Takamitsu Endo
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  7. * or without fee is hereby granted, provided that the above copyright notice and this
  8. * permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  11. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  12. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  13. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  15. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include "DistrhoPlugin.hpp"
  18. START_NAMESPACE_DISTRHO
  19. // -----------------------------------------------------------------------------------------------------------
  20. /**
  21. 1-pole lowpass filter to smooth out parameters and envelopes.
  22. This filter is guaranteed not to overshoot.
  23. */
  24. class Smoother {
  25. float kp;
  26. public:
  27. float value;
  28. Smoother()
  29. : kp(0.0f),
  30. value(0.0f) {}
  31. /**
  32. Set kp from cutoff frequency in Hz.
  33. For derivation, see the answer of Matt L. on the url below. Equation 3 is used.
  34. Computation is done on double for accuracy. When using float, kp will be inaccurate
  35. if the cutoffHz is below around 3.0 to 4.0 Hz.
  36. Reference:
  37. - Single-pole IIR low-pass filter - which is the correct formula for the decay coefficient?
  38. https://dsp.stackexchange.com/questions/54086/single-pole-iir-low-pass-filter-which-is-the-correct-formula-for-the-decay-coe
  39. */
  40. void setCutoff(const float sampleRate, const float cutoffHz)
  41. {
  42. double omega_c = 2.0 * M_PI * cutoffHz / sampleRate;
  43. double y = 1.0 - std::cos(omega_c);
  44. kp = float(-y + std::sqrt((y + 2.0) * y));
  45. }
  46. inline float process(const float input)
  47. {
  48. return value += kp * (input - value);
  49. }
  50. };
  51. // -----------------------------------------------------------------------------------------------------------
  52. /**
  53. Plugin that demonstrates tempo sync in DPF.
  54. The tempo sync implementation is on the first if branch in run() method.
  55. */
  56. class ExamplePluginMetronome : public Plugin
  57. {
  58. public:
  59. ExamplePluginMetronome()
  60. : Plugin(4, 0, 0), // 4 parameters, 0 programs, 0 states
  61. sampleRate(getSampleRate()),
  62. counter(0),
  63. phase(0.0f),
  64. decay(0.0f),
  65. gain(0.5f),
  66. semitone(72),
  67. cent(0),
  68. decayTime(0.2f)
  69. {
  70. sampleRateChanged(sampleRate);
  71. }
  72. protected:
  73. /* --------------------------------------------------------------------------------------------------------
  74. * Information */
  75. /**
  76. Get the plugin label.
  77. A plugin label follows the same rules as Parameter::symbol, with the exception that it can start with numbers.
  78. */
  79. const char* getLabel() const override
  80. {
  81. return "Metronome";
  82. }
  83. /**
  84. Get an extensive comment/description about the plugin.
  85. */
  86. const char* getDescription() const override
  87. {
  88. return "Simple metronome plugin which outputs impulse at the start of every beat.";
  89. }
  90. /**
  91. Get the plugin author/maker.
  92. */
  93. const char* getMaker() const override
  94. {
  95. return "DISTRHO";
  96. }
  97. /**
  98. Get the plugin homepage.
  99. */
  100. const char* getHomePage() const override
  101. {
  102. return "https://github.com/DISTRHO/DPF";
  103. }
  104. /**
  105. Get the plugin license name (a single line of text).
  106. For commercial plugins this should return some short copyright information.
  107. */
  108. const char* getLicense() const override
  109. {
  110. return "ISC";
  111. }
  112. /**
  113. Get the plugin version, in hexadecimal.
  114. */
  115. uint32_t getVersion() const override
  116. {
  117. return d_version(1, 0, 0);
  118. }
  119. /**
  120. Get the plugin unique Id.
  121. This value is used by LADSPA, DSSI and VST plugin formats.
  122. */
  123. int64_t getUniqueId() const override
  124. {
  125. return d_cconst('d', 'M', 'e', 't');
  126. }
  127. /* --------------------------------------------------------------------------------------------------------
  128. * Init */
  129. /**
  130. Initialize the parameter @a index.
  131. This function will be called once, shortly after the plugin is created.
  132. */
  133. void initParameter(uint32_t index, Parameter& parameter) override
  134. {
  135. parameter.hints = kParameterIsAutomable;
  136. switch (index)
  137. {
  138. case 0:
  139. parameter.name = "Gain";
  140. parameter.hints |= kParameterIsLogarithmic;
  141. parameter.ranges.min = 0.001f;
  142. parameter.ranges.max = 1.0f;
  143. parameter.ranges.def = 0.5f;
  144. break;
  145. case 1:
  146. parameter.name = "DecayTime";
  147. parameter.hints |= kParameterIsLogarithmic;
  148. parameter.ranges.min = 0.001f;
  149. parameter.ranges.max = 1.0f;
  150. parameter.ranges.def = 0.2f;
  151. break;
  152. case 2:
  153. parameter.name = "Semitone";
  154. parameter.hints |= kParameterIsInteger;
  155. parameter.ranges.min = 0;
  156. parameter.ranges.max = 127;
  157. parameter.ranges.def = 72;
  158. break;
  159. case 3:
  160. parameter.name = "Cent";
  161. parameter.hints |= kParameterIsInteger;
  162. parameter.ranges.min = -100;
  163. parameter.ranges.max = 100;
  164. parameter.ranges.def = 0;
  165. break;
  166. }
  167. parameter.symbol = parameter.name;
  168. }
  169. /* --------------------------------------------------------------------------------------------------------
  170. * Internal data */
  171. /**
  172. Get the current value of a parameter.
  173. */
  174. float getParameterValue(uint32_t index) const override
  175. {
  176. switch (index)
  177. {
  178. case 0:
  179. return gain;
  180. case 1:
  181. return decayTime;
  182. case 2:
  183. return semitone;
  184. case 3:
  185. return cent;
  186. }
  187. return 0.0f;
  188. }
  189. /**
  190. Change a parameter value.
  191. */
  192. void setParameterValue(uint32_t index, float value) override
  193. {
  194. switch (index)
  195. {
  196. case 0:
  197. gain = value;
  198. break;
  199. case 1:
  200. decayTime = value;
  201. break;
  202. case 2:
  203. semitone = value;
  204. break;
  205. case 3:
  206. cent = value;
  207. break;
  208. }
  209. }
  210. /* --------------------------------------------------------------------------------------------------------
  211. * Process */
  212. /**
  213. Activate this plugin.
  214. We use this to reset our filter states.
  215. */
  216. void activate() override
  217. {
  218. deltaPhaseSmoother.value = 0.0f;
  219. envelopeSmoother.value = 0.0f;
  220. gainSmoother.value = gain;
  221. }
  222. /**
  223. Run/process function for plugins without MIDI input.
  224. `inputs` is commented out because this plugin has no inputs.
  225. */
  226. void run(const float** /* inputs */, float** outputs, uint32_t frames) override
  227. {
  228. const TimePosition& timePos(getTimePosition());
  229. float* const output = outputs[0];
  230. if (timePos.playing && timePos.bbt.valid)
  231. {
  232. // Better to use double when manipulating time.
  233. double secondsPerBeat = 60.0 / timePos.bbt.beatsPerMinute;
  234. double framesPerBeat = sampleRate * secondsPerBeat;
  235. double beatFraction = timePos.bbt.tick / timePos.bbt.ticksPerBeat;
  236. // If beatFraction is zero, next beat is exactly at the start of currenct cycle.
  237. // Otherwise, reset counter to the frames to the next beat.
  238. counter = d_isZero(beatFraction)
  239. ? 0
  240. : static_cast<uint32_t>(framesPerBeat * (1.0 - beatFraction));
  241. // Compute deltaPhase in normalized frequency.
  242. // semitone is midi note number, which is A4 (440Hz at standard tuning) at 69.
  243. // Frequency goes up to 1 octave higher at the start of bar.
  244. float frequency = 440.0f * std::pow(2.0f, (100.0f * (semitone - 69.0f) + cent) / 1200.0f);
  245. float deltaPhase = frequency / sampleRate;
  246. float octave = timePos.bbt.beat == 1 ? 2.0f : 1.0f;
  247. // Envelope reaches 1e-5 at decayTime after triggering.
  248. decay = std::pow(1e-5, 1.0 / (decayTime * sampleRate));
  249. // Reset phase and frequency at the start of transpose.
  250. if (!wasPlaying)
  251. {
  252. phase = 0.0f;
  253. deltaPhaseSmoother.value = deltaPhase;
  254. envelopeSmoother.value = 0.0f;
  255. gainSmoother.value = 0.0f;
  256. }
  257. for (uint32_t i = 0; i < frames; ++i)
  258. {
  259. if (counter <= 0)
  260. {
  261. envelope = 1.0f;
  262. counter = static_cast<uint32_t>(framesPerBeat + 0.5);
  263. octave = (!wasPlaying || timePos.bbt.beat == static_cast<int32_t>(timePos.bbt.beatsPerBar)) ? 2.0f
  264. : 1.0f;
  265. }
  266. --counter;
  267. envelope *= decay;
  268. phase += octave * deltaPhaseSmoother.process(deltaPhase);
  269. phase -= std::floor(phase);
  270. output[i] = gainSmoother.process(gain)
  271. * envelopeSmoother.process(envelope)
  272. * std::sin(float(2.0 * M_PI) * phase);
  273. }
  274. }
  275. else
  276. {
  277. // Stop metronome if not playing or timePos.bbt is invalid.
  278. std::memset(output, 0, sizeof(float)*frames);
  279. }
  280. wasPlaying = timePos.playing;
  281. }
  282. /* --------------------------------------------------------------------------------------------------------
  283. * Callbacks (optional) */
  284. /**
  285. Optional callback to inform the plugin about a sample rate change.
  286. This function will only be called when the plugin is deactivated.
  287. */
  288. void sampleRateChanged(double newSampleRate) override
  289. {
  290. sampleRate = newSampleRate;
  291. // Cutoff value was tuned manually.
  292. deltaPhaseSmoother.setCutoff(sampleRate, 100.0f);
  293. gainSmoother.setCutoff(sampleRate, 500.0f);
  294. envelopeSmoother.setCutoff(sampleRate, 250.0f);
  295. }
  296. // -------------------------------------------------------------------------------------------------------
  297. private:
  298. float sampleRate;
  299. uint32_t counter; // Stores number of frames to the next beat.
  300. bool wasPlaying; // Used to reset phase and frequency at the start of transpose.
  301. float phase; // Sine wave phase. Normalized in [0, 1).
  302. float envelope; // Current value of gain envelope.
  303. float decay; // Coefficient to decay envelope in a frame.
  304. Smoother deltaPhaseSmoother;
  305. Smoother envelopeSmoother;
  306. Smoother gainSmoother;
  307. // Parameters.
  308. float gain;
  309. float semitone;
  310. float cent;
  311. float decayTime;
  312. /**
  313. Set our plugin class as non-copyable and add a leak detector just in case.
  314. */
  315. DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExamplePluginMetronome)
  316. };
  317. /* ------------------------------------------------------------------------------------------------------------
  318. * Plugin entry point, called by DPF to create a new plugin instance. */
  319. Plugin* createPlugin()
  320. {
  321. return new ExamplePluginMetronome();
  322. }
  323. // -----------------------------------------------------------------------------------------------------------
  324. END_NAMESPACE_DISTRHO