Raw ↗
+ +
a18b27f fix(windows): resolve Win32 Winsock, signal, and CLI test compatibility
saifmukhtar · 2026-11-24
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 * test/openavx_concurrency_audit_test.c - Thread safety and lock hierarchy tests
7 *
8 * Runs 13 concurrency regression checks (F-01 through F-13) in monitored
9 * subprocesses with watchdog timers to detect deadlocks and lock contention.
10 */
11  
12 #define _GNU_SOURCE
13 #define _POSIX_C_SOURCE 200809L
14 #define _DEFAULT_SOURCE
15  
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include <string.h>
21 #include <signal.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <assert.h>
25 #include <pthread.h>
26 #include <sys/socket.h>
27 #include <sys/wait.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <time.h>
31  
32 #include "openavx.h"
33 #include "avx_internal.h"
34 #include "avx_platform.h"
35 #include "avx_wire.h"
36 #include "avx_speedhq.h"
37 #include "avx_video_codec.h"
38 #include "avx_discovery_server.h"
39 #include "avx_routing.h"
40  
41 static double get_time_ms(void) {
42 struct timespec ts;
43 clock_gettime(CLOCK_MONOTONIC, &ts);
44 return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1000000.0;
45 }
46  
47 typedef struct {
48 bool passed;
49 bool deadlocked;
50 bool crashed;
51 double duration_ms;
52 char details[512];
53 } audit_result_t;
54  
55 /* Monitored test runner executing test function in an isolated child process */
56 static audit_result_t run_monitored_test(void (*test_fn)(void), int timeout_ms, const char* name) {
57 audit_result_t res;
58 memset(&res, 0, sizeof(res));
59  
60 printf("\n======================================================================\n");
61 printf(" RUNNING AUDIT PROOF: %s\n", name);
62 printf(" (Monitored subprocess with %d ms watchdog timeout)\n", timeout_ms);
63 printf("======================================================================\n");
64  
65 #if defined(_WIN32)
66 double t0 = get_time_ms();
67 test_fn();
68 double t1 = get_time_ms();
69 res.duration_ms = t1 - t0;
70 res.passed = true;
71 snprintf(res.details, sizeof(res.details), "Completed cleanly in %.2f ms", res.duration_ms);
72 return res;
73 #else
74 double t0 = get_time_ms();
75 pid_t pid = fork();
76  
77 if (pid == 0) {
78 /* Child process: run the audit scenario */
79 alarm((unsigned int)(timeout_ms / 1000 + 2));
80 test_fn();
81 exit(0);
82 }
83  
84 if (pid < 0) {
85 res.passed = false;
86 snprintf(res.details, sizeof(res.details), "fork() failed: %s", strerror(errno));
87 return res;
88 }
89  
90 /* Parent process: monitor child with high-resolution poll */
91 int status = 0;
92 int elapsed = 0;
93 int step_ms = 25;
94  
95 while (elapsed < timeout_ms) {
96 pid_t p = waitpid(pid, &status, WNOHANG);
97 if (p == pid) {
98 double t1 = get_time_ms();
99 res.duration_ms = t1 - t0;
100 if (WIFEXITED(status)) {
101 int code = WEXITSTATUS(status);
102 if (code == 0) {
103 res.passed = true;
104 snprintf(res.details, sizeof(res.details), "Completed cleanly in %.2f ms (Exit Code 0)", res.duration_ms);
105 } else {
106 res.passed = false;
107 snprintf(res.details, sizeof(res.details), "Subprocess exited with failure code %d in %.2f ms", code, res.duration_ms);
108 }
109 } else if (WIFSIGNALED(status)) {
110 int sig = WTERMSIG(status);
111 res.crashed = true;
112 res.passed = false;
113 snprintf(res.details, sizeof(res.details), "CRASH: Subprocess killed by signal %d (%s)", sig, strsignal(sig));
114 }
115 return res;
116 }
117 usleep(step_ms * 1000);
118 elapsed += step_ms;
119 }
120  
121 /* Subprocess failed to complete within timeout -> Deadlock detected! */
122 double t1 = get_time_ms();
123 res.duration_ms = t1 - t0;
124 res.deadlocked = true;
125 res.passed = false;
126 snprintf(res.details, sizeof(res.details), "DEADLOCK: Subprocess hung for > %d ms, forcibly killed", timeout_ms);
127  
128 kill(pid, SIGKILL);
129 waitpid(pid, &status, 0);
130 return res;
131 #endif
132 }
133  
134 /* ========================================================================= */
135 /* PROOF F-01: Engine Teardown Self-Deadlock on global_lock */
136 /* ========================================================================= */
137  
138 static void proof_f01_engine_teardown_self_deadlock(void) {
139 printf("[*] F-01: Initializing engine and creating an active find instance...\n");
140 avx_engine_initialize();
141  
142 avx_find_config_t fcfg = { .show_local_sources = false };
143 avx_find_instance_t finder = avx_find_create(&fcfg);
144 if (!finder) {
145 printf(" [-] Failed to create finder\n");
146 exit(1);
147 }
148  
149 printf(" [+] Finder created successfully. slot->in_use = true.\n");
150 printf(" [*] Calling avx_engine_destroy()...\n");
151  
152 avx_engine_destroy();
153  
154 printf(" [+] F-01 PASS: avx_engine_destroy() completed without self-deadlock\n");
155 }
156  
157 /* ========================================================================= */
158 /* PROOF F-02: ABBA Deadlock Between slot->lock and global_lock */
159 /* ========================================================================= */
160  
161 static volatile bool g_f02_stop = false;
162  
163 static void* f02_query_thread(void* arg) {
164 avx_find_instance_t finder = (avx_find_instance_t)arg;
165 while (!g_f02_stop) {
166 uint32_t count = 0;
167 /* avx_find_get_sources locks slot->lock, then avx_find_refresh_sources locks global_lock */
168 avx_find_get_sources(finder, &count);
169 usleep(100);
170 }
171 return NULL;
172 }
173  
174 static void proof_f02_abba_deadlock(void) {
175 printf("[*] F-02: Demonstrating ABBA lock order inversion between slot->lock and global_lock...\n");
176 avx_engine_initialize();
177  
178 avx_find_config_t fcfg = { .show_local_sources = true };
179 avx_find_instance_t finder = avx_find_create(&fcfg);
180 if (!finder) exit(1);
181  
182 pthread_t th;
183 pthread_create(&th, NULL, f02_query_thread, finder);
184  
185 /* Thread 2 repeatedly acquires global_lock and destroys instances */
186 for (int i = 0; i < 50; ++i) {
187 avx_tx_config_t sc = { .name = "TempTx", .clock_video = false, .clock_audio = false };
188 avx_tx_instance_t tx = avx_tx_create(&sc);
189 if (tx) {
190 usleep(200);
191 avx_tx_destroy(tx);
192 }
193 }
194  
195 g_f02_stop = true;
196 pthread_join(th, NULL);
197 avx_find_destroy(finder);
198 }
199  
200 /* ========================================================================= */
201 /* PROOF F-03: Teardown Deadlock in avx_rx_destroy() During Active Ingestion */
202 /* ========================================================================= */
203  
204 static int g_f03_srv_sock = -1;
205 static int g_f03_client_sock = -1;
206 static uint16_t g_f03_port = 0;
207  
208 static void* f03_dummy_sender(void* arg) {
209 (void)arg;
210 struct sockaddr_in client_addr;
211 socklen_t client_len = sizeof(client_addr);
212 g_f03_client_sock = accept(g_f03_srv_sock, (struct sockaddr*)&client_addr, &client_len);
213 if (g_f03_client_sock < 0) return NULL;
214  
215 /* 1. Send XML handshake */
216 const char *xml = "<openavx version=\"1.0\" service=\"Test\"/>";
217 uint32_t xml_len = (uint32_t)strlen(xml);
218 send(g_f03_client_sock, (const char*)&xml_len, sizeof(xml_len), 0);
219 send(g_f03_client_sock, xml, xml_len, 0);
220  
221 /* 2. Send video magic and header with large payload (1 MB) */
222 uint32_t magic = OAVX_WIRE_MAGIC_VIDEO;
223 send(g_f03_client_sock, (const char*)&magic, sizeof(magic), 0);
224  
225 AVX_PACKED_START
226 struct {
227 uint32_t xres;
228 uint32_t yres;
229 uint32_t fourcc;
230 int32_t frame_rate_n;
231 int32_t frame_rate_d;
232 int64_t timecode;
233 uint32_t payload_len;
234 } AVX_PACKED vhdr;
235 AVX_PACKED_END
236 memset(&vhdr, 0, sizeof(vhdr));
237 vhdr.xres = 1920;
238 vhdr.yres = 1080;
239 vhdr.fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2; /* Compressed frame: bypasses min_raw check */
240 vhdr.frame_rate_n = 60;
241 vhdr.frame_rate_d = 1;
242 vhdr.payload_len = 500000; /* 500 KB */
243 send(g_f03_client_sock, (const char*)&vhdr, sizeof(vhdr), 0);
244  
245 /* 3. Send ONLY 128 bytes and intentionally STALL without closing socket! */
246 char partial[128] = {0};
247 send(g_f03_client_sock, partial, sizeof(partial), 0);
248  
249 /* Keep connection stalled */
250 while (1) {
251 sleep(1);
252 }
253 return NULL;
254 }
255  
256 static void* f03_receiver_worker(void* arg) {
257 avx_rx_instance_t rx = (avx_rx_instance_t)arg;
258 oavx_video_frame_t vf;
259 oavx_audio_frame_t af;
260 oavx_metadata_frame_t mf;
261 printf(" [RX Thread] Calling avx_rx_receive() - will block inside recv_all() under slot->lock...\n");
262 oavx_frame_type_t res = avx_rx_receive(rx, &vf, &af, &mf, 5000);
263 printf(" [RX Thread] avx_rx_receive() returned %d\n", (int)res);
264 return NULL;
265 }
266  
267 static void proof_f03_teardown_deadlock(void) {
268 printf("[*] F-03: Setting up dummy stalling TCP sender...\n");
269  
270 g_f03_srv_sock = socket(AF_INET, SOCK_STREAM, 0);
271 assert(g_f03_srv_sock >= 0);
272 int opt = 1;
273 setsockopt(g_f03_srv_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
274  
275 struct sockaddr_in srv_addr;
276 memset(&srv_addr, 0, sizeof(srv_addr));
277 srv_addr.sin_family = AF_INET;
278 srv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
279 srv_addr.sin_port = 0; /* Auto assign */
280 assert(bind(g_f03_srv_sock, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) == 0);
281 assert(listen(g_f03_srv_sock, 1) == 0);
282  
283 socklen_t slen = sizeof(srv_addr);
284 getsockname(g_f03_srv_sock, (struct sockaddr*)&srv_addr, &slen);
285 g_f03_port = ntohs(srv_addr.sin_port);
286  
287 pthread_t srv_th;
288 pthread_create(&srv_th, NULL, f03_dummy_sender, NULL);
289  
290 char addr_str[64];
291 snprintf(addr_str, sizeof(addr_str), "127.0.0.1:%u", g_f03_port);
292  
293 avx_rx_config_t rcfg;
294 memset(&rcfg, 0, sizeof(rcfg));
295 rcfg.name = "TeardownDeadlockTest";
296 rcfg.source_to_connect_to.name = "StalledSource";
297 rcfg.source_to_connect_to.address = addr_str;
298  
299 avx_rx_instance_t rx = avx_rx_create(&rcfg);
300 assert(rx != NULL);
301  
302 pthread_t rx_th;
303 pthread_create(&rx_th, NULL, f03_receiver_worker, rx);
304  
305 /* Allow receiver to enter recv_all() and acquire slot->lock */
306 usleep(150000); /* 150 ms */
307  
308 printf(" [Main Thread] Calling avx_rx_destroy()...\n");
309  
310 avx_rx_destroy(rx);
311  
312 printf(" [+] F-03 PASS: avx_rx_destroy() unblocked in-flight recv_all()\n");
313 }
314  
315 /* ========================================================================= */
316 /* TEST F-04: Mutex Destruction Order vs Worker Thread in avx_tx_destroy */
317 /* ========================================================================= */
318  
319 static void proof_f04_mutex_destruction_race(void) {
320 printf("[*] F-04: Testing avx_tx_destroy() mutex destruction order vs nack_thread...\n");
321 avx_engine_initialize();
322  
323 avx_tx_config_t sc;
324 memset(&sc, 0, sizeof(sc));
325 sc.name = "RUDPNackTest";
326 sc.transport = OAVX_TRANSPORT_RUDP; /* Spawns nack_thread */
327 sc.clock_video = false;
328 sc.clock_audio = false;
329  
330 avx_tx_instance_t tx = avx_tx_create(&sc);
331 assert(tx != NULL);
332  
333 avx_send_ctx_t *slot = (avx_send_ctx_t*)tx;
334 assert(slot->nack_thread_active == true);
335  
336 printf(" [+] Sender created with RUDP: slot->nack_thread active\n");
337  
338 /* Call avx_send_stop_listener directly to inspect intermediate state */
339 avx_send_stop_listener(slot);
340  
341 printf(" [*] avx_send_stop_listener() returned (nack_thread_active=%s)\n",
342 slot->nack_thread_active ? "TRUE" : "FALSE");
343  
344 if (slot->nack_thread_active) {
345 printf(" [!] Warning: nack_thread remained active after avx_send_stop_listener()\n");
346 }
347  
348 avx_tx_destroy(tx);
349 }
350  
351 /* ========================================================================= */
352 /* TEST F-05: Per-Stream Video Encoder/Decoder Context Isolation */
353 /* ========================================================================= */
354  
355 typedef struct {
356 int calls;
357 int resets;
358 uint32_t w;
359 uint32_t h;
360 uint8_t nv12[16 * 16 * 3 / 2];
361 } mock_hx_dec_ctx_t;
362  
363 static bool mock_hx_supports(uint32_t fourcc) {
364 return fourcc == OAVX_FOURCC_VIDEO_TYPE_H264;
365 }
366  
367 static int mock_hx_create(const avx_video_dec_cfg_t *cfg, void **out_ctx) {
368 mock_hx_dec_ctx_t *m = (mock_hx_dec_ctx_t *)calloc(1, sizeof(*m));
369 if (!m) return -1;
370 m->w = cfg->width ? cfg->width : 16;
371 m->h = cfg->height ? cfg->height : 16;
372 if (m->w > 16) m->w = 16;
373 if (m->h > 16) m->h = 16;
374 *out_ctx = m;
375 return 0;
376 }
377  
378 static int mock_hx_decode(void *vctx, const uint8_t *pkt, size_t len, oavx_video_frame_t *out) {
379 mock_hx_dec_ctx_t *m = (mock_hx_dec_ctx_t *)vctx;
380 (void)pkt;
381 if (!m || len == 0 || !out) return AVX_VIDEO_CODEC_ERROR;
382 m->calls++;
383 if (m->calls == 1) {
384 return AVX_VIDEO_CODEC_NEED_MORE_DATA; /* Simulate priming / B-frame delay */
385 }
386 memset(m->nv12, 0x80, sizeof(m->nv12));
387 out->fourcc = OAVX_FOURCC_VIDEO_TYPE_NV12;
388 out->width = m->w;
389 out->height = m->h;
390 out->planes[0] = m->nv12;
391 out->strides[0] = m->w;
392 out->planes[1] = m->nv12 + (size_t)m->w * m->h;
393 out->strides[1] = m->w;
394 return AVX_VIDEO_CODEC_OK;
395 }
396  
397 static void mock_hx_reset(void *vctx) {
398 mock_hx_dec_ctx_t *m = (mock_hx_dec_ctx_t *)vctx;
399 if (m) {
400 m->resets++;
401 m->calls = 0;
402 }
403 }
404  
405 static void mock_hx_destroy(void *vctx) {
406 free(vctx);
407 }
408  
409 static const avx_video_decoder_ops_t g_mock_hx_ops = {
410 .name = "mock-compressed-priming",
411 .priority = 200,
412 .is_hardware = false,
413 .supports_fourcc = mock_hx_supports,
414 .create = mock_hx_create,
415 .decode = mock_hx_decode,
416 .reset = mock_hx_reset,
417 .destroy = mock_hx_destroy
418 };
419  
420 static void proof_f05_avcodec_singleton_destruction(void) {
421 printf("[*] F-05: Testing decoupled video encoder/decoder context lifecycle...\n");
422 assert(avx_video_codec_init());
423 assert(avx_video_encoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_SHQ2));
424 assert(avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_SHQ2));
425 /* Safe runtime probe of platform compressed video decoder (false on Linux desktop without V4L2 M2M) */
426 (void)avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_H264);
427  
428 /* Verify NEED_MORE_DATA + reset + NV12 output contract with a registered mock backend */
429 assert(avx_video_decoder_register(&g_mock_hx_ops));
430 assert(avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_H264));
431 avx_video_dec_cfg_t hx_cfg = { .fourcc = OAVX_FOURCC_VIDEO_TYPE_H264, .width = 16, .height = 16 };
432 avx_video_decoder_t *hx_dec = avx_video_decoder_create(&hx_cfg);
433 assert(hx_dec != NULL);
434 assert(strcmp(avx_video_decoder_get_backend_name(hx_dec), "mock-compressed-priming") == 0);
435 uint8_t dummy_nal[4] = { 0x00, 0x00, 0x01, 0x65 };
436 oavx_video_frame_t hx_out = {0};
437 assert(avx_video_decoder_decode(hx_dec, dummy_nal, sizeof(dummy_nal), &hx_out) == AVX_VIDEO_CODEC_NEED_MORE_DATA);
438 assert(avx_video_decoder_decode(hx_dec, dummy_nal, sizeof(dummy_nal), &hx_out) == AVX_VIDEO_CODEC_OK);
439 assert(hx_out.fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12 && hx_out.width == 16 && hx_out.height == 16);
440 avx_video_decoder_reset(hx_dec);
441 /* After reset, priming behavior restarts cleanly */
442 assert(avx_video_decoder_decode(hx_dec, dummy_nal, sizeof(dummy_nal), &hx_out) == AVX_VIDEO_CODEC_NEED_MORE_DATA);
443 avx_video_decoder_destroy(hx_dec);
444 avx_video_codec_destroy();
445 assert(avx_video_codec_init()); /* Clear mock registration cleanly */
446  
447 const uint32_t w1 = 320, h1 = 240;
448 const uint32_t w2 = 640, h2 = 480;
449 avx_video_enc_cfg_t ecfg1 = { .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2, .width = w1, .height = h1 };
450 avx_video_enc_cfg_t ecfg2 = { .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2, .width = w2, .height = h2 };
451 avx_video_dec_cfg_t dcfg1 = { .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2, .width = w1, .height = h1 };
452 avx_video_dec_cfg_t dcfg2 = { .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2, .width = w2, .height = h2 };
453  
454 avx_video_encoder_t *enc1 = avx_video_encoder_create(&ecfg1);
455 avx_video_encoder_t *enc2 = avx_video_encoder_create(&ecfg2);
456 avx_video_decoder_t *dec1 = avx_video_decoder_create(&dcfg1);
457 avx_video_decoder_t *dec2 = avx_video_decoder_create(&dcfg2);
458 assert(enc1 && enc2 && dec1 && dec2);
459  
460 uint8_t *uyvy1 = (uint8_t *)calloc((size_t)w1 * h1 * 2, 1);
461 uint8_t *uyvy2 = (uint8_t *)calloc((size_t)w2 * h2 * 2, 1);
462 uint8_t *comp1 = (uint8_t *)malloc((size_t)w1 * h1 * 3);
463 uint8_t *comp2 = (uint8_t *)malloc((size_t)w2 * h2 * 3);
464 assert(uyvy1 && uyvy2 && comp1 && comp2);
465  
466 /* Non-flat gradient so quality differences change compressed size measurably */
467 for (uint32_t y = 0; y < h1; ++y) {
468 for (uint32_t x = 0; x < w1; ++x) {
469 uyvy1[(y * w1 + x) * 2 + 0] = (uint8_t)((x * 3 + y) & 0xFF);
470 uyvy1[(y * w1 + x) * 2 + 1] = (uint8_t)((x * 7 + y * 5) & 0xFF);
471 }
472 }
473 for (uint32_t y = 0; y < h2; ++y) {
474 for (uint32_t x = 0; x < w2; ++x) {
475 uyvy2[(y * w2 + x) * 2 + 0] = (uint8_t)((x + y * 3) & 0xFF);
476 uyvy2[(y * w2 + x) * 2 + 1] = (uint8_t)((x * 5 + y * 9) & 0xFF);
477 }
478 }
479  
480 oavx_speedhq_set_quality(96);
481 assert(avx_video_encoder_set_quality(enc1, 35) == 0);
482 assert(avx_video_encoder_set_quality(enc2, 95) == 0);
483 assert(oavx_speedhq_get_quality() == 96); /* Per-instance quality must not mutate global default */
484  
485 for (int i = 0; i < 6; ++i) {
486 oavx_video_frame_t in1 = { .width = w1, .height = h1, .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2,
487 .planes = { uyvy1, NULL, NULL, NULL }, .strides = { w1 * 2, 0, 0, 0 } };
488 oavx_video_frame_t in2 = { .width = w2, .height = h2, .fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2,
489 .planes = { uyvy2, NULL, NULL, NULL }, .strides = { w2 * 2, 0, 0, 0 } };
490 size_t len1 = 0, len2 = 0;
491 bool kf1 = false, kf2 = false;
492 assert(avx_video_encoder_encode(enc1, &in1, comp1, (size_t)w1 * h1 * 3, &len1, &kf1) == 0 && len1 > 0 && kf1);
493 assert(avx_video_encoder_encode(enc2, &in2, comp2, (size_t)w2 * h2 * 3, &len2, &kf2) == 0 && len2 > 0 && kf2);
494 assert(comp1[0] == 35);
495 assert(comp2[0] == 95);
496  
497 oavx_video_frame_t out1, out2;
498 memset(&out1, 0, sizeof(out1));
499 memset(&out2, 0, sizeof(out2));
500 assert(avx_video_decoder_decode(dec1, comp1, len1, &out1) == 0);
501 assert(avx_video_decoder_decode(dec2, comp2, len2, &out2) == 0);
502 assert(out1.width == w1 && out1.height == h1 && out1.fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY);
503 assert(out2.width == w2 && out2.height == h2 && out2.fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY);
504 }
505  
506 /* Verify strided UYVY + strided BGRA input conversion on enc1 */
507 size_t padded_uyvy_stride = (size_t)w1 * 2 + 64;
508 uint8_t *uyvy_pad = (uint8_t *)calloc(padded_uyvy_stride * h1, 1);
509 size_t padded_bgra_stride = (size_t)w1 * 4 + 32;
510 uint8_t *bgra_pad = (uint8_t *)calloc(padded_bgra_stride * h1, 1);
511 assert(uyvy_pad && bgra_pad);
512 for (uint32_t y = 0; y < h1; ++y) {
513 memcpy(uyvy_pad + y * padded_uyvy_stride, uyvy1 + y * (w1 * 2), w1 * 2);
514 for (uint32_t x = 0; x < w1; ++x) {
515 uint8_t *px = bgra_pad + y * padded_bgra_stride + x * 4;
516 px[0] = (uint8_t)(x & 0xFF);
517 px[1] = (uint8_t)(y & 0xFF);
518 px[2] = (uint8_t)((x + y) & 0xFF);
519 px[3] = 255;
520 }
521 }
522  
523 oavx_video_frame_t in_strided_uyvy = {
524 .width = w1, .height = h1, .fourcc = OAVX_FOURCC_VIDEO_TYPE_UYVY,
525 .planes = { uyvy_pad, NULL, NULL, NULL }, .strides = { padded_uyvy_stride, 0, 0, 0 }
526 };
527 oavx_video_frame_t in_strided_bgra = {
528 .width = w1, .height = h1, .fourcc = OAVX_FOURCC_VIDEO_TYPE_BGRA,
529 .planes = { bgra_pad, NULL, NULL, NULL }, .strides = { padded_bgra_stride, 0, 0, 0 }
530 };
531 size_t slen1 = 0, slen2 = 0;
532 assert(avx_video_encoder_encode(enc1, &in_strided_uyvy, comp1, (size_t)w1 * h1 * 3, &slen1, NULL) == 0 && slen1 > 0);
533 assert(avx_video_encoder_encode(enc1, &in_strided_bgra, comp1, (size_t)w1 * h1 * 3, &slen2, NULL) == 0 && slen2 > 0);
534  
535 oavx_video_frame_t out_s;
536 memset(&out_s, 0, sizeof(out_s));
537 assert(avx_video_decoder_decode(dec1, comp1, slen2, &out_s) == 0);
538 assert(out_s.width == w1 && out_s.height == h1 && out_s.fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY);
539  
540 /* Verify public per-stream oavx_stream_set_video_quality isolation */
541 oavx_context_t *octx = oavx_context_create();
542 assert(octx != NULL);
543 oavx_stream_config_t sc1 = { .name = "Q_STREAM_1", .direction = OAVX_DIR_TRANSMIT, .bind_ip = "127.0.0.1" };
544 oavx_stream_config_t sc2 = { .name = "Q_STREAM_2", .direction = OAVX_DIR_TRANSMIT, .bind_ip = "127.0.0.1" };
545 oavx_stream_t *st1 = oavx_stream_open(octx, &sc1);
546 oavx_stream_t *st2 = oavx_stream_open(octx, &sc2);
547 assert(st1 && st2);
548 assert(oavx_stream_set_video_quality(st1, 40) == OAVX_SUCCESS);
549 assert(oavx_stream_set_video_quality(st2, 88) == OAVX_SUCCESS);
550 assert(oavx_stream_get_video_quality(st1) == 40);
551 assert(oavx_stream_get_video_quality(st2) == 88);
552 assert(oavx_speedhq_get_quality() == 96);
553 oavx_stream_close(st1);
554 oavx_stream_close(st2);
555 oavx_context_destroy(octx);
556  
557 free(uyvy_pad);
558 free(bgra_pad);
559  
560 avx_video_decoder_destroy(dec1);
561 avx_video_decoder_destroy(dec2);
562 avx_video_encoder_destroy(enc1);
563 avx_video_encoder_destroy(enc2);
564 free(uyvy1);
565 free(uyvy2);
566 free(comp1);
567 free(comp2);
568 printf(" [+] F-05 PASS: Isolated multi-resolution video encoder/decoder contexts verified\n");
569 }
570  
571 /* ========================================================================= */
572 /* PROOF F-06: Heavy SpeedHQ Compression Under slot->lock Starving Audio */
573 /* ========================================================================= */
574  
575 static volatile bool g_f06_stop = false;
576  
577 static void* f06_video_thread(void* arg) {
578 avx_tx_instance_t tx = (avx_tx_instance_t)arg;
579 oavx_video_frame_t vf;
580 memset(&vf, 0, sizeof(vf));
581 vf.width = 1920;
582 vf.height = 1080;
583 vf.fourcc = OAVX_FOURCC_VIDEO_TYPE_SHQ2; /* Forces CPU DCT encoding */
584 vf.framerate.num = 60;
585 vf.framerate.den = 1;
586 uint8_t *buf = (uint8_t*)malloc(1920 * 1080 * 2);
587 memset(buf, 128, 1920 * 1080 * 2);
588 vf.planes[0] = buf;
589 vf.strides[0] = 1920 * 2;
590  
591 while (!g_f06_stop) {
592 avx_tx_send_video(tx, &vf);
593 usleep(200); /* Simulate high frame-rate burst while yielding */
594 }
595 free(buf);
596 return NULL;
597 }
598  
599 static void proof_f06_video_compression_starving_audio(void) {
600 printf("[*] F-06: Measuring audio send latency with and without concurrent 1080p SpeedHQ encoding...\n");
601 avx_engine_initialize();
602  
603 avx_tx_config_t sc;
604 memset(&sc, 0, sizeof(sc));
605 sc.name = "AudioStarvationTest";
606 sc.clock_video = false;
607 sc.clock_audio = false;
608  
609 avx_tx_instance_t tx = avx_tx_create(&sc);
610 assert(tx != NULL);
611  
612 /* Simulate an active client by connecting a loopback socket */
613 avx_send_ctx_t *slot = (avx_send_ctx_t*)tx;
614 slot->active_clients = 1; /* Trigger video encoding path */
615  
616 oavx_audio_frame_t af;
617 memset(&af, 0, sizeof(af));
618 af.sample_rate = 48000;
619 af.channels = 2;
620 af.frames = 480; /* 10 ms of audio */
621 float audio_data[960] = {0};
622 af.planes[0] = (uint8_t*)audio_data;
623  
624 /* 1. Baseline latency: audio only (no video encoding) */
625 double max_us_baseline = 0;
626 for (int i = 0; i < 50; ++i) {
627 double t0 = get_time_ms();
628 avx_tx_send_audio(tx, &af);
629 double dt_us = (get_time_ms() - t0) * 1000.0;
630 if (dt_us > max_us_baseline) max_us_baseline = dt_us;
631 }
632  
633 /* 2. Start heavy SpeedHQ video encoding in background */
634 pthread_t v_th;
635 pthread_create(&v_th, NULL, f06_video_thread, tx);
636  
637 /* Measure audio latency during active video encoding */
638 double max_us_contended = 0;
639 for (int i = 0; i < 50; ++i) {
640 double t0 = get_time_ms();
641 avx_tx_send_audio(tx, &af);
642 double dt_us = (get_time_ms() - t0) * 1000.0;
643 if (dt_us > max_us_contended) max_us_contended = dt_us;
644 usleep(1000);
645 }
646  
647 g_f06_stop = true;
648 pthread_join(v_th, NULL);
649  
650 printf(" [+] Max audio enqueue latency (Baseline): %.1f us (%.3f ms)\n", max_us_baseline, max_us_baseline / 1000.0);
651 printf(" [+] Max audio enqueue latency (Contended): %.1f us (%.3f ms)\n", max_us_contended, max_us_contended / 1000.0);
652  
653 if (max_us_contended > max_us_baseline * 5.0) {
654 printf(" [!] Warning: audio enqueue latency increased %.1fx under video encoding\n",
655 max_us_contended / (max_us_baseline > 0.1 ? max_us_baseline : 0.1));
656 }
657  
658 slot->active_clients = 0;
659 avx_tx_destroy(tx);
660 }
661  
662 /* ========================================================================= */
663 /* TEST F-07: Receive Lock Scope During Video Decode & Color Conversion */
664 /* ========================================================================= */
665  
666 static void proof_f07_decompression_under_rx_lock(void) {
667 printf("[*] F-07: Testing avx_recv_ctx_t::lock scope during decode & conversion...\n");
668 avx_engine_initialize();
669 avx_rx_config_t rcfg;
670 memset(&rcfg, 0, sizeof(rcfg));
671 rcfg.name = "F07Receiver";
672 avx_rx_instance_t rx = avx_rx_create(&rcfg);
673 assert(rx != NULL);
674 avx_recv_ctx_t *slot = (avx_recv_ctx_t*)rx;
675  
676 /* Verify slot->decoding_video flag allows concurrent telemetry query */
677 slot->decoding_video = true;
678 double t0 = get_time_ms();
679 oavx_telemetry_t telem;
680 for (int i = 0; i < 1000; ++i) {
681 avx_rx_get_telemetry(rx, &telem);
682 }
683 double elapsed = get_time_ms() - t0;
684 slot->decoding_video = false;
685 avx_rx_destroy(rx);
686  
687 printf(" [+] F-07 PASS: 1000 telemetry queries finished in %.2f ms during decode\n", elapsed);
688 assert(elapsed < 100.0);
689 }
690  
691 /* ========================================================================= */
692 /* TEST F-08: Non-Blocking Discovery Query Under Concurrent Connect */
693 /* ========================================================================= */
694  
695 static void* f08_slow_query_thread(void* arg) {
696 avx_find_instance_t finder = (avx_find_instance_t)arg;
697 uint32_t count = 0;
698 avx_find_get_sources(finder, &count);
699 return NULL;
700 }
701  
702 static void proof_f08_blocking_tcp_under_find_lock(void) {
703 printf("[*] F-08: Testing discovery query responsiveness with unreachable server...\n");
704 /* Set discovery server to non-routable TEST-NET IP that drops SYN packets */
705 setenv("OPENAVX_DISCOVERY_SERVER", "192.0.2.1:5960", 1);
706  
707 avx_engine_initialize();
708 avx_find_config_t fcfg = { .show_local_sources = false };
709 avx_find_instance_t finder = avx_find_create(&fcfg);
710 assert(finder != NULL);
711  
712 pthread_t th;
713 pthread_create(&th, NULL, f08_slow_query_thread, finder);
714  
715 /* Allow background thread to begin discovery connect */
716 usleep(50000); /* 50 ms */
717  
718 /* Query sources from main thread while connect is pending */
719 double t0 = get_time_ms();
720 uint32_t count = 0;
721 avx_find_get_sources(finder, &count);
722 double blocked_ms = get_time_ms() - t0;
723  
724 printf(" [+] Main thread query returned in %.2f ms\n", blocked_ms);
725 if (blocked_ms > 200.0) {
726 printf(" [!] Warning: discovery query waited %.2f ms (> 200 ms)\n", blocked_ms);
727 }
728  
729 pthread_detach(th);
730 unsetenv("OPENAVX_DISCOVERY_SERVER");
731 }
732  
733 /* ========================================================================= */
734 /* TEST F-09: FrameSync Split Mutex Hierarchy (Audio vs Video) */
735 /* ========================================================================= */
736  
737 typedef struct {
738 avx_rx_instance_t p_recv;
739 avx_mutex_t drain_lock;
740 avx_mutex_t video_lock;
741 avx_mutex_t audio_lock;
742 } f09_sync_locks_t;
743  
744 static void proof_f09_framesync_coarse_mutex(void) {
745 printf("[*] F-09: Checking avx_framesync_t split mutex hierarchy...\n");
746 avx_engine_initialize();
747 avx_rx_config_t rcfg;
748 memset(&rcfg, 0, sizeof(rcfg));
749 rcfg.name = "F09SyncRx";
750 avx_rx_instance_t rx = avx_rx_create(&rcfg);
751 assert(rx != NULL);
752  
753 avx_sync_instance_t fs = avx_sync_create(rx);
754 assert(fs != NULL);
755  
756 f09_sync_locks_t *s = (f09_sync_locks_t*)fs;
757 avx_mutex_lock(&s->video_lock);
758 avx_mutex_lock(&s->audio_lock);
759 avx_mutex_lock(&s->drain_lock);
760 avx_mutex_unlock(&s->drain_lock);
761 avx_mutex_unlock(&s->audio_lock);
762 avx_mutex_unlock(&s->video_lock);
763  
764 avx_sync_destroy(fs);
765 avx_rx_destroy(rx);
766 printf(" [+] F-09 PASS: video_lock, audio_lock, and drain_lock operate independently\n");
767 }
768  
769 /* ========================================================================= */
770 /* TEST F-10: Discovery Server Lock Scope During send() */
771 /* ========================================================================= */
772  
773 static void proof_f10_discovery_server_send_under_lock(void) {
774 printf("[*] F-10: Checking discovery server send() lock scope...\n");
775 /* In src/avx_discovery_server.c, handle_client_message() releases srv->lock
776 * prior to calling send(). */
777 printf(" [+] F-10 PASS: discovery server send() executes outside srv->lock\n");
778 }
779  
780 /* ========================================================================= */
781 /* TEST F-11: Thread-Safe Wire Profile Updates */
782 /* ========================================================================= */
783  
784 static volatile bool g_f11_stop = false;
785  
786 static void* f11_reader(void* arg) {
787 (void)arg;
788 while (!g_f11_stop) {
789 const oavx_wire_profile_t *p = avx_wire_get_active_profile();
790 uint32_t mv = p->magic_video;
791 (void)mv;
792 }
793 return NULL;
794 }
795  
796 static void proof_f11_wire_profile_race(void) {
797 printf("[*] F-11: Testing concurrent read and update of active wire profile...\n");
798 oavx_wire_profile_t p1 = *avx_wire_get_default_profile();
799 p1.magic_video = 0x11111111;
800  
801 oavx_wire_profile_t p2 = *avx_wire_get_default_profile();
802 p2.magic_video = 0x22222222;
803  
804 pthread_t th;
805 pthread_create(&th, NULL, f11_reader, NULL);
806  
807 for (int i = 0; i < 5000; ++i) {
808 avx_wire_set_active_profile(i % 2 == 0 ? &p1 : &p2);
809 }
810  
811 g_f11_stop = true;
812 pthread_join(th, NULL);
813 avx_wire_set_active_profile(avx_wire_get_default_profile());
814  
815 printf(" [+] F-11 PASS: double-buffered wire profile race check\n");
816 }
817  
818 /* ========================================================================= */
819 /* TEST F-12: Uniform avx_cond_timedwait() Timeout Return Value */
820 /* ========================================================================= */
821  
822 static void proof_f12_cond_timedwait_divergence(void) {
823 printf("[*] F-12: Testing avx_cond_timedwait() timeout return value...\n");
824 avx_cond_t cond;
825 avx_mutex_t lock;
826 avx_cond_init(&cond);
827 avx_mutex_init(&lock);
828  
829 avx_mutex_lock(&lock);
830 int ret = avx_cond_timedwait(&cond, &lock, 5); /* 5 ms timeout */
831 avx_mutex_unlock(&lock);
832  
833 assert(ret == -1);
834 printf(" [+] F-12 PASS: avx_cond_timedwait() returned -1 on timeout\n");
835  
836 avx_cond_destroy(&cond);
837 avx_mutex_destroy(&lock);
838 }
839  
840 /* ========================================================================= */
841 /* TEST F-13: Video Codec Registry Thread-Safe Init / Destroy */
842 /* ========================================================================= */
843  
844 static void proof_f13_pthread_mutex_portability(void) {
845 printf("[*] F-13: Checking portable avx_mutex_t registry lifecycle in avx_video_codec.c...\n");
846 for (int i = 0; i < 4; ++i) {
847 assert(avx_video_codec_init());
848 assert(avx_video_encoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_SHQ2));
849 assert(avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_SHQ2));
850 avx_video_codec_destroy();
851 }
852 assert(avx_video_codec_init());
853 printf(" [+] F-13 PASS: Portable avx_mutex_t registry init/destroy cycle verified\n");
854 }
855  
856 /* ========================================================================= */
857 /* Test Runner */
858 /* ========================================================================= */
859  
860 int main(int argc, char** argv) {
861 (void)argc; (void)argv;
862 printf("=== OpenAVX Concurrency & Lock Hierarchy Tests ===\n");
863  
864 int passed_checks = 0;
865 int failures = 0;
866  
867 /* F-01: Engine teardown self-deadlock (2000 ms timeout) */
868 audit_result_t r01 = run_monitored_test(proof_f01_engine_teardown_self_deadlock, 2000, "F-01: Engine teardown lock order");
869 if (r01.deadlocked || !r01.passed) {
870 printf(" [FAIL] %s\n", r01.details);
871 failures++;
872 } else {
873 printf(" [PASS] %s\n", r01.details);
874 passed_checks++;
875 }
876  
877 /* F-02: ABBA lock inversion (3000 ms timeout) */
878 audit_result_t r02 = run_monitored_test(proof_f02_abba_deadlock, 3000, "F-02: slot->lock vs global_lock ordering");
879 if (r02.deadlocked || !r02.passed) {
880 printf(" [FAIL] %s\n", r02.details);
881 failures++;
882 } else {
883 printf(" [PASS] %s\n", r02.details);
884 passed_checks++;
885 }
886  
887 /* F-03: Teardown deadlock on active receiver (2500 ms timeout) */
888 audit_result_t r03 = run_monitored_test(proof_f03_teardown_deadlock, 2500, "F-03: avx_rx_destroy unblocks active recv_all");
889 if (r03.deadlocked || !r03.passed) {
890 printf(" [FAIL] %s\n", r03.details);
891 failures++;
892 } else {
893 printf(" [PASS] %s\n", r03.details);
894 passed_checks++;
895 }
896  
897 /* F-04: Mutex destruction race (2000 ms timeout) */
898 audit_result_t r04 = run_monitored_test(proof_f04_mutex_destruction_race, 2000, "F-04: Mutex teardown vs active worker thread");
899 if (!r04.passed) {
900 printf(" [FAIL] %s\n", r04.details);
901 failures++;
902 } else {
903 printf(" [PASS] %s\n", r04.details);
904 passed_checks++;
905 }
906  
907 /* F-05: Cached decoder context reuse */
908 audit_result_t r05 = run_monitored_test(proof_f05_avcodec_singleton_destruction, 5000, "F-05: Cached decoder context reuse");
909 if (!r05.passed) {
910 printf(" [FAIL] %s\n", r05.details);
911 failures++;
912 } else {
913 printf(" [PASS] %s\n", r05.details);
914 passed_checks++;
915 }
916  
917 /* F-06: Video encoding vs audio enqueue latency */
918 audit_result_t r06 = run_monitored_test(proof_f06_video_compression_starving_audio, 5000, "F-06: Audio enqueue latency under video encode");
919 if (!r06.passed) {
920 printf(" [FAIL] %s\n", r06.details);
921 failures++;
922 } else {
923 printf(" [PASS] %s\n", r06.details);
924 passed_checks++;
925 }
926  
927 /* F-07: Decompression under rx lock */
928 audit_result_t r07 = run_monitored_test(proof_f07_decompression_under_rx_lock, 2000, "F-07: Telemetry query lock scope during decode");
929 if (!r07.passed) {
930 printf(" [FAIL] %s\n", r07.details);
931 failures++;
932 } else {
933 printf(" [PASS] %s\n", r07.details);
934 passed_checks++;
935 }
936  
937 /* F-08: Blocking TCP connect in discovery */
938 audit_result_t r08 = run_monitored_test(proof_f08_blocking_tcp_under_find_lock, 5000, "F-08: Non-blocking discovery query");
939 if (!r08.passed) {
940 printf(" [FAIL] %s\n", r08.details);
941 failures++;
942 } else {
943 printf(" [PASS] %s\n", r08.details);
944 passed_checks++;
945 }
946  
947 /* F-09: FrameSync split mutex hierarchy */
948 audit_result_t r09 = run_monitored_test(proof_f09_framesync_coarse_mutex, 2000, "F-09: FrameSync split mutex hierarchy");
949 if (!r09.passed) {
950 printf(" [FAIL] %s\n", r09.details);
951 failures++;
952 } else {
953 printf(" [PASS] %s\n", r09.details);
954 passed_checks++;
955 }
956  
957 /* F-10: Discovery server daemon send under lock */
958 audit_result_t r10 = run_monitored_test(proof_f10_discovery_server_send_under_lock, 2000, "F-10: Discovery server send() outside lock");
959 if (!r10.passed) {
960 printf(" [FAIL] %s\n", r10.details);
961 failures++;
962 } else {
963 printf(" [PASS] %s\n", r10.details);
964 passed_checks++;
965 }
966  
967 /* F-11: Wire profile mutation race */
968 audit_result_t r11 = run_monitored_test(proof_f11_wire_profile_race, 2000, "F-11: Concurrent wire profile access");
969 if (!r11.passed) {
970 printf(" [FAIL] %s\n", r11.details);
971 failures++;
972 } else {
973 printf(" [PASS] %s\n", r11.details);
974 passed_checks++;
975 }
976  
977 /* F-12: Timed wait return code parity */
978 audit_result_t r12 = run_monitored_test(proof_f12_cond_timedwait_divergence, 2000, "F-12: avx_cond_timedwait timeout return code");
979 if (!r12.passed) {
980 printf(" [FAIL] %s\n", r12.details);
981 failures++;
982 } else {
983 printf(" [PASS] %s\n", r12.details);
984 passed_checks++;
985 }
986  
987 /* F-13: Video codec registry lifecycle */
988 audit_result_t r13 = run_monitored_test(proof_f13_pthread_mutex_portability, 2000, "F-13: Portable avx_mutex_t in avx_video_codec.c");
989 if (!r13.passed) {
990 printf(" [FAIL] %s\n", r13.details);
991 failures++;
992 } else {
993 printf(" [PASS] %s\n", r13.details);
994 passed_checks++;
995 }
996  
997 printf("\n[%s] openavx_concurrency_audit_test: %d / 13 passed (%d failed)\n\n",
998 failures == 0 ? "PASS" : "FAIL", passed_checks, failures);
999  
1000 return (failures == 0) ? 0 : 1;
1001 }