00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #include "hdhomerun_os.h"
00034
00035 uint32_t random_get32(void)
00036 {
00037 FILE *fp = fopen("/dev/urandom", "rb");
00038 if (!fp) {
00039 return (uint32_t)rand();
00040 }
00041
00042 uint32_t Result;
00043 if (fread(&Result, 4, 1, fp) != 1) {
00044 Result = (uint32_t)rand();
00045 }
00046
00047 fclose(fp);
00048 return Result;
00049 }
00050
00051 uint64_t getcurrenttime(void)
00052 {
00053 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
00054 static uint64_t result = 0;
00055 static uint64_t previous_time = 0;
00056
00057 pthread_mutex_lock(&lock);
00058
00059 #if defined(CLOCK_MONOTONIC)
00060 struct timespec tp;
00061 clock_gettime(CLOCK_MONOTONIC, &tp);
00062 uint64_t current_time = ((uint64_t)tp.tv_sec * 1000) + (tp.tv_nsec / 1000000);
00063 #else
00064 struct timeval t;
00065 gettimeofday(&t, NULL);
00066 uint64_t current_time = ((uint64_t)t.tv_sec * 1000) + (t.tv_usec / 1000);
00067 #endif
00068
00069 if (current_time > previous_time) {
00070 result += current_time - previous_time;
00071 }
00072
00073 previous_time = current_time;
00074
00075 pthread_mutex_unlock(&lock);
00076 return result;
00077 }
00078
00079 void msleep_approx(uint64_t ms)
00080 {
00081 unsigned int delay_s = ms / 1000;
00082 if (delay_s > 0) {
00083 sleep(delay_s);
00084 ms -= delay_s * 1000;
00085 }
00086
00087 unsigned int delay_us = ms * 1000;
00088 if (delay_us > 0) {
00089 usleep(delay_us);
00090 }
00091 }
00092
00093 void msleep_minimum(uint64_t ms)
00094 {
00095 uint64_t stop_time = getcurrenttime() + ms;
00096
00097 while (1) {
00098 uint64_t current_time = getcurrenttime();
00099 if (current_time >= stop_time) {
00100 return;
00101 }
00102
00103 msleep_approx(stop_time - current_time);
00104 }
00105 }