SDL_timer.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
  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(SDL_PLATFORM_EMSCRIPTEN) || !defined(SDL_THREADS_DISABLED)
  23. typedef struct SDL_Timer
  24. {
  25. SDL_TimerID timerID;
  26. SDL_TimerCallback callback_ms;
  27. SDL_NSTimerCallback callback_ns;
  28. void *userdata;
  29. Uint64 interval;
  30. Uint64 scheduled;
  31. SDL_AtomicInt canceled;
  32. struct SDL_Timer *next;
  33. } SDL_Timer;
  34. typedef struct SDL_TimerMap
  35. {
  36. SDL_TimerID timerID;
  37. SDL_Timer *timer;
  38. struct SDL_TimerMap *next;
  39. } SDL_TimerMap;
  40. // The timers are kept in a sorted list
  41. typedef struct
  42. {
  43. // Data used by the main thread
  44. SDL_InitState init;
  45. SDL_Thread *thread;
  46. SDL_TimerMap *timermap;
  47. SDL_Mutex *timermap_lock;
  48. // Padding to separate cache lines between threads
  49. char cache_pad[SDL_CACHELINE_SIZE];
  50. // Data used to communicate with the timer thread
  51. SDL_SpinLock lock;
  52. SDL_Semaphore *sem;
  53. SDL_Timer *pending;
  54. SDL_Timer *freelist;
  55. SDL_AtomicInt active;
  56. // List of timers - this is only touched by the timer thread
  57. SDL_Timer *timers;
  58. } SDL_TimerData;
  59. static SDL_TimerData SDL_timer_data;
  60. /* The idea here is that any thread might add a timer, but a single
  61. * thread manages the active timer queue, sorted by scheduling time.
  62. *
  63. * Timers are removed by simply setting a canceled flag
  64. */
  65. static void SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer)
  66. {
  67. SDL_Timer *prev, *curr;
  68. prev = NULL;
  69. for (curr = data->timers; curr; prev = curr, curr = curr->next) {
  70. if (curr->scheduled > timer->scheduled) {
  71. break;
  72. }
  73. }
  74. // Insert the timer here!
  75. if (prev) {
  76. prev->next = timer;
  77. } else {
  78. data->timers = timer;
  79. }
  80. timer->next = curr;
  81. }
  82. static int SDLCALL SDL_TimerThread(void *_data)
  83. {
  84. SDL_TimerData *data = (SDL_TimerData *)_data;
  85. SDL_Timer *pending;
  86. SDL_Timer *current;
  87. SDL_Timer *freelist_head = NULL;
  88. SDL_Timer *freelist_tail = NULL;
  89. Uint64 tick, now, interval, delay;
  90. /* Threaded timer loop:
  91. * 1. Queue timers added by other threads
  92. * 2. Handle any timers that should dispatch this cycle
  93. * 3. Wait until next dispatch time or new timer arrives
  94. */
  95. for (;;) {
  96. // Pending and freelist maintenance
  97. SDL_LockSpinlock(&data->lock);
  98. {
  99. // Get any timers ready to be queued
  100. pending = data->pending;
  101. data->pending = NULL;
  102. // Make any unused timer structures available
  103. if (freelist_head) {
  104. freelist_tail->next = data->freelist;
  105. data->freelist = freelist_head;
  106. }
  107. }
  108. SDL_UnlockSpinlock(&data->lock);
  109. // Sort the pending timers into our list
  110. while (pending) {
  111. current = pending;
  112. pending = pending->next;
  113. SDL_AddTimerInternal(data, current);
  114. }
  115. freelist_head = NULL;
  116. freelist_tail = NULL;
  117. // Check to see if we're still running, after maintenance
  118. if (!SDL_GetAtomicInt(&data->active)) {
  119. break;
  120. }
  121. // Initial delay if there are no timers
  122. delay = (Uint64)-1;
  123. tick = SDL_GetTicksNS();
  124. // Process all the pending timers for this tick
  125. while (data->timers) {
  126. current = data->timers;
  127. if (tick < current->scheduled) {
  128. // Scheduled for the future, wait a bit
  129. delay = (current->scheduled - tick);
  130. break;
  131. }
  132. // We're going to do something with this timer
  133. data->timers = current->next;
  134. if (SDL_GetAtomicInt(&current->canceled)) {
  135. interval = 0;
  136. } else {
  137. if (current->callback_ms) {
  138. interval = SDL_MS_TO_NS(current->callback_ms(current->userdata, current->timerID, (Uint32)SDL_NS_TO_MS(current->interval)));
  139. } else {
  140. interval = current->callback_ns(current->userdata, current->timerID, current->interval);
  141. }
  142. }
  143. if (interval > 0) {
  144. // Reschedule this timer
  145. current->interval = interval;
  146. current->scheduled = tick + interval;
  147. SDL_AddTimerInternal(data, current);
  148. } else {
  149. if (!freelist_head) {
  150. freelist_head = current;
  151. }
  152. if (freelist_tail) {
  153. freelist_tail->next = current;
  154. }
  155. freelist_tail = current;
  156. SDL_SetAtomicInt(&current->canceled, 1);
  157. }
  158. }
  159. // Adjust the delay based on processing time
  160. now = SDL_GetTicksNS();
  161. interval = (now - tick);
  162. if (interval > delay) {
  163. delay = 0;
  164. } else {
  165. delay -= interval;
  166. }
  167. /* Note that each time a timer is added, this will return
  168. immediately, but we process the timers added all at once.
  169. That's okay, it just means we run through the loop a few
  170. extra times.
  171. */
  172. SDL_WaitSemaphoreTimeoutNS(data->sem, delay);
  173. }
  174. return 0;
  175. }
  176. bool SDL_InitTimers(void)
  177. {
  178. SDL_TimerData *data = &SDL_timer_data;
  179. if (!SDL_ShouldInit(&data->init)) {
  180. return true;
  181. }
  182. data->timermap_lock = SDL_CreateMutex();
  183. if (!data->timermap_lock) {
  184. goto error;
  185. }
  186. data->sem = SDL_CreateSemaphore(0);
  187. if (!data->sem) {
  188. goto error;
  189. }
  190. SDL_SetAtomicInt(&data->active, true);
  191. // Timer threads use a callback into the app, so we can't set a limited stack size here.
  192. data->thread = SDL_CreateThread(SDL_TimerThread, "SDLTimer", data);
  193. if (!data->thread) {
  194. goto error;
  195. }
  196. SDL_SetInitialized(&data->init, true);
  197. return true;
  198. error:
  199. SDL_SetInitialized(&data->init, true);
  200. SDL_QuitTimers();
  201. return false;
  202. }
  203. void SDL_QuitTimers(void)
  204. {
  205. SDL_TimerData *data = &SDL_timer_data;
  206. SDL_Timer *timer;
  207. SDL_TimerMap *entry;
  208. if (!SDL_ShouldQuit(&data->init)) {
  209. return;
  210. }
  211. SDL_SetAtomicInt(&data->active, false);
  212. // Shutdown the timer thread
  213. if (data->thread) {
  214. SDL_SignalSemaphore(data->sem);
  215. SDL_WaitThread(data->thread, NULL);
  216. data->thread = NULL;
  217. }
  218. if (data->sem) {
  219. SDL_DestroySemaphore(data->sem);
  220. data->sem = NULL;
  221. }
  222. // Clean up the timer entries
  223. while (data->timers) {
  224. timer = data->timers;
  225. data->timers = timer->next;
  226. SDL_free(timer);
  227. }
  228. while (data->freelist) {
  229. timer = data->freelist;
  230. data->freelist = timer->next;
  231. SDL_free(timer);
  232. }
  233. while (data->timermap) {
  234. entry = data->timermap;
  235. data->timermap = entry->next;
  236. SDL_free(entry);
  237. }
  238. if (data->timermap_lock) {
  239. SDL_DestroyMutex(data->timermap_lock);
  240. data->timermap_lock = NULL;
  241. }
  242. SDL_SetInitialized(&data->init, false);
  243. }
  244. static bool SDL_CheckInitTimers(void)
  245. {
  246. return SDL_InitTimers();
  247. }
  248. static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata)
  249. {
  250. SDL_TimerData *data = &SDL_timer_data;
  251. SDL_Timer *timer;
  252. SDL_TimerMap *entry;
  253. if (!callback_ms && !callback_ns) {
  254. SDL_InvalidParamError("callback");
  255. return 0;
  256. }
  257. if (!SDL_CheckInitTimers()) {
  258. return 0;
  259. }
  260. SDL_LockSpinlock(&data->lock);
  261. timer = data->freelist;
  262. if (timer) {
  263. data->freelist = timer->next;
  264. }
  265. SDL_UnlockSpinlock(&data->lock);
  266. if (timer) {
  267. SDL_RemoveTimer(timer->timerID);
  268. } else {
  269. timer = (SDL_Timer *)SDL_malloc(sizeof(*timer));
  270. if (!timer) {
  271. return 0;
  272. }
  273. }
  274. timer->timerID = SDL_GetNextObjectID();
  275. timer->callback_ms = callback_ms;
  276. timer->callback_ns = callback_ns;
  277. timer->userdata = userdata;
  278. timer->interval = interval;
  279. timer->scheduled = SDL_GetTicksNS() + timer->interval;
  280. SDL_SetAtomicInt(&timer->canceled, 0);
  281. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  282. if (!entry) {
  283. SDL_free(timer);
  284. return 0;
  285. }
  286. entry->timer = timer;
  287. entry->timerID = timer->timerID;
  288. SDL_LockMutex(data->timermap_lock);
  289. entry->next = data->timermap;
  290. data->timermap = entry;
  291. SDL_UnlockMutex(data->timermap_lock);
  292. // Add the timer to the pending list for the timer thread
  293. SDL_LockSpinlock(&data->lock);
  294. timer->next = data->pending;
  295. data->pending = timer;
  296. SDL_UnlockSpinlock(&data->lock);
  297. // Wake up the timer thread if necessary
  298. SDL_SignalSemaphore(data->sem);
  299. return entry->timerID;
  300. }
  301. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata)
  302. {
  303. return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata);
  304. }
  305. SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata)
  306. {
  307. return SDL_CreateTimer(interval, NULL, callback, userdata);
  308. }
  309. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  310. {
  311. SDL_TimerData *data = &SDL_timer_data;
  312. SDL_TimerMap *prev, *entry;
  313. bool canceled = false;
  314. if (!id) {
  315. return SDL_InvalidParamError("id");
  316. }
  317. // Find the timer
  318. SDL_LockMutex(data->timermap_lock);
  319. prev = NULL;
  320. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  321. if (entry->timerID == id) {
  322. if (prev) {
  323. prev->next = entry->next;
  324. } else {
  325. data->timermap = entry->next;
  326. }
  327. break;
  328. }
  329. }
  330. SDL_UnlockMutex(data->timermap_lock);
  331. if (entry) {
  332. if (!SDL_GetAtomicInt(&entry->timer->canceled)) {
  333. SDL_SetAtomicInt(&entry->timer->canceled, 1);
  334. canceled = true;
  335. }
  336. SDL_free(entry);
  337. }
  338. if (canceled) {
  339. return true;
  340. } else {
  341. return SDL_SetError("Timer not found");
  342. }
  343. }
  344. #else
  345. #include <emscripten/emscripten.h>
  346. #include <emscripten/eventloop.h>
  347. typedef struct SDL_TimerMap
  348. {
  349. SDL_TimerID timerID;
  350. int timeoutID;
  351. Uint64 interval;
  352. SDL_TimerCallback callback_ms;
  353. SDL_NSTimerCallback callback_ns;
  354. void *userdata;
  355. struct SDL_TimerMap *next;
  356. } SDL_TimerMap;
  357. typedef struct
  358. {
  359. SDL_TimerMap *timermap;
  360. } SDL_TimerData;
  361. static SDL_TimerData SDL_timer_data;
  362. static void SDL_Emscripten_TimerHelper(void *userdata)
  363. {
  364. SDL_TimerMap *entry = (SDL_TimerMap *)userdata;
  365. if (entry->callback_ms) {
  366. entry->interval = SDL_MS_TO_NS(entry->callback_ms(entry->userdata, entry->timerID, (Uint32)SDL_NS_TO_MS(entry->interval)));
  367. } else {
  368. entry->interval = entry->callback_ns(entry->userdata, entry->timerID, entry->interval);
  369. }
  370. if (entry->interval > 0) {
  371. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  372. SDL_NS_TO_MS(entry->interval),
  373. entry);
  374. }
  375. }
  376. bool SDL_InitTimers(void)
  377. {
  378. return true;
  379. }
  380. void SDL_QuitTimers(void)
  381. {
  382. SDL_TimerData *data = &SDL_timer_data;
  383. SDL_TimerMap *entry;
  384. while (data->timermap) {
  385. entry = data->timermap;
  386. data->timermap = entry->next;
  387. SDL_free(entry);
  388. }
  389. }
  390. static SDL_TimerID SDL_CreateTimer(Uint64 interval, SDL_TimerCallback callback_ms, SDL_NSTimerCallback callback_ns, void *userdata)
  391. {
  392. SDL_TimerData *data = &SDL_timer_data;
  393. SDL_TimerMap *entry;
  394. if (!callback_ms && !callback_ns) {
  395. SDL_InvalidParamError("callback");
  396. return 0;
  397. }
  398. entry = (SDL_TimerMap *)SDL_malloc(sizeof(*entry));
  399. if (!entry) {
  400. return 0;
  401. }
  402. entry->timerID = SDL_GetNextObjectID();
  403. entry->callback_ms = callback_ms;
  404. entry->callback_ns = callback_ns;
  405. entry->userdata = userdata;
  406. entry->interval = interval;
  407. entry->timeoutID = emscripten_set_timeout(&SDL_Emscripten_TimerHelper,
  408. SDL_NS_TO_MS(entry->interval),
  409. entry);
  410. entry->next = data->timermap;
  411. data->timermap = entry;
  412. return entry->timerID;
  413. }
  414. SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *userdata)
  415. {
  416. return SDL_CreateTimer(SDL_MS_TO_NS(interval), callback, NULL, userdata);
  417. }
  418. SDL_TimerID SDL_AddTimerNS(Uint64 interval, SDL_NSTimerCallback callback, void *userdata)
  419. {
  420. return SDL_CreateTimer(interval, NULL, callback, userdata);
  421. }
  422. SDL_bool SDL_RemoveTimer(SDL_TimerID id)
  423. {
  424. SDL_TimerData *data = &SDL_timer_data;
  425. SDL_TimerMap *prev, *entry;
  426. if (!id) {
  427. return SDL_InvalidParamError("id");
  428. }
  429. // Find the timer
  430. prev = NULL;
  431. for (entry = data->timermap; entry; prev = entry, entry = entry->next) {
  432. if (entry->timerID == id) {
  433. if (prev) {
  434. prev->next = entry->next;
  435. } else {
  436. data->timermap = entry->next;
  437. }
  438. break;
  439. }
  440. }
  441. if (entry) {
  442. emscripten_clear_timeout(entry->timeoutID);
  443. SDL_free(entry);
  444. return true;
  445. } else {
  446. return SDL_SetError("Timer not found");
  447. }
  448. }
  449. #endif // !defined(SDL_PLATFORM_EMSCRIPTEN) || !SDL_THREADS_DISABLED
  450. static Uint64 tick_start;
  451. static Uint32 tick_numerator_ns;
  452. static Uint32 tick_denominator_ns;
  453. static Uint32 tick_numerator_ms;
  454. static Uint32 tick_denominator_ms;
  455. #if defined(SDL_TIMER_WINDOWS) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  456. #include <mmsystem.h>
  457. #define HAVE_TIME_BEGIN_PERIOD
  458. #endif
  459. static void SDL_SetSystemTimerResolutionMS(int period)
  460. {
  461. #ifdef HAVE_TIME_BEGIN_PERIOD
  462. static int timer_period = 0;
  463. if (period != timer_period) {
  464. if (timer_period) {
  465. timeEndPeriod((UINT)timer_period);
  466. }
  467. timer_period = period;
  468. if (timer_period) {
  469. timeBeginPeriod((UINT)timer_period);
  470. }
  471. }
  472. #endif // HAVE_TIME_BEGIN_PERIOD
  473. }
  474. static void SDLCALL SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  475. {
  476. int period;
  477. // Unless the hint says otherwise, let's have good sleep precision
  478. if (hint && *hint) {
  479. period = SDL_atoi(hint);
  480. } else {
  481. period = 1;
  482. }
  483. if (period || oldValue != hint) {
  484. SDL_SetSystemTimerResolutionMS(period);
  485. }
  486. }
  487. void SDL_InitTicks(void)
  488. {
  489. Uint64 tick_freq;
  490. Uint32 gcd;
  491. if (tick_start) {
  492. return;
  493. }
  494. /* If we didn't set a precision, set it high. This affects lots of things
  495. on Windows besides the SDL timers, like audio callbacks, etc. */
  496. SDL_AddHintCallback(SDL_HINT_TIMER_RESOLUTION,
  497. SDL_TimerResolutionChanged, NULL);
  498. tick_freq = SDL_GetPerformanceFrequency();
  499. SDL_assert(tick_freq > 0 && tick_freq <= (Uint64)SDL_MAX_UINT32);
  500. gcd = SDL_CalculateGCD(SDL_NS_PER_SECOND, (Uint32)tick_freq);
  501. tick_numerator_ns = (SDL_NS_PER_SECOND / gcd);
  502. tick_denominator_ns = (Uint32)(tick_freq / gcd);
  503. gcd = SDL_CalculateGCD(SDL_MS_PER_SECOND, (Uint32)tick_freq);
  504. tick_numerator_ms = (SDL_MS_PER_SECOND / gcd);
  505. tick_denominator_ms = (Uint32)(tick_freq / gcd);
  506. tick_start = SDL_GetPerformanceCounter();
  507. if (!tick_start) {
  508. --tick_start;
  509. }
  510. }
  511. void SDL_QuitTicks(void)
  512. {
  513. SDL_RemoveHintCallback(SDL_HINT_TIMER_RESOLUTION,
  514. SDL_TimerResolutionChanged, NULL);
  515. SDL_SetSystemTimerResolutionMS(0); // always release our timer resolution request.
  516. tick_start = 0;
  517. }
  518. Uint64 SDL_GetTicksNS(void)
  519. {
  520. Uint64 starting_value, value;
  521. if (!tick_start) {
  522. SDL_InitTicks();
  523. }
  524. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  525. value = (starting_value * tick_numerator_ns);
  526. SDL_assert(value >= starting_value);
  527. value /= tick_denominator_ns;
  528. return value;
  529. }
  530. Uint64 SDL_GetTicks(void)
  531. {
  532. Uint64 starting_value, value;
  533. if (!tick_start) {
  534. SDL_InitTicks();
  535. }
  536. starting_value = (SDL_GetPerformanceCounter() - tick_start);
  537. value = (starting_value * tick_numerator_ms);
  538. SDL_assert(value >= starting_value);
  539. value /= tick_denominator_ms;
  540. return value;
  541. }
  542. void SDL_Delay(Uint32 ms)
  543. {
  544. SDL_SYS_DelayNS(SDL_MS_TO_NS(ms));
  545. }
  546. void SDL_DelayNS(Uint64 ns)
  547. {
  548. Uint64 current_value = SDL_GetTicksNS();
  549. Uint64 target_value = current_value + ns;
  550. // Sleep for a short number of cycles
  551. // We'll use 1 ms as a scheduling timeslice, it's a good value for modern operating systems
  552. const int SCHEDULING_TIMESLICE_NS = 1 * SDL_NS_PER_MS;
  553. while (current_value < target_value) {
  554. Uint64 remaining_ns = (target_value - current_value);
  555. if (remaining_ns > (SCHEDULING_TIMESLICE_NS + SDL_NS_PER_US)) {
  556. // Sleep for a short time, less than the scheduling timeslice
  557. SDL_SYS_DelayNS(SCHEDULING_TIMESLICE_NS - SDL_NS_PER_US);
  558. } else {
  559. // Spin for any remaining time
  560. SDL_CPUPauseInstruction();
  561. }
  562. current_value = SDL_GetTicksNS();
  563. }
  564. }