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.

390 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. using LockType = CriticalSection; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
  25. TimerThread() : Thread ("JUCE Timer")
  26. {
  27. timers.reserve (32);
  28. triggerAsyncUpdate();
  29. }
  30. ~TimerThread() override
  31. {
  32. signalThreadShouldExit();
  33. callbackArrived.signal();
  34. stopThread (4000);
  35. jassert (instance == this || instance == nullptr);
  36. if (instance == this)
  37. instance = nullptr;
  38. }
  39. void run() override
  40. {
  41. auto lastTime = Time::getMillisecondCounter();
  42. ReferenceCountedObjectPtr<CallTimersMessage> messageToSend (new CallTimersMessage());
  43. while (! threadShouldExit())
  44. {
  45. auto now = Time::getMillisecondCounter();
  46. auto elapsed = (int) (now >= lastTime ? (now - lastTime)
  47. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  48. lastTime = now;
  49. auto timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  50. if (timeUntilFirstTimer <= 0)
  51. {
  52. if (callbackArrived.wait (0))
  53. {
  54. // already a message in flight - do nothing..
  55. }
  56. else
  57. {
  58. messageToSend->post();
  59. if (! callbackArrived.wait (300))
  60. {
  61. // Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  62. // when the app has a modal loop), so this is how long to wait before assuming the
  63. // message has been lost and trying again.
  64. messageToSend->post();
  65. }
  66. continue;
  67. }
  68. }
  69. // don't wait for too long because running this loop also helps keep the
  70. // Time::getApproximateMillisecondTimer value stay up-to-date
  71. wait (jlimit (1, 100, timeUntilFirstTimer));
  72. }
  73. }
  74. void callTimers()
  75. {
  76. auto timeout = Time::getMillisecondCounter() + 100;
  77. const LockType::ScopedLockType sl (lock);
  78. while (! timers.empty())
  79. {
  80. auto& first = timers.front();
  81. if (first.countdownMs > 0)
  82. break;
  83. auto* timer = first.timer;
  84. first.countdownMs = timer->timerPeriodMs;
  85. shuffleTimerBackInQueue (0);
  86. notify();
  87. const LockType::ScopedUnlockType ul (lock);
  88. JUCE_TRY
  89. {
  90. timer->timerCallback();
  91. }
  92. JUCE_CATCH_EXCEPTION
  93. // avoid getting stuck in a loop if a timer callback repeatedly takes too long
  94. if (Time::getMillisecondCounter() > timeout)
  95. break;
  96. }
  97. callbackArrived.signal();
  98. }
  99. void callTimersSynchronously()
  100. {
  101. if (! isThreadRunning())
  102. {
  103. // (This is relied on by some plugins in cases where the MM has
  104. // had to restart and the async callback never started)
  105. cancelPendingUpdate();
  106. triggerAsyncUpdate();
  107. }
  108. callTimers();
  109. }
  110. static inline void add (Timer* tim) noexcept
  111. {
  112. if (instance == nullptr)
  113. instance = new TimerThread();
  114. instance->addTimer (tim);
  115. }
  116. static inline void remove (Timer* tim) noexcept
  117. {
  118. if (instance != nullptr)
  119. instance->removeTimer (tim);
  120. }
  121. static inline void resetCounter (Timer* tim) noexcept
  122. {
  123. if (instance != nullptr)
  124. instance->resetTimerCounter (tim);
  125. }
  126. static TimerThread* instance;
  127. static LockType lock;
  128. private:
  129. struct TimerCountdown
  130. {
  131. Timer* timer;
  132. int countdownMs;
  133. };
  134. std::vector<TimerCountdown> timers;
  135. WaitableEvent callbackArrived;
  136. struct CallTimersMessage : public MessageManager::MessageBase
  137. {
  138. CallTimersMessage() {}
  139. void messageCallback() override
  140. {
  141. if (instance != nullptr)
  142. instance->callTimers();
  143. }
  144. };
  145. //==============================================================================
  146. void addTimer (Timer* t)
  147. {
  148. // Trying to add a timer that's already here - shouldn't get to this point,
  149. // so if you get this assertion, let me know!
  150. jassert (std::find_if (timers.begin(), timers.end(),
  151. [t](TimerCountdown i) { return i.timer == t; }) == timers.end());
  152. auto pos = timers.size();
  153. timers.push_back ({ t, t->timerPeriodMs });
  154. t->positionInQueue = pos;
  155. shuffleTimerForwardInQueue (pos);
  156. notify();
  157. }
  158. void removeTimer (Timer* t)
  159. {
  160. auto pos = t->positionInQueue;
  161. auto lastIndex = timers.size() - 1;
  162. jassert (pos <= lastIndex);
  163. jassert (timers[pos].timer == t);
  164. for (auto i = pos; i < lastIndex; ++i)
  165. {
  166. timers[i] = timers[i + 1];
  167. timers[i].timer->positionInQueue = i;
  168. }
  169. timers.pop_back();
  170. }
  171. void resetTimerCounter (Timer* t) noexcept
  172. {
  173. auto pos = t->positionInQueue;
  174. jassert (pos < timers.size());
  175. jassert (timers[pos].timer == t);
  176. auto lastCountdown = timers[pos].countdownMs;
  177. auto newCountdown = t->timerPeriodMs;
  178. if (newCountdown != lastCountdown)
  179. {
  180. timers[pos].countdownMs = newCountdown;
  181. if (newCountdown > lastCountdown)
  182. shuffleTimerBackInQueue (pos);
  183. else
  184. shuffleTimerForwardInQueue (pos);
  185. notify();
  186. }
  187. }
  188. void shuffleTimerBackInQueue (size_t pos)
  189. {
  190. auto numTimers = timers.size();
  191. if (pos < numTimers - 1)
  192. {
  193. auto t = timers[pos];
  194. for (;;)
  195. {
  196. auto next = pos + 1;
  197. if (next == numTimers || timers[next].countdownMs >= t.countdownMs)
  198. break;
  199. timers[pos] = timers[next];
  200. timers[pos].timer->positionInQueue = pos;
  201. ++pos;
  202. }
  203. timers[pos] = t;
  204. t.timer->positionInQueue = pos;
  205. }
  206. }
  207. void shuffleTimerForwardInQueue (size_t pos)
  208. {
  209. if (pos > 0)
  210. {
  211. auto t = timers[pos];
  212. while (pos > 0)
  213. {
  214. auto& prev = timers[(size_t) pos - 1];
  215. if (prev.countdownMs <= t.countdownMs)
  216. break;
  217. timers[pos] = prev;
  218. timers[pos].timer->positionInQueue = pos;
  219. --pos;
  220. }
  221. timers[pos] = t;
  222. t.timer->positionInQueue = pos;
  223. }
  224. }
  225. int getTimeUntilFirstTimer (int numMillisecsElapsed)
  226. {
  227. const LockType::ScopedLockType sl (lock);
  228. if (timers.empty())
  229. return 1000;
  230. for (auto& t : timers)
  231. t.countdownMs -= numMillisecsElapsed;
  232. return timers.front().countdownMs;
  233. }
  234. void handleAsyncUpdate() override
  235. {
  236. startThread (7);
  237. }
  238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  239. };
  240. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  241. Timer::TimerThread::LockType Timer::TimerThread::lock;
  242. //==============================================================================
  243. Timer::Timer() noexcept {}
  244. Timer::Timer (const Timer&) noexcept {}
  245. Timer::~Timer()
  246. {
  247. stopTimer();
  248. }
  249. void Timer::startTimer (int interval) noexcept
  250. {
  251. // If you're calling this before (or after) the MessageManager is
  252. // running, then you're not going to get any timer callbacks!
  253. JUCE_ASSERT_MESSAGE_MANAGER_EXISTS
  254. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  255. bool wasStopped = (timerPeriodMs == 0);
  256. timerPeriodMs = jmax (1, interval);
  257. if (wasStopped)
  258. TimerThread::add (this);
  259. else
  260. TimerThread::resetCounter (this);
  261. }
  262. void Timer::startTimerHz (int timerFrequencyHz) noexcept
  263. {
  264. if (timerFrequencyHz > 0)
  265. startTimer (1000 / timerFrequencyHz);
  266. else
  267. stopTimer();
  268. }
  269. void Timer::stopTimer() noexcept
  270. {
  271. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  272. if (timerPeriodMs > 0)
  273. {
  274. TimerThread::remove (this);
  275. timerPeriodMs = 0;
  276. }
  277. }
  278. void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
  279. {
  280. if (TimerThread::instance != nullptr)
  281. TimerThread::instance->callTimersSynchronously();
  282. }
  283. struct LambdaInvoker : private Timer
  284. {
  285. LambdaInvoker (int milliseconds, std::function<void()> f) : function (f)
  286. {
  287. startTimer (milliseconds);
  288. }
  289. void timerCallback() override
  290. {
  291. auto f = function;
  292. delete this;
  293. f();
  294. }
  295. std::function<void()> function;
  296. JUCE_DECLARE_NON_COPYABLE (LambdaInvoker)
  297. };
  298. void JUCE_CALLTYPE Timer::callAfterDelay (int milliseconds, std::function<void()> f)
  299. {
  300. new LambdaInvoker (milliseconds, f);
  301. }
  302. } // namespace juce