Wrap tick API

This avoids to use the SDL timer API directly, and will allow to handle
generic ticks (possibly negative).
This commit is contained in:
Romain Vimont
2021-07-04 16:50:19 +02:00
parent 5524f378c8
commit ec871dd3f5
8 changed files with 58 additions and 16 deletions

View File

@@ -123,7 +123,12 @@ sc_cond_wait(sc_cond *cond, sc_mutex *mutex) {
}
bool
sc_cond_timedwait(sc_cond *cond, sc_mutex *mutex, uint32_t ms) {
sc_cond_timedwait(sc_cond *cond, sc_mutex *mutex, sc_tick delay) {
if (delay < 0) {
return false; // timeout
}
uint32_t ms = SC_TICK_TO_MS(delay);
int r = SDL_CondWaitTimeout(cond->cond, mutex->mutex, ms);
#ifndef NDEBUG
if (r < 0) {

View File

@@ -5,7 +5,8 @@
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include "tick.h"
/* Forward declarations */
typedef struct SDL_Thread SDL_Thread;
@@ -72,7 +73,7 @@ sc_cond_wait(sc_cond *cond, sc_mutex *mutex);
// return true on signaled, false on timeout
bool
sc_cond_timedwait(sc_cond *cond, sc_mutex *mutex, uint32_t ms);
sc_cond_timedwait(sc_cond *cond, sc_mutex *mutex, sc_tick ms);
void
sc_cond_signal(sc_cond *cond);

16
app/src/util/tick.c Normal file
View File

@@ -0,0 +1,16 @@
#include "tick.h"
#include <SDL2/SDL_timer.h>
sc_tick
sc_tick_now(void) {
// SDL_GetTicks() resolution is in milliseconds, but sc_tick are expressed
// in microseconds to store PTS without precision loss.
//
// As an alternative, SDL_GetPerformanceCounter() and
// SDL_GetPerformanceFrequency() could be used, but:
// - the conversions (avoiding overflow) are expansive, since the
// frequency is not known at compile time;
// - in practice, we don't need more precision for now.
return (sc_tick) SDL_GetTicks() * 1000;
}

20
app/src/util/tick.h Normal file
View File

@@ -0,0 +1,20 @@
#ifndef SC_TICK_H
#define SC_TICK_H
#include <stdint.h>
typedef int64_t sc_tick;
#define SC_TICK_FREQ 1000000 // microsecond
// To be adapted if SC_TICK_FREQ changes
#define SC_TICK_TO_US(tick) (tick)
#define SC_TICK_TO_MS(tick) ((tick) / 1000)
#define SC_TICK_TO_SEC(tick) ((tick) / 1000000)
#define SC_TICK_FROM_US(us) (us)
#define SC_TICK_FROM_MS(ms) ((ms) * 1000)
#define SC_TICK_FROM_SEC(sec) ((sec) * 1000000)
sc_tick
sc_tick_now(void);
#endif