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.

399 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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. cancelPendingUpdate();
  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. auto lastTime = Time::getMillisecondCounter();
  43. ReferenceCountedObjectPtr<CallTimersMessage> messageToSend (new CallTimersMessage());
  44. while (! threadShouldExit())
  45. {
  46. auto now = Time::getMillisecondCounter();
  47. auto elapsed = (int) (now >= lastTime ? (now - lastTime)
  48. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  49. lastTime = now;
  50. auto 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. auto timeout = Time::getMillisecondCounter() + 100;
  78. const LockType::ScopedLockType sl (lock);
  79. while (! timers.empty())
  80. {
  81. auto& first = timers.front();
  82. if (first.countdownMs > 0)
  83. break;
  84. auto* timer = first.timer;
  85. first.countdownMs = timer->timerPeriodMs;
  86. shuffleTimerBackInQueue (0);
  87. notify();
  88. const LockType::ScopedUnlockType ul (lock);
  89. JUCE_TRY
  90. {
  91. timer->timerCallback();
  92. }
  93. JUCE_CATCH_EXCEPTION
  94. // avoid getting stuck in a loop if a timer callback repeatedly takes too long
  95. if (Time::getMillisecondCounter() > timeout)
  96. break;
  97. }
  98. callbackArrived.signal();
  99. }
  100. void callTimersSynchronously()
  101. {
  102. if (! isThreadRunning())
  103. {
  104. // (This is relied on by some plugins in cases where the MM has
  105. // had to restart and the async callback never started)
  106. cancelPendingUpdate();
  107. triggerAsyncUpdate();
  108. }
  109. callTimers();
  110. }
  111. static void add (Timer* tim) noexcept
  112. {
  113. if (instance == nullptr)
  114. instance = new TimerThread();
  115. instance->addTimer (tim);
  116. }
  117. static void remove (Timer* tim) noexcept
  118. {
  119. if (instance != nullptr)
  120. instance->removeTimer (tim);
  121. }
  122. static void resetCounter (Timer* tim) noexcept
  123. {
  124. if (instance != nullptr)
  125. instance->resetTimerCounter (tim);
  126. }
  127. static TimerThread* instance;
  128. static LockType lock;
  129. private:
  130. struct TimerCountdown
  131. {
  132. Timer* timer;
  133. int countdownMs;
  134. };
  135. std::vector<TimerCountdown> timers;
  136. WaitableEvent callbackArrived;
  137. struct CallTimersMessage : public MessageManager::MessageBase
  138. {
  139. CallTimersMessage() {}
  140. void messageCallback() override
  141. {
  142. if (instance != nullptr)
  143. instance->callTimers();
  144. }
  145. };
  146. //==============================================================================
  147. void addTimer (Timer* t)
  148. {
  149. // Trying to add a timer that's already here - shouldn't get to this point,
  150. // so if you get this assertion, let me know!
  151. jassert (std::none_of (timers.begin(), timers.end(),
  152. [t] (TimerCountdown i) { return i.timer == t; }));
  153. auto pos = timers.size();
  154. timers.push_back ({ t, t->timerPeriodMs });
  155. t->positionInQueue = pos;
  156. shuffleTimerForwardInQueue (pos);
  157. notify();
  158. }
  159. void removeTimer (Timer* t)
  160. {
  161. auto pos = t->positionInQueue;
  162. auto lastIndex = timers.size() - 1;
  163. jassert (pos <= lastIndex);
  164. jassert (timers[pos].timer == t);
  165. for (auto i = pos; i < lastIndex; ++i)
  166. {
  167. timers[i] = timers[i + 1];
  168. timers[i].timer->positionInQueue = i;
  169. }
  170. timers.pop_back();
  171. }
  172. void resetTimerCounter (Timer* t) noexcept
  173. {
  174. auto pos = t->positionInQueue;
  175. jassert (pos < timers.size());
  176. jassert (timers[pos].timer == t);
  177. auto lastCountdown = timers[pos].countdownMs;
  178. auto newCountdown = t->timerPeriodMs;
  179. if (newCountdown != lastCountdown)
  180. {
  181. timers[pos].countdownMs = newCountdown;
  182. if (newCountdown > lastCountdown)
  183. shuffleTimerBackInQueue (pos);
  184. else
  185. shuffleTimerForwardInQueue (pos);
  186. notify();
  187. }
  188. }
  189. void shuffleTimerBackInQueue (size_t pos)
  190. {
  191. auto numTimers = timers.size();
  192. if (pos < numTimers - 1)
  193. {
  194. auto t = timers[pos];
  195. for (;;)
  196. {
  197. auto next = pos + 1;
  198. if (next == numTimers || timers[next].countdownMs >= t.countdownMs)
  199. break;
  200. timers[pos] = timers[next];
  201. timers[pos].timer->positionInQueue = pos;
  202. ++pos;
  203. }
  204. timers[pos] = t;
  205. t.timer->positionInQueue = pos;
  206. }
  207. }
  208. void shuffleTimerForwardInQueue (size_t pos)
  209. {
  210. if (pos > 0)
  211. {
  212. auto t = timers[pos];
  213. while (pos > 0)
  214. {
  215. auto& prev = timers[(size_t) pos - 1];
  216. if (prev.countdownMs <= t.countdownMs)
  217. break;
  218. timers[pos] = prev;
  219. timers[pos].timer->positionInQueue = pos;
  220. --pos;
  221. }
  222. timers[pos] = t;
  223. t.timer->positionInQueue = pos;
  224. }
  225. }
  226. int getTimeUntilFirstTimer (int numMillisecsElapsed)
  227. {
  228. const LockType::ScopedLockType sl (lock);
  229. if (timers.empty())
  230. return 1000;
  231. for (auto& t : timers)
  232. t.countdownMs -= numMillisecsElapsed;
  233. return timers.front().countdownMs;
  234. }
  235. void handleAsyncUpdate() override
  236. {
  237. startThread (7);
  238. }
  239. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  240. };
  241. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  242. Timer::TimerThread::LockType Timer::TimerThread::lock;
  243. //==============================================================================
  244. Timer::Timer() noexcept {}
  245. Timer::Timer (const Timer&) noexcept {}
  246. Timer::~Timer()
  247. {
  248. // If you're destroying a timer on a background thread, make sure the timer has
  249. // been stopped before execution reaches this point. A simple way to achieve this
  250. // is to add a call to `stopTimer()` to the destructor of your class which inherits
  251. // from Timer.
  252. jassert (! isTimerRunning()
  253. || MessageManager::getInstanceWithoutCreating() == nullptr
  254. || MessageManager::getInstanceWithoutCreating()->currentThreadHasLockedMessageManager());
  255. stopTimer();
  256. }
  257. void Timer::startTimer (int interval) noexcept
  258. {
  259. // If you're calling this before (or after) the MessageManager is
  260. // running, then you're not going to get any timer callbacks!
  261. JUCE_ASSERT_MESSAGE_MANAGER_EXISTS
  262. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  263. bool wasStopped = (timerPeriodMs == 0);
  264. timerPeriodMs = jmax (1, interval);
  265. if (wasStopped)
  266. TimerThread::add (this);
  267. else
  268. TimerThread::resetCounter (this);
  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. }
  291. struct LambdaInvoker : private Timer
  292. {
  293. LambdaInvoker (int milliseconds, std::function<void()> f) : function (f)
  294. {
  295. startTimer (milliseconds);
  296. }
  297. void timerCallback() override
  298. {
  299. auto f = function;
  300. delete this;
  301. f();
  302. }
  303. std::function<void()> function;
  304. JUCE_DECLARE_NON_COPYABLE (LambdaInvoker)
  305. };
  306. void JUCE_CALLTYPE Timer::callAfterDelay (int milliseconds, std::function<void()> f)
  307. {
  308. new LambdaInvoker (milliseconds, f);
  309. }
  310. } // namespace juce