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.

359 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. if (now == lastTime)
  45. {
  46. wait (1);
  47. continue;
  48. }
  49. const int elapsed = (int) (now >= lastTime ? (now - lastTime)
  50. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  51. lastTime = now;
  52. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  53. if (timeUntilFirstTimer <= 0)
  54. {
  55. /* If we managed to set the atomic boolean to true then send a message, this is needed
  56. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  57. but if it fails it means the message-thread changed the value from under us so at least
  58. some processing is happenening and we can just loop around and try again
  59. */
  60. if (callbackNeeded.compareAndSetBool (1, 0))
  61. {
  62. messageToSend->post();
  63. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  64. when the app has a modal loop), so this is how long to wait before assuming the
  65. message has been lost and trying again.
  66. */
  67. const uint32 messageDeliveryTimeout = now + 300;
  68. while (callbackNeeded.get() != 0)
  69. {
  70. wait (4);
  71. if (threadShouldExit())
  72. return;
  73. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  74. {
  75. messageToSend->post();
  76. break;
  77. }
  78. }
  79. }
  80. }
  81. else
  82. {
  83. // don't wait for too long because running this loop also helps keep the
  84. // Time::getApproximateMillisecondTimer value stay up-to-date
  85. wait (jlimit (1, 50, timeUntilFirstTimer));
  86. }
  87. }
  88. }
  89. void callTimers()
  90. {
  91. const LockType::ScopedLockType sl (lock);
  92. while (firstTimer != nullptr && firstTimer->timerCountdownMs <= 0)
  93. {
  94. Timer* const t = firstTimer;
  95. t->timerCountdownMs = t->timerPeriodMs;
  96. removeTimer (t);
  97. addTimer (t);
  98. const LockType::ScopedUnlockType ul (lock);
  99. JUCE_TRY
  100. {
  101. t->timerCallback();
  102. }
  103. JUCE_CATCH_EXCEPTION
  104. }
  105. /* This is needed as a memory barrier to make sure all processing of current timers is done
  106. before the boolean is set. This set should never fail since if it was false in the first place,
  107. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  108. get a message then the value is true and the other thread can only set it to true again and
  109. we will get another callback to set it to false.
  110. */
  111. callbackNeeded.set (0);
  112. }
  113. void callTimersSynchronously()
  114. {
  115. if (! isThreadRunning())
  116. {
  117. // (This is relied on by some plugins in cases where the MM has
  118. // had to restart and the async callback never started)
  119. cancelPendingUpdate();
  120. triggerAsyncUpdate();
  121. }
  122. callTimers();
  123. }
  124. static inline void add (Timer* const tim) noexcept
  125. {
  126. if (instance == nullptr)
  127. instance = new TimerThread();
  128. instance->addTimer (tim);
  129. }
  130. static inline void remove (Timer* const tim) noexcept
  131. {
  132. if (instance != nullptr)
  133. instance->removeTimer (tim);
  134. }
  135. static inline void resetCounter (Timer* const tim, const int newCounter) noexcept
  136. {
  137. if (instance != nullptr)
  138. {
  139. tim->timerCountdownMs = newCounter;
  140. tim->timerPeriodMs = newCounter;
  141. if ((tim->nextTimer != nullptr && tim->nextTimer->timerCountdownMs < tim->timerCountdownMs)
  142. || (tim->previousTimer != nullptr && tim->previousTimer->timerCountdownMs > tim->timerCountdownMs))
  143. {
  144. instance->removeTimer (tim);
  145. instance->addTimer (tim);
  146. }
  147. }
  148. }
  149. static TimerThread* instance;
  150. static LockType lock;
  151. private:
  152. Timer* volatile firstTimer;
  153. Atomic<int> callbackNeeded;
  154. struct CallTimersMessage : public MessageManager::MessageBase
  155. {
  156. CallTimersMessage() {}
  157. void messageCallback() override
  158. {
  159. if (instance != nullptr)
  160. instance->callTimers();
  161. }
  162. };
  163. //==============================================================================
  164. void addTimer (Timer* const t) noexcept
  165. {
  166. #if JUCE_DEBUG
  167. // trying to add a timer that's already here - shouldn't get to this point,
  168. // so if you get this assertion, let me know!
  169. jassert (! timerExists (t));
  170. #endif
  171. Timer* i = firstTimer;
  172. if (i == nullptr || i->timerCountdownMs > t->timerCountdownMs)
  173. {
  174. t->nextTimer = firstTimer;
  175. firstTimer = t;
  176. }
  177. else
  178. {
  179. while (i->nextTimer != nullptr && i->nextTimer->timerCountdownMs <= t->timerCountdownMs)
  180. i = i->nextTimer;
  181. jassert (i != nullptr);
  182. t->nextTimer = i->nextTimer;
  183. t->previousTimer = i;
  184. i->nextTimer = t;
  185. }
  186. if (t->nextTimer != nullptr)
  187. t->nextTimer->previousTimer = t;
  188. jassert ((t->nextTimer == nullptr || t->nextTimer->timerCountdownMs >= t->timerCountdownMs)
  189. && (t->previousTimer == nullptr || t->previousTimer->timerCountdownMs <= t->timerCountdownMs));
  190. notify();
  191. }
  192. void removeTimer (Timer* const t) noexcept
  193. {
  194. #if JUCE_DEBUG
  195. // trying to remove a timer that's not here - shouldn't get to this point,
  196. // so if you get this assertion, let me know!
  197. jassert (timerExists (t));
  198. #endif
  199. if (t->previousTimer != nullptr)
  200. {
  201. jassert (firstTimer != t);
  202. t->previousTimer->nextTimer = t->nextTimer;
  203. }
  204. else
  205. {
  206. jassert (firstTimer == t);
  207. firstTimer = t->nextTimer;
  208. }
  209. if (t->nextTimer != nullptr)
  210. t->nextTimer->previousTimer = t->previousTimer;
  211. t->nextTimer = nullptr;
  212. t->previousTimer = nullptr;
  213. }
  214. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  215. {
  216. const LockType::ScopedLockType sl (lock);
  217. for (Timer* t = firstTimer; t != nullptr; t = t->nextTimer)
  218. t->timerCountdownMs -= numMillisecsElapsed;
  219. return firstTimer != nullptr ? firstTimer->timerCountdownMs : 1000;
  220. }
  221. void handleAsyncUpdate() override
  222. {
  223. startThread (7);
  224. }
  225. #if JUCE_DEBUG
  226. bool timerExists (Timer* const t) const noexcept
  227. {
  228. for (Timer* tt = firstTimer; tt != nullptr; tt = tt->nextTimer)
  229. if (tt == t)
  230. return true;
  231. return false;
  232. }
  233. #endif
  234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  235. };
  236. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  237. Timer::TimerThread::LockType Timer::TimerThread::lock;
  238. //==============================================================================
  239. Timer::Timer() noexcept
  240. : timerCountdownMs (0),
  241. timerPeriodMs (0),
  242. previousTimer (nullptr),
  243. nextTimer (nullptr)
  244. {
  245. }
  246. Timer::Timer (const Timer&) noexcept
  247. : timerCountdownMs (0),
  248. timerPeriodMs (0),
  249. previousTimer (nullptr),
  250. nextTimer (nullptr)
  251. {
  252. }
  253. Timer::~Timer()
  254. {
  255. stopTimer();
  256. }
  257. void Timer::startTimer (const int interval) noexcept
  258. {
  259. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  260. if (timerPeriodMs == 0)
  261. {
  262. timerCountdownMs = interval;
  263. timerPeriodMs = jmax (1, interval);
  264. TimerThread::add (this);
  265. }
  266. else
  267. {
  268. TimerThread::resetCounter (this, interval);
  269. }
  270. }
  271. void Timer::startTimerHz (int timerFrequencyHz) noexcept
  272. {
  273. if (timerFrequencyHz > 0)
  274. startTimer (1000 / timerFrequencyHz);
  275. else
  276. stopTimer();
  277. }
  278. void Timer::stopTimer() noexcept
  279. {
  280. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  281. if (timerPeriodMs > 0)
  282. {
  283. TimerThread::remove (this);
  284. timerPeriodMs = 0;
  285. }
  286. }
  287. void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
  288. {
  289. if (TimerThread::instance != nullptr)
  290. TimerThread::instance->callTimersSynchronously();
  291. }