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 HCRYPTPROV hProv;
00038 if (!CryptAcquireContext(&hProv, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
00039 return (uint32_t)rand();
00040 }
00041
00042 uint32_t Result;
00043 CryptGenRandom(hProv, sizeof(Result), (BYTE*)&Result);
00044
00045 CryptReleaseContext(hProv, 0);
00046 return Result;
00047 }
00048
00049 uint64_t getcurrenttime(void)
00050 {
00051 static pthread_mutex_t lock = INVALID_HANDLE_VALUE;
00052 static uint64_t result = 0;
00053 static uint32_t previous_time = 0;
00054
00055
00056 if (lock == INVALID_HANDLE_VALUE) {
00057 pthread_mutex_init(&lock, NULL);
00058 }
00059
00060 pthread_mutex_lock(&lock);
00061
00062 uint32_t current_time = GetTickCount();
00063
00064 if (current_time > previous_time) {
00065 result += current_time - previous_time;
00066 }
00067
00068 previous_time = current_time;
00069
00070 pthread_mutex_unlock(&lock);
00071 return result;
00072 }
00073
00074 void msleep_approx(uint64_t ms)
00075 {
00076 Sleep((DWORD)ms);
00077 }
00078
00079 void msleep_minimum(uint64_t ms)
00080 {
00081 uint64_t stop_time = getcurrenttime() + ms;
00082
00083 while (1) {
00084 uint64_t current_time = getcurrenttime();
00085 if (current_time >= stop_time) {
00086 return;
00087 }
00088
00089 msleep_approx(stop_time - current_time);
00090 }
00091 }
00092
00093 #if !defined(PTHREAD_H)
00094 int pthread_create(pthread_t *tid, void *attr, LPTHREAD_START_ROUTINE start, void *arg)
00095 {
00096 *tid = CreateThread(NULL, 0, start, arg, 0, NULL);
00097 if (!*tid) {
00098 return (int)GetLastError();
00099 }
00100 return 0;
00101 }
00102
00103 int pthread_join(pthread_t tid, void **value_ptr)
00104 {
00105 while (1) {
00106 DWORD ExitCode = 0;
00107 if (!GetExitCodeThread(tid, &ExitCode)) {
00108 return (int)GetLastError();
00109 }
00110 if (ExitCode != STILL_ACTIVE) {
00111 return 0;
00112 }
00113 }
00114 }
00115
00116 void pthread_mutex_init(pthread_mutex_t *mutex, void *attr)
00117 {
00118 *mutex = CreateMutex(NULL, FALSE, NULL);
00119 }
00120
00121 void pthread_mutex_lock(pthread_mutex_t *mutex)
00122 {
00123 WaitForSingleObject(*mutex, INFINITE);
00124 }
00125
00126 void pthread_mutex_unlock(pthread_mutex_t *mutex)
00127 {
00128 ReleaseMutex(*mutex);
00129 }
00130 #endif
00131
00132
00133
00134
00135
00136
00137 void console_vprintf(const char *fmt, va_list ap)
00138 {
00139 UINT cp = GetConsoleOutputCP();
00140 SetConsoleOutputCP(CP_UTF8);
00141 vprintf(fmt, ap);
00142 SetConsoleOutputCP(cp);
00143 }
00144
00145 void console_printf(const char *fmt, ...)
00146 {
00147 va_list ap;
00148 va_start(ap, fmt);
00149 console_vprintf(fmt, ap);
00150 va_end(ap);
00151 }