Audio plugin host https://kx.studio/carla
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.

372 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. class Timer::TimerThread : private Thread,
  20. private DeletedAtShutdown,
  21. private AsyncUpdater
  22. {
  23. public:
  24. typedef CriticalSection LockType; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
  25. TimerThread()
  26. : Thread ("Juce Timer"),
  27. firstTimer (nullptr)
  28. {
  29. triggerAsyncUpdate();
  30. }
  31. ~TimerThread() noexcept
  32. {
  33. signalThreadShouldExit();
  34. callbackArrived.signal();
  35. stopThread (4000);
  36. jassert (instance == this || instance == nullptr);
  37. if (instance == this)
  38. instance = nullptr;
  39. }
  40. void run() override
  41. {
  42. uint32 lastTime = Time::getMillisecondCounter();
  43. MessageManager::MessageBase::Ptr messageToSend (new CallTimersMessage());
  44. while (! threadShouldExit())
  45. {
  46. const uint32 now = Time::getMillisecondCounter();
  47. const int elapsed = (int) (now >= lastTime ? (now - lastTime)
  48. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  49. lastTime = now;
  50. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  51. if (timeUntilFirstTimer <= 0)
  52. {
  53. if (callbackArrived.wait (0))
  54. {
  55. // already a message in flight - do nothing..
  56. }
  57. else
  58. {
  59. messageToSend->post();
  60. if (! callbackArrived.wait (300))
  61. {
  62. // Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  63. // when the app has a modal loop), so this is how long to wait before assuming the
  64. // message has been lost and trying again.
  65. messageToSend->post();
  66. }
  67. continue;
  68. }
  69. }
  70. // don't wait for too long because running this loop also helps keep the
  71. // Time::getApproximateMillisecondTimer value stay up-to-date
  72. wait (jlimit (1, 100, timeUntilFirstTimer));
  73. }
  74. }
  75. void callTimers()
  76. {
  77. // avoid getting stuck in a loop if a timer callback repeatedly takes too long
  78. const uint32 timeout = Time::getMillisecondCounter() + 100;
  79. const LockType::ScopedLockType sl (lock);
  80. while (firstTimer != nullptr && firstTimer->timerCountdownMs <= 0)
  81. {
  82. Timer* const t = firstTimer;
  83. t->timerCountdownMs = t->timerPeriodMs;
  84. removeTimer (t);
  85. addTimer (t);
  86. const LockType::ScopedUnlockType ul (lock);
  87. JUCE_TRY
  88. {
  89. t->timerCallback();
  90. }
  91. JUCE_CATCH_EXCEPTION
  92. if (Time::getMillisecondCounter() > timeout)
  93. break;
  94. }
  95. callbackArrived.signal();
  96. }
  97. void callTimersSynchronously()
  98. {
  99. if (! isThreadRunning())
  100. {
  101. // (This is relied on by some plugins in cases where the MM has
  102. // had to restart and the async callback never started)
  103. cancelPendingUpdate();
  104. triggerAsyncUpdate();
  105. }
  106. callTimers();
  107. }
  108. static inline void add (Timer* const tim) noexcept
  109. {
  110. if (instance == nullptr)
  111. instance = new TimerThread();
  112. instance->addTimer (tim);
  113. }
  114. static inline void remove (Timer* const tim) noexcept
  115. {
  116. if (instance != nullptr)
  117. instance->removeTimer (tim);
  118. }
  119. static inline void resetCounter (Timer* const tim, const int newCounter) noexcept
  120. {
  121. if (instance != nullptr)
  122. {
  123. tim->timerCountdownMs = newCounter;
  124. tim->timerPeriodMs = newCounter;
  125. if ((tim->nextTimer != nullptr && tim->nextTimer->timerCountdownMs < tim->timerCountdownMs)
  126. || (tim->previousTimer != nullptr && tim->previousTimer->timerCountdownMs > tim->timerCountdownMs))
  127. {
  128. instance->removeTimer (tim);
  129. instance->addTimer (tim);
  130. }
  131. }
  132. }
  133. static TimerThread* instance;
  134. static LockType lock;
  135. private:
  136. Timer* volatile firstTimer;
  137. WaitableEvent callbackArrived;
  138. struct CallTimersMessage : public MessageManager::MessageBase
  139. {
  140. CallTimersMessage() {}
  141. void messageCallback() override
  142. {
  143. if (instance != nullptr)
  144. instance->callTimers();
  145. }
  146. };
  147. //==============================================================================
  148. void addTimer (Timer* const t) noexcept
  149. {
  150. #if JUCE_DEBUG
  151. // trying to add a timer that's already here - shouldn't get to this point,
  152. // so if you get this assertion, let me know!
  153. jassert (! timerExists (t));
  154. #endif
  155. Timer* i = firstTimer;
  156. if (i == nullptr || i->timerCountdownMs > t->timerCountdownMs)
  157. {
  158. t->nextTimer = firstTimer;
  159. firstTimer = t;
  160. }
  161. else
  162. {
  163. while (i->nextTimer != nullptr && i->nextTimer->timerCountdownMs <= t->timerCountdownMs)
  164. i = i->nextTimer;
  165. jassert (i != nullptr);
  166. t->nextTimer = i->nextTimer;
  167. t->previousTimer = i;
  168. i->nextTimer = t;
  169. }
  170. if (t->nextTimer != nullptr)
  171. t->nextTimer->previousTimer = t;
  172. jassert ((t->nextTimer == nullptr || t->nextTimer->timerCountdownMs >= t->timerCountdownMs)
  173. && (t->previousTimer == nullptr || t->previousTimer->timerCountdownMs <= t->timerCountdownMs));
  174. notify();
  175. }
  176. void removeTimer (Timer* const t) noexcept
  177. {
  178. #if JUCE_DEBUG
  179. // trying to remove a timer that's not here - shouldn't get to this point,
  180. // so if you get this assertion, let me know!
  181. jassert (timerExists (t));
  182. #endif
  183. if (t->previousTimer != nullptr)
  184. {
  185. jassert (firstTimer != t);
  186. t->previousTimer->nextTimer = t->nextTimer;
  187. }
  188. else
  189. {
  190. jassert (firstTimer == t);
  191. firstTimer = t->nextTimer;
  192. }
  193. if (t->nextTimer != nullptr)
  194. t->nextTimer->previousTimer = t->previousTimer;
  195. t->nextTimer = nullptr;
  196. t->previousTimer = nullptr;
  197. }
  198. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  199. {
  200. const LockType::ScopedLockType sl (lock);
  201. for (Timer* t = firstTimer; t != nullptr; t = t->nextTimer)
  202. t->timerCountdownMs -= numMillisecsElapsed;
  203. return firstTimer != nullptr ? firstTimer->timerCountdownMs : 1000;
  204. }
  205. void handleAsyncUpdate() override
  206. {
  207. startThread (7);
  208. }
  209. #if JUCE_DEBUG
  210. bool timerExists (Timer* const t) const noexcept
  211. {
  212. for (Timer* tt = firstTimer; tt != nullptr; tt = tt->nextTimer)
  213. if (tt == t)
  214. return true;
  215. return false;
  216. }
  217. #endif
  218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  219. };
  220. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  221. Timer::TimerThread::LockType Timer::TimerThread::lock;
  222. //==============================================================================
  223. Timer::Timer() noexcept
  224. : timerCountdownMs (0),
  225. timerPeriodMs (0),
  226. previousTimer (nullptr),
  227. nextTimer (nullptr)
  228. {
  229. }
  230. Timer::Timer (const Timer&) noexcept
  231. : timerCountdownMs (0),
  232. timerPeriodMs (0),
  233. previousTimer (nullptr),
  234. nextTimer (nullptr)
  235. {
  236. }
  237. Timer::~Timer()
  238. {
  239. stopTimer();
  240. }
  241. void Timer::startTimer (const int interval) noexcept
  242. {
  243. // If you're calling this before (or after) the MessageManager is
  244. // running, then you're not going to get any timer callbacks!
  245. jassert (MessageManager::getInstanceWithoutCreating() != nullptr);
  246. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  247. if (timerPeriodMs == 0)
  248. {
  249. timerCountdownMs = interval;
  250. timerPeriodMs = jmax (1, interval);
  251. TimerThread::add (this);
  252. }
  253. else
  254. {
  255. TimerThread::resetCounter (this, interval);
  256. }
  257. }
  258. void Timer::startTimerHz (int timerFrequencyHz) noexcept
  259. {
  260. if (timerFrequencyHz > 0)
  261. startTimer (1000 / timerFrequencyHz);
  262. else
  263. stopTimer();
  264. }
  265. void Timer::stopTimer() noexcept
  266. {
  267. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  268. if (timerPeriodMs > 0)
  269. {
  270. TimerThread::remove (this);
  271. timerPeriodMs = 0;
  272. }
  273. }
  274. void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
  275. {
  276. if (TimerThread::instance != nullptr)
  277. TimerThread::instance->callTimersSynchronously();
  278. }
  279. struct LambdaInvoker : private Timer
  280. {
  281. LambdaInvoker (int milliseconds, std::function<void()> f) : function (f)
  282. {
  283. startTimer (milliseconds);
  284. }
  285. void timerCallback() override
  286. {
  287. auto f = function;
  288. delete this;
  289. f();
  290. }
  291. std::function<void()> function;
  292. JUCE_DECLARE_NON_COPYABLE (LambdaInvoker)
  293. };
  294. void JUCE_CALLTYPE Timer::callAfterDelay (int milliseconds, std::function<void()> f)
  295. {
  296. new LambdaInvoker (milliseconds, f);
  297. }
  298. } // namespace juce