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.

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