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.

381 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. wasPlaying(false),
  64. phase(0.0f),
  65. envelope(1.0f),
  66. decay(0.0f),
  67. gain(0.5f),
  68. semitone(72),
  69. cent(0),
  70. decayTime(0.2f)
  71. {
  72. sampleRateChanged(sampleRate);
  73. }
  74. protected:
  75. /* --------------------------------------------------------------------------------------------------------
  76. * Information */
  77. /**
  78. Get the plugin label.
  79. A plugin label follows the same rules as Parameter::symbol, with the exception that it can start with numbers.
  80. */
  81. const char* getLabel() const override
  82. {
  83. return "Metronome";
  84. }
  85. /**
  86. Get an extensive comment/description about the plugin.
  87. */
  88. const char* getDescription() const override
  89. {
  90. return "Simple metronome plugin which outputs impulse at the start of every beat.";
  91. }
  92. /**
  93. Get the plugin author/maker.
  94. */
  95. const char* getMaker() const override
  96. {
  97. return "DISTRHO";
  98. }
  99. /**
  100. Get the plugin homepage.
  101. */
  102. const char* getHomePage() const override
  103. {
  104. return "https://github.com/DISTRHO/DPF";
  105. }
  106. /**
  107. Get the plugin license name (a single line of text).
  108. For commercial plugins this should return some short copyright information.
  109. */
  110. const char* getLicense() const override
  111. {
  112. return "ISC";
  113. }
  114. /**
  115. Get the plugin version, in hexadecimal.
  116. */
  117. uint32_t getVersion() const override
  118. {
  119. return d_version(1, 0, 0);
  120. }
  121. /**
  122. Get the plugin unique Id.
  123. This value is used by LADSPA, DSSI and VST plugin formats.
  124. */
  125. int64_t getUniqueId() const override
  126. {
  127. return d_cconst('d', 'M', 'e', 't');
  128. }
  129. /* --------------------------------------------------------------------------------------------------------
  130. * Init */
  131. /**
  132. Initialize the parameter @a index.
  133. This function will be called once, shortly after the plugin is created.
  134. */
  135. void initParameter(uint32_t index, Parameter& parameter) override
  136. {
  137. parameter.hints = kParameterIsAutomatable;
  138. switch (index)
  139. {
  140. case 0:
  141. parameter.name = "Gain";
  142. parameter.hints |= kParameterIsLogarithmic;
  143. parameter.ranges.min = 0.001f;
  144. parameter.ranges.max = 1.0f;
  145. parameter.ranges.def = 0.5f;
  146. break;
  147. case 1:
  148. parameter.name = "DecayTime";
  149. parameter.hints |= kParameterIsLogarithmic;
  150. parameter.ranges.min = 0.001f;
  151. parameter.ranges.max = 1.0f;
  152. parameter.ranges.def = 0.2f;
  153. break;
  154. case 2:
  155. parameter.name = "Semitone";
  156. parameter.hints |= kParameterIsInteger;
  157. parameter.ranges.min = 0;
  158. parameter.ranges.max = 127;
  159. parameter.ranges.def = 72;
  160. break;
  161. case 3:
  162. parameter.name = "Cent";
  163. parameter.hints |= kParameterIsInteger;
  164. parameter.ranges.min = -100;
  165. parameter.ranges.max = 100;
  166. parameter.ranges.def = 0;
  167. break;
  168. }
  169. parameter.symbol = parameter.name;
  170. }
  171. /* --------------------------------------------------------------------------------------------------------
  172. * Internal data */
  173. /**
  174. Get the current value of a parameter.
  175. */
  176. float getParameterValue(uint32_t index) const override
  177. {
  178. switch (index)
  179. {
  180. case 0:
  181. return gain;
  182. case 1:
  183. return decayTime;
  184. case 2:
  185. return semitone;
  186. case 3:
  187. return cent;
  188. }
  189. return 0.0f;
  190. }
  191. /**
  192. Change a parameter value.
  193. */
  194. void setParameterValue(uint32_t index, float value) override
  195. {
  196. switch (index)
  197. {
  198. case 0:
  199. gain = value;
  200. break;
  201. case 1:
  202. decayTime = value;
  203. break;
  204. case 2:
  205. semitone = value;
  206. break;
  207. case 3:
  208. cent = value;
  209. break;
  210. }
  211. }
  212. /* --------------------------------------------------------------------------------------------------------
  213. * Process */
  214. /**
  215. Activate this plugin.
  216. We use this to reset our filter states.
  217. */
  218. void activate() override
  219. {
  220. deltaPhaseSmoother.value = 0.0f;
  221. envelopeSmoother.value = 0.0f;
  222. gainSmoother.value = gain;
  223. }
  224. /**
  225. Run/process function for plugins without MIDI input.
  226. `inputs` is commented out because this plugin has no inputs.
  227. */
  228. void run(const float** /* inputs */, float** outputs, uint32_t frames) override
  229. {
  230. const TimePosition& timePos(getTimePosition());
  231. float* const output = outputs[0];
  232. if (timePos.playing && timePos.bbt.valid)
  233. {
  234. // Better to use double when manipulating time.
  235. double secondsPerBeat = 60.0 / timePos.bbt.beatsPerMinute;
  236. double framesPerBeat = sampleRate * secondsPerBeat;
  237. double beatFraction = timePos.bbt.tick / timePos.bbt.ticksPerBeat;
  238. // If beatFraction is zero, next beat is exactly at the start of currenct cycle.
  239. // Otherwise, reset counter to the frames to the next beat.
  240. counter = d_isZero(beatFraction)
  241. ? 0
  242. : static_cast<uint32_t>(framesPerBeat * (1.0 - beatFraction));
  243. // Compute deltaPhase in normalized frequency.
  244. // semitone is midi note number, which is A4 (440Hz at standard tuning) at 69.
  245. // Frequency goes up to 1 octave higher at the start of bar.
  246. float frequency = 440.0f * std::pow(2.0f, (100.0f * (semitone - 69.0f) + cent) / 1200.0f);
  247. float deltaPhase = frequency / sampleRate;
  248. float octave = timePos.bbt.beat == 1 ? 2.0f : 1.0f;
  249. // Envelope reaches 1e-5 at decayTime after triggering.
  250. decay = std::pow(1e-5, 1.0 / (decayTime * sampleRate));
  251. // Reset phase and frequency at the start of transpose.
  252. if (!wasPlaying)
  253. {
  254. phase = 0.0f;
  255. deltaPhaseSmoother.value = deltaPhase;
  256. envelopeSmoother.value = 0.0f;
  257. gainSmoother.value = 0.0f;
  258. }
  259. for (uint32_t i = 0; i < frames; ++i)
  260. {
  261. if (counter <= 0)
  262. {
  263. envelope = 1.0f;
  264. counter = static_cast<uint32_t>(framesPerBeat + 0.5);
  265. octave = (!wasPlaying || timePos.bbt.beat == static_cast<int32_t>(timePos.bbt.beatsPerBar)) ? 2.0f
  266. : 1.0f;
  267. }
  268. --counter;
  269. envelope *= decay;
  270. phase += octave * deltaPhaseSmoother.process(deltaPhase);
  271. phase -= std::floor(phase);
  272. output[i] = gainSmoother.process(gain)
  273. * envelopeSmoother.process(envelope)
  274. * std::sin(float(2.0 * M_PI) * phase);
  275. }
  276. }
  277. else
  278. {
  279. // Stop metronome if not playing or timePos.bbt is invalid.
  280. std::memset(output, 0, sizeof(float)*frames);
  281. }
  282. wasPlaying = timePos.playing;
  283. }
  284. /* --------------------------------------------------------------------------------------------------------
  285. * Callbacks (optional) */
  286. /**
  287. Optional callback to inform the plugin about a sample rate change.
  288. This function will only be called when the plugin is deactivated.
  289. */
  290. void sampleRateChanged(double newSampleRate) override
  291. {
  292. sampleRate = newSampleRate;
  293. // Cutoff value was tuned manually.
  294. deltaPhaseSmoother.setCutoff(sampleRate, 100.0f);
  295. gainSmoother.setCutoff(sampleRate, 500.0f);
  296. envelopeSmoother.setCutoff(sampleRate, 250.0f);
  297. }
  298. // -------------------------------------------------------------------------------------------------------
  299. private:
  300. float sampleRate;
  301. uint32_t counter; // Stores number of frames to the next beat.
  302. bool wasPlaying; // Used to reset phase and frequency at the start of transpose.
  303. float phase; // Sine wave phase. Normalized in [0, 1).
  304. float envelope; // Current value of gain envelope.
  305. float decay; // Coefficient to decay envelope in a frame.
  306. Smoother deltaPhaseSmoother;
  307. Smoother envelopeSmoother;
  308. Smoother gainSmoother;
  309. // Parameters.
  310. float gain;
  311. float semitone;
  312. float cent;
  313. float decayTime;
  314. /**
  315. Set our plugin class as non-copyable and add a leak detector just in case.
  316. */
  317. DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExamplePluginMetronome)
  318. };
  319. /* ------------------------------------------------------------------------------------------------------------
  320. * Plugin entry point, called by DPF to create a new plugin instance. */
  321. Plugin* createPlugin()
  322. {
  323. return new ExamplePluginMetronome();
  324. }
  325. // -----------------------------------------------------------------------------------------------------------
  326. END_NAMESPACE_DISTRHO