Raw ↗
+ +
d9fbf5b fix(ci): resolve windows dshow com exports, qpc timer overflow, and temp path
saifmukhtar · 2026-11-25
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * include/avx_platform.h - Cross-platform socket, threading, and timer abstractions
7 */
8  
9 #ifndef AVX_PLATFORM_H
10 #define AVX_PLATFORM_H
11  
12 #include <stdint.h>
13 #include <stdbool.h>
14 #include <stddef.h>
15 #include <time.h>
16 #include <string.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19  
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23  
24 /* ========================================================================= */
25 /* 1. OS & PLATFORM IDENTIFICATION */
26 /* ========================================================================= */
27  
28 #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
29 #define AVX_OS_WINDOWS 1
30 #define AVX_PLATFORM_NAME "Windows"
31 #elif defined(__APPLE__) && defined(__MACH__)
32 #define AVX_OS_MACOS 1
33 #define AVX_OS_POSIX 1
34 #define AVX_PLATFORM_NAME "macOS"
35 #elif defined(__linux__)
36 #define AVX_OS_LINUX 1
37 #define AVX_OS_POSIX 1
38 #define AVX_PLATFORM_NAME "Linux"
39 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
40 #define AVX_OS_BSD 1
41 #define AVX_OS_POSIX 1
42 #define AVX_PLATFORM_NAME "BSD"
43 #else
44 #define AVX_OS_POSIX 1
45 #define AVX_PLATFORM_NAME "POSIX"
46 #endif
47  
48 /* Architecture Identification */
49 #if defined(__x86_64__) || defined(_M_X64)
50 #define AVX_ARCH_X86_64 1
51 #define AVX_ARCH_NAME "x86_64"
52 #elif defined(__aarch64__) || defined(_M_ARM64)
53 #define AVX_ARCH_ARM64 1
54 #define AVX_ARCH_NAME "ARM64"
55 #elif defined(__arm__) || defined(_M_ARM)
56 #define AVX_ARCH_ARM32 1
57 #define AVX_ARCH_NAME "ARM32"
58 #elif defined(__i386__) || defined(_M_IX86)
59 #define AVX_ARCH_X86 1
60 #define AVX_ARCH_NAME "x86"
61 #else
62 #define AVX_ARCH_NAME "Generic"
63 #endif
64  
65 /* SIMD Function Target Attributes (Clang/GCC function multi-versioning, no-op on MSVC) */
66 #if defined(__GNUC__) || defined(__clang__)
67 #define AVX_TARGET_AVX2 __attribute__((target("avx2,fma")))
68 #else
69 #define AVX_TARGET_AVX2
70 #endif
71  
72 /* Path separators */
73 #if defined(AVX_OS_WINDOWS)
74 #define AVX_PATH_SEP "\\"
75 #define AVX_PATH_SEP_CHAR '\\'
76 #else
77 #define AVX_PATH_SEP "/"
78 #define AVX_PATH_SEP_CHAR '/'
79 #endif
80  
81 /* ========================================================================= */
82 /* 2. SOCKET & NETWORKING ABSTRACTION */
83 /* ========================================================================= */
84  
85 #if defined(AVX_OS_WINDOWS)
86  
87 #ifndef WIN32_LEAN_AND_MEAN
88 #define WIN32_LEAN_AND_MEAN
89 #endif
90 #include <winsock2.h>
91 #include <ws2tcpip.h>
92 #include <mstcpip.h>
93 #include <windows.h>
94 #include <io.h>
95 #include "compat/win32/unistd.h"
96  
97 typedef SOCKET avx_socket_t;
98 typedef int avx_socklen_t;
99 typedef WSAPOLLFD avx_pollfd_t;
100 typedef ULONG avx_nfds_t;
101  
102 #define AVX_INVALID_SOCKET INVALID_SOCKET
103 #define AVX_SOCKET_ERROR SOCKET_ERROR
104 #define avx_socket_is_valid(s) ((s) != INVALID_SOCKET)
105  
106 #define avx_socket_close(s) closesocket(s)
107 #define avx_socket_errno() WSAGetLastError()
108  
109 #define AVX_EWOULDBLOCK WSAEWOULDBLOCK
110 #define AVX_EAGAIN WSAEWOULDBLOCK
111 #define AVX_EINPROGRESS WSAEINPROGRESS
112 #define AVX_EINTR WSAEINTR
113 #define AVX_ECONNRESET WSAECONNRESET
114  
115 #define AVX_SHUT_RDWR SD_BOTH
116 #define AVX_SHUT_RD SD_RECEIVE
117 #define AVX_SHUT_WR SD_SEND
118  
119 #define avx_poll WSAPoll
120  
121 #ifndef MSG_NOSIGNAL
122 #define MSG_NOSIGNAL 0
123 #endif
124  
125 #if defined(AVX_OS_WINDOWS) || defined(_WIN32)
126 #if defined(_MSC_VER)
127 #ifndef strtok_r
128 #define strtok_r(s, d, p) strtok_s(s, d, p)
129 #endif
130 #endif
131 #ifndef strcasecmp
132 #define strcasecmp _stricmp
133 #endif
134 #ifndef strncasecmp
135 #define strncasecmp _strnicmp
136 #endif
137 static inline char* avx_strcasestr_impl(const char *haystack, const char *needle) {
138 if (!haystack || !needle) return NULL;
139 if (*needle == '\0') return (char*)haystack;
140 size_t nlen = strlen(needle);
141 for (; *haystack != '\0'; ++haystack) {
142 if (_strnicmp(haystack, needle, nlen) == 0) {
143 return (char*)haystack;
144 }
145 }
146 return NULL;
147 }
148 #ifndef strcasestr
149 #define strcasestr avx_strcasestr_impl
150 #endif
151 #include <intrin.h>
152 #ifndef __sync_synchronize
153 #define __sync_synchronize() MemoryBarrier()
154 #endif
155 #ifndef __sync_lock_test_and_set
156 #define __sync_lock_test_and_set(ptr, val) _InterlockedExchange((volatile long*)(ptr), (long)(val))
157 #endif
158 #endif
159  
160 static inline int avx_gettimeofday(struct timeval *tv, void *tz) {
161 (void)tz;
162 if (!tv) return -1;
163 FILETIME ft;
164 GetSystemTimeAsFileTime(&ft);
165 ULARGE_INTEGER u;
166 u.LowPart = ft.dwLowDateTime;
167 u.HighPart = ft.dwHighDateTime;
168 uint64_t t = u.QuadPart - 116444736000000000ULL;
169 tv->tv_sec = (long)(t / 10000000ULL);
170 tv->tv_usec = (long)((t % 10000000ULL) / 10);
171 return 0;
172 }
173 #ifndef gettimeofday
174 #define gettimeofday(tv, tz) avx_gettimeofday((tv), (tz))
175 #endif
176  
177 #ifndef CLOCK_MONOTONIC
178 #define CLOCK_MONOTONIC 1
179 #endif
180 #ifndef CLOCK_REALTIME
181 #define CLOCK_REALTIME 0
182 #endif
183  
184 static inline int avx_compat_clock_gettime(int clk_id, struct timespec *ts) {
185 if (!ts) return -1;
186 if (clk_id == CLOCK_MONOTONIC) {
187 LARGE_INTEGER freq, count;
188 QueryPerformanceFrequency(&freq);
189 QueryPerformanceCounter(&count);
190 ts->tv_sec = (time_t)(count.QuadPart / freq.QuadPart);
191 ts->tv_nsec = (long)(((count.QuadPart % freq.QuadPart) * 1000000000LL) / freq.QuadPart);
192 return 0;
193 } else {
194 FILETIME ft;
195 GetSystemTimeAsFileTime(&ft);
196 ULARGE_INTEGER u;
197 u.LowPart = ft.dwLowDateTime;
198 u.HighPart = ft.dwHighDateTime;
199 uint64_t t = u.QuadPart - 116444736000000000ULL;
200 ts->tv_sec = (time_t)(t / 10000000ULL);
201 ts->tv_nsec = (long)((t % 10000000ULL) * 100);
202 return 0;
203 }
204 }
205 #ifndef clock_gettime
206 #define clock_gettime(clk, ts) avx_compat_clock_gettime((clk), (ts))
207 #endif
208  
209 static inline int avx_compat_nanosleep(const struct timespec *req, struct timespec *rem) {
210 (void)rem;
211 if (!req) return -1;
212 DWORD ms = (DWORD)(req->tv_sec * 1000 + (req->tv_nsec + 999999) / 1000000);
213 Sleep(ms);
214 return 0;
215 }
216 #ifndef nanosleep
217 #define nanosleep(req, rem) avx_compat_nanosleep((req), (rem))
218 #endif
219  
220 #else /* POSIX (Linux, macOS, BSD) */
221  
222 #include <sys/types.h>
223 #include <sys/time.h>
224 #include <sys/socket.h>
225 #include <netinet/in.h>
226 #include <netinet/tcp.h>
227 #include <arpa/inet.h>
228 #include <netdb.h>
229 #include <sys/ioctl.h>
230 #include <poll.h>
231 #include <unistd.h>
232 #include <fcntl.h>
233 #include <errno.h>
234 #include <signal.h>
235  
236 static inline int avx_gettimeofday(struct timeval *tv, void *tz) {
237 return gettimeofday(tv, (struct timezone *)tz);
238 }
239  
240 typedef int avx_socket_t;
241 typedef socklen_t avx_socklen_t;
242 typedef struct pollfd avx_pollfd_t;
243 typedef nfds_t avx_nfds_t;
244  
245 #define AVX_INVALID_SOCKET (-1)
246 #define AVX_SOCKET_ERROR (-1)
247 #define avx_socket_is_valid(s) ((s) >= 0)
248  
249 #define avx_socket_close(s) close(s)
250 #define avx_socket_errno() (errno)
251  
252 #define AVX_EWOULDBLOCK EWOULDBLOCK
253 #define AVX_EAGAIN EAGAIN
254 #define AVX_EINPROGRESS EINPROGRESS
255 #define AVX_EINTR EINTR
256 #define AVX_ECONNRESET ECONNRESET
257  
258 #define AVX_SHUT_RDWR SHUT_RDWR
259 #define AVX_SHUT_RD SHUT_RD
260 #define AVX_SHUT_WR SHUT_WR
261  
262 #define avx_poll poll
263  
264 #ifndef MSG_NOSIGNAL
265 #define MSG_NOSIGNAL 0
266 #endif
267  
268 #if defined(AVX_OS_WINDOWS) || defined(_WIN32)
269 #if defined(_MSC_VER)
270 #ifndef strtok_r
271 #define strtok_r(s, d, p) strtok_s(s, d, p)
272 #endif
273 #endif
274 #ifndef strcasecmp
275 #define strcasecmp _stricmp
276 #endif
277 #ifndef strncasecmp
278 #define strncasecmp _strnicmp
279 #endif
280 #include <intrin.h>
281 #ifndef __sync_synchronize
282 #define __sync_synchronize() MemoryBarrier()
283 #endif
284 #ifndef __sync_lock_test_and_set
285 #define __sync_lock_test_and_set(ptr, val) _InterlockedExchange((volatile long*)(ptr), (long)(val))
286 #endif
287 #endif
288  
289 #endif
290  
291 /* Set SO_NOSIGPIPE on socket (macOS & BSD prevent SIGPIPE on broken connections) */
292 static inline void avx_socket_set_nosigpipe(avx_socket_t s) {
293 #if (defined(AVX_OS_MACOS) || defined(AVX_OS_BSD)) && defined(SO_NOSIGPIPE)
294 int opt = 1;
295 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (const char *)&opt, sizeof(opt));
296 #else
297 (void)s;
298 #endif
299 }
300  
301 /* Set socket non-blocking mode */
302 static inline int avx_socket_set_nonblocking(avx_socket_t s, bool nonblock) {
303 #if defined(AVX_OS_WINDOWS)
304 u_long mode = nonblock ? 1 : 0;
305 return ioctlsocket(s, FIONBIO, &mode);
306 #else
307 int flags = fcntl(s, F_GETFL, 0);
308 if (flags < 0) return -1;
309 flags = nonblock ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
310 return fcntl(s, F_SETFL, flags);
311 #endif
312 }
313  
314 /* Enable and configure TCP keepalive probes on socket */
315 static inline int avx_socket_set_keepalive(avx_socket_t s, int idle_sec, int interval_sec, int count) {
316 if (!avx_socket_is_valid(s)) return -1;
317 int opt = 1;
318 if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (const char *)&opt, sizeof(opt)) < 0) {
319 return -1;
320 }
321  
322 #if defined(AVX_OS_WINDOWS)
323 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) && defined(TCP_KEEPCNT)
324 setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, (const char *)&idle_sec, sizeof(idle_sec));
325 setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, (const char *)&interval_sec, sizeof(interval_sec));
326 setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, (const char *)&count, sizeof(count));
327 #elif defined(SIO_KEEPALIVE_VALS)
328 struct tcp_keepalive vals;
329 vals.onoff = 1;
330 vals.keepalivetime = (u_long)(idle_sec * 1000);
331 vals.keepaliveinterval = (u_long)(interval_sec * 1000);
332 DWORD bytes_ret = 0;
333 WSAIoctl(s, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &bytes_ret, NULL, NULL);
334 #endif
335 #else
336 #if defined(TCP_KEEPIDLE)
337 setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, (const char *)&idle_sec, sizeof(idle_sec));
338 #elif defined(TCP_KEEPALIVE)
339 setsockopt(s, IPPROTO_TCP, TCP_KEEPALIVE, (const char *)&idle_sec, sizeof(idle_sec));
340 #endif
341  
342 #if defined(TCP_KEEPINTVL)
343 setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, (const char *)&interval_sec, sizeof(interval_sec));
344 #endif
345  
346 #if defined(TCP_KEEPCNT)
347 setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, (const char *)&count, sizeof(count));
348 #endif
349 #endif
350 return 0;
351 }
352  
353 /* Configure TCP_NODELAY (disable Nagle algorithm for low-latency streaming) */
354 static inline int avx_socket_set_tcp_nodelay(avx_socket_t s, bool nodelay) {
355 if (!avx_socket_is_valid(s)) return -1;
356 int opt = nodelay ? 1 : 0;
357 return setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char *)&opt, sizeof(opt));
358 }
359  
360 /* Configure socket receive timeout in milliseconds */
361 static inline int avx_socket_set_recv_timeout(avx_socket_t s, uint32_t timeout_ms) {
362 if (!avx_socket_is_valid(s)) return -1;
363 #if defined(AVX_OS_WINDOWS)
364 DWORD tv = (DWORD)timeout_ms;
365 return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));
366 #else
367 struct timeval tv;
368 tv.tv_sec = (time_t)(timeout_ms / 1000);
369 tv.tv_usec = (suseconds_t)((timeout_ms % 1000) * 1000);
370 return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));
371 #endif
372 }
373  
374 /* Configure socket send timeout in milliseconds */
375 static inline int avx_socket_set_send_timeout(avx_socket_t s, uint32_t timeout_ms) {
376 if (!avx_socket_is_valid(s)) return -1;
377 #if defined(AVX_OS_WINDOWS)
378 DWORD tv = (DWORD)timeout_ms;
379 return setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof(tv));
380 #else
381 struct timeval tv;
382 tv.tv_sec = (time_t)(timeout_ms / 1000);
383 tv.tv_usec = (suseconds_t)((timeout_ms % 1000) * 1000);
384 return setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof(tv));
385 #endif
386 }
387  
388 /* Initialize platform sockets (Winsock startup on Windows, SIGPIPE ignore on POSIX) */
389 static inline bool avx_platform_sockets_init(void) {
390 #if defined(AVX_OS_WINDOWS)
391 #if defined(_MSC_VER)
392 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
393 #endif
394 WSADATA wsa;
395 return (WSAStartup(MAKEWORD(2, 2), &wsa) == 0);
396 #elif defined(AVX_OS_POSIX)
397 #if defined(SIGPIPE)
398 signal(SIGPIPE, SIG_IGN);
399 #endif
400 return true;
401 #else
402 return true;
403 #endif
404 }
405  
406 /* Cleanup platform sockets (WSACleanup on Windows, no-op on POSIX) */
407 static inline void avx_platform_sockets_cleanup(void) {
408 #if defined(AVX_OS_WINDOWS)
409 WSACleanup();
410 #endif
411 }
412  
413 /* ========================================================================= */
414 /* 3. THREADING & SYNCHRONIZATION ABSTRACTION */
415 /* ========================================================================= */
416  
417 #if !defined(AVX_OS_WINDOWS) || defined(__MINGW32__) || defined(__MINGW64__)
418  
419 #include <pthread.h>
420  
421 typedef pthread_t avx_thread_t;
422 typedef pthread_mutex_t avx_mutex_t;
423 typedef pthread_cond_t avx_cond_t;
424  
425 #define AVX_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
426 #define AVX_COND_INITIALIZER PTHREAD_COND_INITIALIZER
427  
428 #define avx_mutex_init(m) pthread_mutex_init((m), NULL)
429 #define avx_mutex_destroy(m) pthread_mutex_destroy(m)
430 #define avx_mutex_lock(m) pthread_mutex_lock(m)
431 #define avx_mutex_unlock(m) pthread_mutex_unlock(m)
432  
433 #define avx_cond_init(c) pthread_cond_init((c), NULL)
434 #define avx_cond_destroy(c) pthread_cond_destroy(c)
435 #define avx_cond_wait(c, m) pthread_cond_wait((c), (m))
436 #define avx_cond_signal(c) pthread_cond_signal(c)
437 #define avx_cond_broadcast(c) pthread_cond_broadcast(c)
438  
439 static inline int avx_cond_timedwait(avx_cond_t *c, avx_mutex_t *m, uint32_t timeout_ms) {
440 struct timespec ts;
441 clock_gettime(CLOCK_REALTIME, &ts);
442 ts.tv_sec += (time_t)(timeout_ms / 1000);
443 ts.tv_nsec += (long)((timeout_ms % 1000) * 1000000L);
444 if (ts.tv_nsec >= 1000000000L) {
445 ts.tv_sec += 1;
446 ts.tv_nsec -= 1000000000L;
447 }
448 int rc = pthread_cond_timedwait(c, m, &ts);
449 return (rc == 0) ? 0 : -1;
450 }
451  
452 static inline int avx_thread_create(avx_thread_t *t, void *(*fn)(void *), void *arg) {
453 pthread_attr_t attr;
454 pthread_attr_init(&attr);
455 /* Ensure at least 2 MB stack to prevent stack overflow on musl libc (Alpine) */
456 pthread_attr_setstacksize(&attr, 2 * 1024 * 1024);
457 int rc = pthread_create(t, &attr, fn, arg);
458 pthread_attr_destroy(&attr);
459 return rc;
460 }
461 #define avx_thread_join(t) pthread_join((t), NULL)
462  
463 #else /* Windows Native Threads & Synchronization */
464  
465 #include <windows.h>
466 #include <process.h>
467  
468 typedef HANDLE avx_thread_t;
469 typedef SRWLOCK avx_mutex_t;
470 typedef CONDITION_VARIABLE avx_cond_t;
471  
472 #define AVX_MUTEX_INITIALIZER SRWLOCK_INIT
473 #define AVX_COND_INITIALIZER CONDITION_VARIABLE_INIT
474  
475 #define avx_mutex_init(m) InitializeSRWLock(m)
476 #define avx_mutex_destroy(m) ((void)(m))
477 #define avx_mutex_lock(m) AcquireSRWLockExclusive(m)
478 #define avx_mutex_unlock(m) ReleaseSRWLockExclusive(m)
479  
480 #define avx_cond_init(c) InitializeConditionVariable(c)
481 #define avx_cond_destroy(c) ((void)(c))
482 #define avx_cond_wait(c, m) SleepConditionVariableSRW((c), (m), INFINITE, 0)
483 #define avx_cond_signal(c) WakeConditionVariable(c)
484 #define avx_cond_broadcast(c) WakeAllConditionVariable(c)
485  
486 static inline int avx_cond_timedwait(avx_cond_t *c, avx_mutex_t *m, uint32_t timeout_ms) {
487 return SleepConditionVariableSRW(c, m, (DWORD)timeout_ms, 0) ? 0 : -1;
488 }
489  
490 typedef void *(*avx_thread_fn_t)(void *);
491 struct avx_win_thread_arg_s {
492 avx_thread_fn_t fn;
493 void *arg;
494 };
495  
496 static inline unsigned __stdcall avx_win_thread_trampoline(void *p) {
497 struct avx_win_thread_arg_s *a = (struct avx_win_thread_arg_s *)p;
498 avx_thread_fn_t fn = a->fn;
499 void *arg = a->arg;
500 free(a);
501 fn(arg);
502 return 0;
503 }
504  
505 static inline int avx_thread_create(avx_thread_t *t, void *(*fn)(void *), void *arg) {
506 struct avx_win_thread_arg_s *a = (struct avx_win_thread_arg_s *)malloc(sizeof(*a));
507 if (!a) return -1;
508 a->fn = fn;
509 a->arg = arg;
510 uintptr_t h = _beginthreadex(NULL, 0, avx_win_thread_trampoline, a, 0, NULL);
511 if (!h) {
512 free(a);
513 return -1;
514 }
515 *t = (HANDLE)h;
516 return 0;
517 }
518  
519 static inline int avx_thread_join(avx_thread_t t) {
520 WaitForSingleObject(t, INFINITE);
521 CloseHandle(t);
522 return 0;
523 }
524  
525 #endif
526  
527 /* ========================================================================= */
528 /* 4. DYNAMIC LIBRARY LOADING ABSTRACTION */
529 /* ========================================================================= */
530  
531 #if defined(AVX_OS_WINDOWS)
532 #define avx_dlopen(path) ((void *)LoadLibraryA(path))
533 #define avx_dlsym(handle, sym) ((void *)GetProcAddress((HMODULE)(handle), (sym)))
534 #define avx_dlclose(handle) FreeLibrary((HMODULE)(handle))
535 #else
536 #include <dlfcn.h>
537 #define avx_dlopen(path) dlopen(path, RTLD_LAZY | RTLD_GLOBAL)
538 #define avx_dlsym(handle, sym) dlsym(handle, sym)
539 #define avx_dlclose(handle) dlclose(handle)
540 #endif
541  
542 /* ========================================================================= */
543 /* 5. HIGH-RESOLUTION TIMERS & SLEEP ABSTRACTION */
544 /* ========================================================================= */
545  
546 #if defined(AVX_OS_WINDOWS)
547  
548 static inline void avx_sleep_ms(uint32_t ms) {
549 Sleep((DWORD)ms);
550 }
551  
552 static inline void avx_sleep_ns(uint64_t ns) {
553 avx_sleep_ms((uint32_t)((ns + 999999ULL) / 1000000ULL));
554 }
555  
556 static inline int64_t avx_time_ms(void) {
557 return (int64_t)GetTickCount64();
558 }
559  
560 static inline int64_t avx_time_ns(void) {
561 LARGE_INTEGER freq, count;
562 QueryPerformanceFrequency(&freq);
563 QueryPerformanceCounter(&count);
564 int64_t sec = (int64_t)(count.QuadPart / freq.QuadPart);
565 int64_t rem = (int64_t)(count.QuadPart % freq.QuadPart);
566 return (sec * 1000000000LL) + ((rem * 1000000000LL) / freq.QuadPart);
567 }
568  
569 static inline int64_t avx_time_100ns(void) {
570 FILETIME ft;
571 GetSystemTimeAsFileTime(&ft);
572 ULARGE_INTEGER u;
573 u.LowPart = ft.dwLowDateTime;
574 u.HighPart = ft.dwHighDateTime;
575 return (int64_t)u.QuadPart;
576 }
577  
578 #else /* POSIX (Linux, macOS, BSD) */
579  
580 static inline void avx_sleep_ms(uint32_t ms) {
581 struct timespec ts;
582 ts.tv_sec = (time_t)(ms / 1000);
583 ts.tv_nsec = (long)((ms % 1000) * 1000000L);
584 nanosleep(&ts, NULL);
585 }
586  
587 static inline void avx_sleep_ns(uint64_t ns) {
588 struct timespec ts;
589 ts.tv_sec = (time_t)(ns / 1000000000ULL);
590 ts.tv_nsec = (long)(ns % 1000000000ULL);
591 nanosleep(&ts, NULL);
592 }
593  
594 static inline int64_t avx_time_ms(void) {
595 struct timespec ts;
596 clock_gettime(CLOCK_MONOTONIC, &ts);
597 return ((int64_t)ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000LL);
598 }
599  
600 static inline int64_t avx_time_ns(void) {
601 struct timespec ts;
602 clock_gettime(CLOCK_MONOTONIC, &ts);
603 return ((int64_t)ts.tv_sec * 1000000000LL) + (int64_t)ts.tv_nsec;
604 }
605  
606 static inline int64_t avx_time_100ns(void) {
607 struct timespec ts;
608 clock_gettime(CLOCK_REALTIME, &ts);
609 return ((int64_t)ts.tv_sec * 10000000LL) + (ts.tv_nsec / 100LL);
610 }
611  
612 #endif
613  
614 /* ========================================================================= */
615 /* 6. COMPATIBILITY, TYPES & PACKING HELPERS */
616 /* ========================================================================= */
617  
618 #if defined(_MSC_VER)
619 #include <BaseTsd.h>
620 typedef SSIZE_T ssize_t;
621  
622 #define AVX_PACKED_START __pragma(pack(push, 1))
623 #define AVX_PACKED_END __pragma(pack(pop))
624 #define AVX_PACKED
625 #else
626 #define AVX_PACKED_START
627 #define AVX_PACKED_END
628 #define AVX_PACKED __attribute__((packed))
629 #endif
630  
631 /* Cache-line & DMA aligned memory allocation (64-byte alignment for ARM/AVX2/DMA) */
632 static inline void *avx_aligned_alloc(size_t alignment, size_t size) {
633 #if defined(AVX_OS_WINDOWS)
634 return _aligned_malloc(size, alignment);
635 #elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L) || defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 600) || \
636 defined(__APPLE__) || defined(__FreeBSD__)
637 void *ptr = NULL;
638 if (posix_memalign(&ptr, alignment, size) != 0) return NULL;
639 return ptr;
640 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
641 return aligned_alloc(alignment, size);
642 #else
643 return malloc(size);
644 #endif
645 }
646  
647 static inline void avx_aligned_free(void *ptr) {
648 #if defined(AVX_OS_WINDOWS)
649 _aligned_free(ptr);
650 #else
651 free(ptr);
652 #endif
653 }
654  
655 #if defined(AVX_OS_WINDOWS)
656 #ifndef strcasecmp
657 #define strcasecmp _stricmp
658 #endif
659 #ifndef strncasecmp
660 #define strncasecmp _strnicmp
661 #endif
662 #ifndef popen
663 #define popen _popen
664 #endif
665 #ifndef pclose
666 #define pclose _pclose
667 #endif
668 #ifndef usleep
669 #define usleep(us) avx_sleep_ms(((us) + 999) / 1000)
670 #endif
671 #ifndef sleep
672 #define sleep(s) avx_sleep_ms((s) * 1000)
673 #endif
674 #ifndef R_OK
675 #define R_OK 4
676 #endif
677 #ifndef access
678 #define access _access
679 #endif
680 static inline int avx_setenv(const char *name, const char *value, int overwrite) {
681 if (!name || !value) return -1;
682 if (!overwrite && getenv(name) != NULL) return 0;
683 return (_putenv_s(name, value) == 0) ? 0 : -1;
684 }
685 static inline int avx_unsetenv(const char *name) {
686 if (!name) return -1;
687 return (_putenv_s(name, "") == 0) ? 0 : -1;
688 }
689 #ifndef setenv
690 #define setenv(name, value, overwrite) avx_setenv((name), (value), (overwrite))
691 #endif
692 #ifndef unsetenv
693 #define unsetenv(name) avx_unsetenv((name))
694 #endif
695 #endif
696  
697 /* Minimal getopt_long implementation for native MSVC */
698 #if defined(_MSC_VER)
699 struct option {
700 const char *name;
701 int has_arg;
702 int *flag;
703 int val;
704 };
705 #define no_argument 0
706 #define required_argument 1
707 #define optional_argument 2
708  
709 static char *avx_optarg = NULL;
710 static int avx_optind = 1;
711 #ifndef optarg
712 #define optarg avx_optarg
713 #endif
714 #ifndef optind
715 #define optind avx_optind
716 #endif
717  
718 static inline int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts,
719 int *longindex) {
720 if (avx_optind >= argc || !argv[avx_optind]) return -1;
721 char *arg = argv[avx_optind];
722 if (arg[0] != '-' || arg[1] == '\0') return -1;
723 if (arg[1] == '-' && arg[2] == '\0') {
724 avx_optind++;
725 return -1;
726 }
727  
728 if (arg[1] == '-') {
729 const char *opt_name = arg + 2;
730 const char *eq = strchr(opt_name, '=');
731 size_t name_len = eq ? (size_t)(eq - opt_name) : strlen(opt_name);
732  
733 for (int i = 0; longopts && longopts[i].name; ++i) {
734 if (strncmp(longopts[i].name, opt_name, name_len) == 0 && longopts[i].name[name_len] == '\0') {
735 if (longindex) *longindex = i;
736 avx_optind++;
737 if (longopts[i].has_arg == required_argument) {
738 if (eq) {
739 avx_optarg = (char *)(eq + 1);
740 } else if (avx_optind < argc) {
741 avx_optarg = argv[avx_optind++];
742 } else {
743 return '?';
744 }
745 } else if (longopts[i].has_arg == optional_argument && eq) {
746 avx_optarg = (char *)(eq + 1);
747 } else {
748 avx_optarg = NULL;
749 }
750 if (longopts[i].flag) {
751 *longopts[i].flag = longopts[i].val;
752 return 0;
753 }
754 return longopts[i].val;
755 }
756 }
757 return '?';
758 }
759  
760 char opt = arg[1];
761 avx_optind++;
762 const char *match = strchr(optstring, opt);
763 if (!match) return '?';
764  
765 if (match[1] == ':') {
766 if (match[2] == ':') {
767 avx_optarg = (arg[2] != '\0') ? (arg + 2) : NULL;
768 } else if (arg[2] != '\0') {
769 avx_optarg = arg + 2;
770 } else if (avx_optind < argc) {
771 avx_optarg = argv[avx_optind++];
772 } else {
773 return '?';
774 }
775 } else {
776 avx_optarg = NULL;
777 }
778 return (int)opt;
779 }
780  
781 static inline int getopt(int argc, char *const argv[], const char *optstring) {
782 return getopt_long(argc, argv, optstring, NULL, NULL);
783 }
784 #else
785 #include <getopt.h>
786 #endif
787  
788 /* Thread-local storage abstraction */
789 #if defined(_MSC_VER)
790 #define AVX_THREAD_LOCAL __declspec(thread)
791 #elif defined(__GNUC__) || defined(__clang__)
792 #define AVX_THREAD_LOCAL __thread
793 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
794 #define AVX_THREAD_LOCAL _Thread_local
795 #else
796 #define AVX_THREAD_LOCAL
797 #endif
798  
799 #ifdef __cplusplus
800 }
801 #endif
802  
803 #endif /* AVX_PLATFORM_H */