40 double da = *(
const double*)a;
41 double db = *(
const double*)b;
42 if (da < db)
return -1;
43 if (da > db)
return 1;
48static double median_of(
const double* samples,
int count) {
49 if (count <= 0)
return 0.0;
53 memcpy(tmp, samples, (
size_t)n *
sizeof(
double));
54 qsort(tmp, (
size_t)n,
sizeof(
double),
cmp_double);
59 return (tmp[n / 2 - 1] + tmp[n / 2]) / 2.0;
88 double rtt = local_now - client_send_time;
90 n_log(
LOG_ERR,
"n_clock_sync: negative RTT (%.4f), ignoring sample", rtt);
94 double one_way = rtt / 2.0;
95 double offset = server_time + one_way - local_now;
109 n_log(
LOG_DEBUG,
"n_clock_sync: sample %d, offset=%.4f rtt=%.4f (median offset=%.4f rtt=%.4f)",
int sample_index
current write position in circular buffer
double last_sync_time
local time of last sync request sent
double estimated_offset
add to local time to get estimated server time
double estimated_rtt
current estimated round-trip time
int sample_count
number of samples collected so far
double rtt_samples[11]
circular buffer of RTT values
double offset_samples[11]
circular buffer of offset estimates
#define N_CLOCK_SYNC_SAMPLE_COUNT
number of samples for the median filter
N_CLOCK_SYNC * n_clock_sync_new(void)
allocate and initialize a new clock sync estimator
#define N_CLOCK_SYNC_INTERVAL
default interval between sync requests in seconds
static int cmp_double(const void *a, const void *b)
comparison function for qsort on doubles
int n_clock_sync_should_send(const N_CLOCK_SYNC *cs, double local_now)
check if it's time to send a new sync request (returns TRUE/FALSE)
double n_clock_sync_server_time(const N_CLOCK_SYNC *cs, double local_now)
get estimated server time given a local time value
void n_clock_sync_delete(N_CLOCK_SYNC **cs)
free a clock sync estimator
void n_clock_sync_mark_sent(N_CLOCK_SYNC *cs, double local_now)
mark that a sync request was just sent
int n_clock_sync_process_response(N_CLOCK_SYNC *cs, double client_send_time, double server_time, double local_now)
record a sync response: client_send_time is the local time the request was sent, server_time is the s...
static double median_of(const double *samples, int count)
compute the median of an array of doubles
clock synchronization estimator
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
#define __n_assert(__ptr, __ret)
macro to assert things
#define Free(__ptr)
Free Handler to get errors.
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_DEBUG
debug-level messages
#define LOG_ERR
error conditions
Clock synchronization estimator for networked games.
Common headers and low-level functions & define.