The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

357 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. class Timer::TimerThread : private Thread,
  18. private DeletedAtShutdown,
  19. private AsyncUpdater
  20. {
  21. public:
  22. typedef CriticalSection LockType; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
  23. TimerThread()
  24. : Thread ("Juce Timer"),
  25. firstTimer (nullptr),
  26. callbackNeeded (0)
  27. {
  28. triggerAsyncUpdate();
  29. }
  30. ~TimerThread() noexcept
  31. {
  32. stopThread (4000);
  33. jassert (instance == this || instance == nullptr);
  34. if (instance == this)
  35. instance = nullptr;
  36. }
  37. void run() override
  38. {
  39. uint32 lastTime = Time::getMillisecondCounter();
  40. MessageManager::MessageBase::Ptr messageToSend (new CallTimersMessage());
  41. while (! threadShouldExit())
  42. {
  43. const uint32 now = Time::getMillisecondCounter();
  44. const int elapsed = (int) (now >= lastTime ? (now - lastTime)
  45. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  46. lastTime = now;
  47. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  48. if (timeUntilFirstTimer <= 0)
  49. {
  50. /* If we managed to set the atomic boolean to true then send a message, this is needed
  51. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  52. but if it fails it means the message-thread changed the value from under us so at least
  53. some processing is happenening and we can just loop around and try again
  54. */
  55. if (callbackNeeded.compareAndSetBool (1, 0))
  56. {
  57. messageToSend->post();
  58. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  59. when the app has a modal loop), so this is how long to wait before assuming the
  60. message has been lost and trying again.
  61. */
  62. const uint32 messageDeliveryTimeout = now + 300;
  63. while (callbackNeeded.get() != 0)
  64. {
  65. wait (4);
  66. if (threadShouldExit())
  67. return;
  68. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  69. {
  70. messageToSend->post();
  71. break;
  72. }
  73. }
  74. }
  75. else
  76. {
  77. wait (1);
  78. }
  79. }
  80. else
  81. {
  82. // don't wait for too long because running this loop also helps keep the
  83. // Time::getApproximateMillisecondTimer value stay up-to-date
  84. wait (jlimit (1, 50, timeUntilFirstTimer));
  85. }
  86. }
  87. }
  88. void callTimers()
  89. {
  90. const LockType::ScopedLockType sl (lock);
  91. while (firstTimer != nullptr && firstTimer->timerCountdownMs <= 0)
  92. {
  93. Timer* const t = firstTimer;
  94. t->timerCountdownMs = t->timerPeriodMs;
  95. removeTimer (t);
  96. addTimer (t);
  97. const LockType::ScopedUnlockType ul (lock);
  98. JUCE_TRY
  99. {
  100. t->timerCallback();
  101. }
  102. JUCE_CATCH_EXCEPTION
  103. }
  104. /* This is needed as a memory barrier to make sure all processing of current timers is done
  105. before the boolean is set. This set should never fail since if it was false in the first place,
  106. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  107. get a message then the value is true and the other thread can only set it to true again and
  108. we will get another callback to set it to false.
  109. */
  110. callbackNeeded.set (0);
  111. }
  112. void callTimersSynchronously()
  113. {
  114. if (! isThreadRunning())
  115. {
  116. // (This is relied on by some plugins in cases where the MM has
  117. // had to restart and the async callback never started)
  118. cancelPendingUpdate();
  119. triggerAsyncUpdate();
  120. }
  121. callTimers();
  122. }
  123. static inline void add (Timer* const tim) noexcept
  124. {
  125. if (instance == nullptr)
  126. instance = new TimerThread();
  127. instance->addTimer (tim);
  128. }
  129. static inline void remove (Timer* const tim) noexcept
  130. {
  131. if (instance != nullptr)
  132. instance->removeTimer (tim);
  133. }
  134. static inline void resetCounter (Timer* const tim, const int newCounter) noexcept
  135. {
  136. if (instance != nullptr)
  137. {
  138. tim->timerCountdownMs = newCounter;
  139. tim->timerPeriodMs = newCounter;
  140. if ((tim->nextTimer != nullptr && tim->nextTimer->timerCountdownMs < tim->timerCountdownMs)
  141. || (tim->previousTimer != nullptr && tim->previousTimer->timerCountdownMs > tim->timerCountdownMs))
  142. {
  143. instance->removeTimer (tim);
  144. instance->addTimer (tim);
  145. }
  146. }
  147. }
  148. static TimerThread* instance;
  149. static LockType lock;
  150. private:
  151. Timer* volatile firstTimer;
  152. Atomic<int> callbackNeeded;
  153. struct CallTimersMessage : public MessageManager::MessageBase
  154. {
  155. CallTimersMessage() {}
  156. void messageCallback() override
  157. {
  158. if (instance != nullptr)
  159. instance->callTimers();
  160. }
  161. };
  162. //==============================================================================
  163. void addTimer (Timer* const t) noexcept
  164. {
  165. #if JUCE_DEBUG
  166. // trying to add a timer that's already here - shouldn't get to this point,
  167. // so if you get this assertion, let me know!
  168. jassert (! timerExists (t));
  169. #endif
  170. Timer* i = firstTimer;
  171. if (i == nullptr || i->timerCountdownMs > t->timerCountdownMs)
  172. {
  173. t->nextTimer = firstTimer;
  174. firstTimer = t;
  175. }
  176. else
  177. {
  178. while (i->nextTimer != nullptr && i->nextTimer->timerCountdownMs <= t->timerCountdownMs)
  179. i = i->nextTimer;
  180. jassert (i != nullptr);
  181. t->nextTimer = i->nextTimer;
  182. t->previousTimer = i;
  183. i->nextTimer = t;
  184. }
  185. if (t->nextTimer != nullptr)
  186. t->nextTimer->previousTimer = t;
  187. jassert ((t->nextTimer == nullptr || t->nextTimer->timerCountdownMs >= t->timerCountdownMs)
  188. && (t->previousTimer == nullptr || t->previousTimer->timerCountdownMs <= t->timerCountdownMs));
  189. notify();
  190. }
  191. void removeTimer (Timer* const t) noexcept
  192. {
  193. #if JUCE_DEBUG
  194. // trying to remove a timer that's not here - shouldn't get to this point,
  195. // so if you get this assertion, let me know!
  196. jassert (timerExists (t));
  197. #endif
  198. if (t->previousTimer != nullptr)
  199. {
  200. jassert (firstTimer != t);
  201. t->previousTimer->nextTimer = t->nextTimer;
  202. }
  203. else
  204. {
  205. jassert (firstTimer == t);
  206. firstTimer = t->nextTimer;
  207. }
  208. if (t->nextTimer != nullptr)
  209. t->nextTimer->previousTimer = t->previousTimer;
  210. t->nextTimer = nullptr;
  211. t->previousTimer = nullptr;
  212. }
  213. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  214. {
  215. const LockType::ScopedLockType sl (lock);
  216. for (Timer* t = firstTimer; t != nullptr; t = t->nextTimer)
  217. t->timerCountdownMs -= numMillisecsElapsed;
  218. return firstTimer != nullptr ? firstTimer->timerCountdownMs : 1000;
  219. }
  220. void handleAsyncUpdate() override
  221. {
  222. startThread (7);
  223. }
  224. #if JUCE_DEBUG
  225. bool timerExists (Timer* const t) const noexcept
  226. {
  227. for (Timer* tt = firstTimer; tt != nullptr; tt = tt->nextTimer)
  228. if (tt == t)
  229. return true;
  230. return false;
  231. }
  232. #endif
  233. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  234. };
  235. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  236. Timer::TimerThread::LockType Timer::TimerThread::lock;
  237. //==============================================================================
  238. Timer::Timer() noexcept
  239. : timerCountdownMs (0),
  240. timerPeriodMs (0),
  241. previousTimer (nullptr),
  242. nextTimer (nullptr)
  243. {
  244. }
  245. Timer::Timer (const Timer&) noexcept
  246. : timerCountdownMs (0),
  247. timerPeriodMs (0),
  248. previousTimer (nullptr),
  249. nextTimer (nullptr)
  250. {
  251. }
  252. Timer::~Timer()
  253. {
  254. stopTimer();
  255. }
  256. void Timer::startTimer (const int interval) noexcept
  257. {
  258. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  259. if (timerPeriodMs == 0)
  260. {
  261. timerCountdownMs = interval;
  262. timerPeriodMs = jmax (1, interval);
  263. TimerThread::add (this);
  264. }
  265. else
  266. {
  267. TimerThread::resetCounter (this, interval);
  268. }
  269. }
  270. void Timer::startTimerHz (int timerFrequencyHz) noexcept
  271. {
  272. if (timerFrequencyHz > 0)
  273. startTimer (1000 / timerFrequencyHz);
  274. else
  275. stopTimer();
  276. }
  277. void Timer::stopTimer() noexcept
  278. {
  279. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  280. if (timerPeriodMs > 0)
  281. {
  282. TimerThread::remove (this);
  283. timerPeriodMs = 0;
  284. }
  285. }
  286. void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
  287. {
  288. if (TimerThread::instance != nullptr)
  289. TimerThread::instance->callTimersSynchronously();
  290. }