SDL_timer.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #include "SDL_timer_c.h"
  20. #include "../thread/SDL_systhread.h"
  21. /* #define DEBUG_TIMERS */
  22. #if !defined(__EMSCRIPTEN__) || !SDL_THREADS_DISABLED
  23. typedef struct SDL_Timer
  24. {
  25. int timerID;
  26. SDL_TimerCallback callback;
  27. void *param;
  28. Uint64 interval;
  29. Uint64 scheduled;
  30. SDL_AtomicInt canceled;
  31. struct SDL_Timer *next;
  32. } SDL_Timer;
  33. typedef struct SDL_TimerMap
  34. {
  35. int timerID;
  36. SDL_Timer *timer;
  37. struct SDL_TimerMap *next;
  38. } SDL_TimerMap;
  39. /* The timers are kept in a sorted list */
  40. typedef struct
  41. {
  42. /* Data used by the main thread */
  43. SDL_Thread *thread;
  44. SDL_AtomicInt nextID;
  45. SDL_TimerMap *timermap;
  46. SDL_mutex *timermap_lock;
  47. /* Padding to separate cache lines between threads */
  48. char cache_pad[SDL_CACHELINE_SIZE];
  49. /* Data used to communicate with the timer thread */
  50. SDL_SpinLock lock;
  51. SDL_sem *sem;
  52. SDL_Timer *pending;
  53. SDL_Timer *freelist;
  54. SDL_AtomicInt active;
  55. /* List of timers - this is only touched by the timer thread */
  56. SDL_Timer *timers;
  57. } SDL_TimerData;
  58. static SDL_TimerData SDL_timer_data;
  59. /* The idea here is that any thread might add a timer, but a single
  60. * thread manages the active timer queue, sorted by scheduling time.
  61. *
  62. * Timers are removed by simply setting a canceled flag
  63. */
  64. static void SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer)
  65. {
  66. SDL_Timer *prev, *curr;
  67. prev = NULL;
  68. for (curr = data->timers; curr; prev = curr, curr = curr->next) {
  69. if (curr->scheduled > timer->scheduled) {
  70. break;
  71. }
  72. }
  73. /* Insert the timer here! */
  74. if (prev) {
  75. prev->next = timer;
  76. } else {
  77. data->timers = timer;
  78. }
  79. timer->next = curr;
  80. }
  81. static int SDLCALL SDL_TimerThread(void *_data)
  82. {
  83. SDL_TimerData *data = (SDL_TimerData *)_data;
  84. SDL_Timer *pending;
  85. SDL_Timer *current;
  86. SDL_Timer *freelist_head = NULL;
  87. SDL_Timer *freelist_tail = NULL;
  88. Uint64 tick, now, interval, delay;
  89. /* Threaded timer loop:
  90. * 1. Queue timers added by other threads
  91. * 2. Handle any timers that should dispatch this cycle
  92. * 3. Wait until next dispatch time or new timer arrives
  93. */
  94. for (;;) {
  95. /* Pending and freelist maintenance */
  96. SDL_AtomicLock(&data->lock);
  97. {
  98. /* Get any timers ready to be queued */
  99. pending = data->pending;
  100. data->pending = NULL;
  101. /* Make any unused timer structures available */
  102. if (freelist_head) {
  103. freelist_tail->next = data->freelist;
  104. data->freelist = freelist_head;
  105. }
  106. }
  107. SDL_AtomicUnlock(&data->lock);
  108. /* Sort the pending timers into our list */
  109. while (pending) {
  110. current = pending;
  111. pending = pending->next;
  112. SDL_AddTimerInternal(data, current);
  113. }
  114. freelist_head = NULL;
  115. freelist_tail = NULL;
  116. /* Check to see if we're still running, after maintenance */
  117. if (!SDL_AtomicGet(&data->active)) {
  118. break;
  119. }
  120. /* Initial delay if there are no timers */
  121. delay = SDL_MUTEX_MAXWAIT;
  122. tick = SDL_GetTicksNS();
  123. /* Process all the pending timers for this tick */
  124. while (data->timers) {
  125. current = data->timers;
  126. if (tick < current->scheduled) {
  127. /* Scheduled for the future, wait a bit */
  128. delay = (current->scheduled - tick);
  129. break;
  130. }
  131. /* We're going to do something with this timer */
  132. data->timers = current->next;
  133. if (SDL_AtomicGet(&current->canceled)) {
  134. interval = 0;
  135. } else {
  136. /* FIXME: We could potentially support sub-millisecond timers now */
  137. interval = SDL_MS_TO_NS(current->callback((Uint32)SDL_NS_TO_MS(current->interval), current->param));
  138. }
  139. if (interval > 0) {
  140. /* Reschedule this timer */
  141. current->interval = interval;
  142. current->scheduled = tick + interval;
  143. SDL_AddTimerInternal(data, current);
  144. } else {
  145. if (freelist_head == NULL) {
  146. freelist_head = current;
  147. }
  148. if (freelist_tail) {
  149. freelist_tail->next = current;
  150. }
  151. freelist_tail = current;
  152. SDL_AtomicSet(&current->canceled, 1);
  153. }
  154. }
  155. /* Adjust the delay based on processing time */
  156. now = SDL_GetTicksNS();
  157. interval = (now - tick);
  158. if (interval > delay) {
  159. delay = 0;
  160. } else {
  161. delay -= interval;
  162. }
  163. /* Note that each time a timer is added, this will return
  164. immediately, but we process the timers added all at once.
  165. That's okay, it just means we run through the loop a few
  166. extra times.
  167. */
  168. SDL_SemWaitTimeoutNS(data->sem, delay);
  169. }
  170. return 0;
  171. }
  172. int SDL_InitTimers(void)
  173. {
  174. SDL_TimerData *data = &SDL_timer_data;
  175. if (!SDL_AtomicGet(&data->active)) {
  176. const char *name = "SDLTimer";
  177. data->timermap_lock = SDL_CreateMutex();
  178. if (!data->timermap_lock) {
  179. return -1;
  180. }
  181. data->sem = SDL_CreateSemaphore(0);
  182. if (!data->sem) {
  183. SDL_DestroyMutex(data->timermap_lock);
  184. return -1;
  185. }
  186. SDL_AtomicSet(&data->active, 1);
  187. /* Timer threads use a callback into the app, so we can't set a limited stack size here. */
  188. data->thread = SDL_CreateThreadInternal(SDL_TimerThread, name, 0, data);
  189. if (!data->thread) {
  190. SDL_QuitTimers();
  191. return -1;
  192. }
  193. SDL_AtomicSet(&data->nextID, 1);
  194. }
  195. return 0;
  196. }
  197. void SDL_QuitTimers(void)
  198. {
  199. SDL_TimerData *data = &SDL_timer_data;
  200. SDL_Timer *timer;
  201. SDL_TimerMap *entry;
  202. if (SDL_AtomicCAS(&data->active, 1, 0)) { /* active? Move to inactive. */
  203. /* Shutdown the timer thread */
  204. if (data->thread) {
  205. SDL_SemPost(data->sem);
  206. SDL_WaitThread(data->thread, NULL);
  207. data->thread = NULL;
  208. }
  209. SDL_DestroySemaphore(data->sem);
  210. data->sem = NULL;
  211. /* Clean up the timer entries */
  212. while (data->timers) {
  213. timer = data->timers;
  214. data->timers = timer->next;
  215. SDL_free(timer);
  216. }
  217. while (data->freelist) {
  218. timer = data->freelist;
  219. data->freelist = timer->next;
  220. SDL_free(timer);
  221. }
  222. while (data->timermap) {
  223. entry = data->timermap;
  224. data->timermap = entry->next;
  225. SDL_free(entry);
  226. }
  227. SDL_DestroyMutex(data->timermap_lock);
  228. data->timermap_lock = NULL;
  229. }
  230. }
  231. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  232. {
  233. SDL_TimerData *data = &SDL_timer_data;
  234. SDL_Timer *timer;
  235. SDL_TimerMap *entry;
  236. SDL_AtomicLock(&data->lock);
  237. if (!SDL_AtomicGet(&data->active)) {
  238. if (SDL_InitTimers() < 0) {
  239. SDL_AtomicUnlock(&data->lock);
  240. return 0;
  241. }
  242. }
  243. timer = data->freelist;
  244. if (timer) {
  245. data->freelist = timer->next;
  246. }
  247. SDL_AtomicUnlock(&data->lock);
  248. if (timer) {
  249. SDL_RemoveTimer(timer->timerID);
  250. } else {
  251. timer = (SDL_Timer *)SDL_malloc(sizeof(*timer));
  252. if (timer == NULL) {
  253. SDL_OutOfMemory();
  254. return 0;
  255. }
  256. }
  257. timer->timerID = SDL_AtomicIncRef(&data->nextID);
  258. timer->callback = callback;
  259. timer->param = param;
  260. timer->interval = SDL_MS_TO_NS(interval);
  261. timer->scheduled = SDL_GetTicksNS() + timer->interval;
  262. SDL_AtomicSet(&timer->canceled, 0);
  263. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  264. if (entry == NULL) {
  265. SDL_free(timer);
  266. SDL_OutOfMemory();
  267. return 0;
  268. }
  269. entry->timer = timer;
  270. entry->timerID = timer->timerID;
  271. SDL_LockMutex(data->timermap_lock);
  272. entry->next = data->timermap;
  273. data->timermap = entry;
  274. SDL_UnlockMutex(data->timermap_lock);
  275. /* Add the timer to the pending list for the timer thread */
  276. SDL_AtomicLock(&data->lock);
  277. timer->next = data->pending;
  278. data->pending = timer;
  279. SDL_AtomicUnlock(&data->lock);
  280. /* Wake up the timer thread if necessary */
  281. SDL_SemPost(data->sem);
  282. return entry->timerID;
  283. }
  284. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  285. {
  286. SDL_TimerData *data = &SDL_timer_data;
  287. SDL_TimerMap *prev, *entry;
  288. SDL_bool canceled = SDL_FALSE;
  289. /* Find the timer */
  290. SDL_LockMutex(data->timermap_lock);
  291. prev = NULL;
  292. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  293. if (entry->timerID == id) {
  294. if (prev) {
  295. prev->next = entry->next;
  296. } else {
  297. data->timermap = entry->next;
  298. }
  299. break;
  300. }
  301. }
  302. SDL_UnlockMutex(data->timermap_lock);
  303. if (entry) {
  304. if (!SDL_AtomicGet(&entry->timer->canceled)) {
  305. SDL_AtomicSet(&entry->timer->canceled, 1);
  306. canceled = SDL_TRUE;
  307. }
  308. SDL_free(entry);
  309. }
  310. return canceled;
  311. }
  312. #else
  313. #include <emscripten/emscripten.h>
  314. #include <emscripten/eventloop.h>
  315. typedef struct SDL_TimerMap
  316. {
  317. int timerID;
  318. int timeoutID;
  319. Uint32 interval;
  320. SDL_TimerCallback callback;
  321. void *param;
  322. struct SDL_TimerMap *next;
  323. } SDL_TimerMap;
  324. typedef struct
  325. {
  326. int nextID;
  327. SDL_TimerMap *timermap;
  328. } SDL_TimerData;
  329. static SDL_TimerData SDL_timer_data;
  330. static void SDL_Emscripten_TimerHelper(void *userdata)
  331. {
  332. SDL_TimerMap *entry = (SDL_TimerMap *)userdata;
  333. entry->interval = entry->callback(entry->interval, entry->param);
  334. if (entry->interval > 0) {
  335. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  336. entry->interval,
  337. entry);
  338. }
  339. }
  340. int SDL_InitTimers(void)
  341. {
  342. return 0;
  343. }
  344. void SDL_QuitTimers(void)
  345. {
  346. SDL_TimerData *data = &SDL_timer_data;
  347. SDL_TimerMap *entry;
  348. while (data->timermap) {
  349. entry = data->timermap;
  350. data->timermap = entry->next;
  351. SDL_free(entry);
  352. }
  353. }
  354. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param)
  355. {
  356. SDL_TimerData *data = &SDL_timer_data;
  357. SDL_TimerMap *entry;
  358. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  359. if (entry == NULL) {
  360. SDL_OutOfMemory();
  361. return 0;
  362. }
  363. entry->timerID = ++data->nextID;
  364. entry->callback = callback;
  365. entry->param = param;
  366. entry->interval = interval;
  367. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  368. entry->interval,
  369. entry);
  370. entry->next = data->timermap;
  371. data->timermap = entry;
  372. return entry->timerID;
  373. }
  374. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  375. {
  376. SDL_TimerData *data = &SDL_timer_data;
  377. SDL_TimerMap *prev, *entry;
  378. /* Find the timer */
  379. prev = NULL;
  380. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  381. if (entry->timerID == id) {
  382. if (prev) {
  383. prev->next = entry->next;
  384. } else {
  385. data->timermap = entry->next;
  386. }
  387. break;
  388. }
  389. }
  390. if (entry) {
  391. emscripten_clear_timeout(entry->timeoutID);
  392. SDL_free(entry);
  393. return SDL_TRUE;
  394. }
  395. return SDL_FALSE;
  396. }
  397. #endif /* !defined(__EMSCRIPTEN__) || !SDL_THREADS_DISABLED */
  398. static Uint64 tick_start;
  399. static Uint32 tick_numerator_ns;
  400. static Uint32 tick_denominator_ns;
  401. static Uint32 tick_numerator_ms;
  402. static Uint32 tick_denominator_ms;
  403. #if defined(SDL_TIMER_WINDOWS) && \
  404. !defined(__WINRT__) && !defined(__XBOXONE__) && !defined(__XBOXSERIES__)
  405. #include <mmsystem.h>
  406. #define HAVE_TIME_BEGIN_PERIOD
  407. #endif
  408. static void SDL_SetSystemTimerResolutionMS(int period)
  409. {
  410. #ifdef HAVE_TIME_BEGIN_PERIOD
  411. static int timer_period = 0;
  412. if (period != timer_period) {
  413. if (timer_period) {
  414. timeEndPeriod((UINT)timer_period);
  415. }
  416. timer_period = period;
  417. if (timer_period) {
  418. timeBeginPeriod((UINT)timer_period);
  419. }
  420. }
  421. #endif /* HAVE_TIME_BEGIN_PERIOD */
  422. }
  423. static void SDLCALL SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  424. {
  425. int period;
  426. /* Unless the hint says otherwise, let's have good sleep precision */
  427. if (hint && *hint) {
  428. period = SDL_atoi(hint);
  429. } else {
  430. period = 1;
  431. }
  432. if (period || oldValue != hint) {
  433. SDL_SetSystemTimerResolutionMS(period);
  434. }
  435. }
  436. static Uint32 CalculateGCD(Uint32 a, Uint32 b)
  437. {
  438. if (b == 0) {
  439. return a;
  440. }
  441. return CalculateGCD(b, (a % b));
  442. }
  443. void SDL_InitTicks(void)
  444. {
  445. Uint64 tick_freq;
  446. Uint32 gcd;
  447. if (tick_start) {
  448. return;
  449. }
  450. /* If we didn't set a precision, set it high. This affects lots of things
  451. on Windows besides the SDL timers, like audio callbacks, etc. */
  452. SDL_AddHintCallback(SDL_HINT_TIMER_RESOLUTION,
  453. SDL_TimerResolutionChanged, NULL);
  454. tick_freq = SDL_GetPerformanceFrequency();
  455. SDL_assert(tick_freq > 0 && tick_freq <= SDL_MAX_UINT32);
  456. gcd = CalculateGCD(SDL_NS_PER_SECOND, (Uint32)tick_freq);
  457. tick_numerator_ns = (SDL_NS_PER_SECOND / gcd);
  458. tick_denominator_ns = (Uint32)(tick_freq / gcd);
  459. gcd = CalculateGCD(SDL_MS_PER_SECOND, (Uint32)tick_freq);
  460. tick_numerator_ms = (SDL_MS_PER_SECOND / gcd);
  461. tick_denominator_ms = (Uint32)(tick_freq / gcd);
  462. tick_start = SDL_GetPerformanceCounter();
  463. if (!tick_start) {
  464. --tick_start;
  465. }
  466. }
  467. void SDL_QuitTicks(void)
  468. {
  469. SDL_DelHintCallback(SDL_HINT_TIMER_RESOLUTION,
  470. SDL_TimerResolutionChanged, NULL);
  471. SDL_SetSystemTimerResolutionMS(0); /* always release our timer resolution request. */
  472. tick_start = 0;
  473. }
  474. Uint64
  475. SDL_GetTicksNS(void)
  476. {
  477. Uint64 starting_value, value;
  478. if (!tick_start) {
  479. SDL_InitTicks();
  480. }
  481. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  482. value = (starting_value * tick_numerator_ns);
  483. SDL_assert(value >= starting_value);
  484. value /= tick_denominator_ns;
  485. return value;
  486. }
  487. Uint64 SDL_GetTicks(void)
  488. {
  489. Uint64 starting_value, value;
  490. if (!tick_start) {
  491. SDL_InitTicks();
  492. }
  493. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  494. value = (starting_value * tick_numerator_ms);
  495. SDL_assert(value >= starting_value);
  496. value /= tick_denominator_ms;
  497. return value;
  498. }
  499. void SDL_Delay(Uint32 ms)
  500. {
  501. SDL_DelayNS(SDL_MS_TO_NS(ms));
  502. }