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 * src/avx_recv.c - Stream receiver, session handling, and frame decoding
7 */
8  
9 #include "avx_internal.h"
10 #include "avx_audio.h"
11 #include "avx_speedhq.h"
12 #include "avx_video_codec.h"
13 #include "avx_rtsp.h"
14 #include "avx_color.h"
15 #include "avx_wire.h"
16 #include <stdlib.h>
17 #include <string.h>
18 #include <stdio.h>
19 #include <time.h>
20 #include <math.h>
21  
22 static ssize_t recv_all(avx_socket_t fd, void* buf, size_t len) {
23 size_t total = 0;
24 char* p = (char*)buf;
25 while (total < len) {
26 ssize_t r = recv(fd, p + total, (int)(len - total), 0);
27 if (r <= 0) return r;
28 total += (size_t)r;
29 }
30 return (ssize_t)total;
31 }
32  
33 static bool avx_parse_url_host_port(const char* url, uint16_t default_port, char* host_out, size_t host_out_size, uint16_t* port_out) {
34 if (!url || url[0] == '\0' || !host_out || host_out_size == 0) return false;
35 uint16_t port = default_port;
36  
37 /* Strip scheme if present (e.g. openavx://, oavx://, http://) */
38 const char *scheme_sep = strstr(url, "://");
39 if (scheme_sep) {
40 url = scheme_sep + 3;
41 }
42  
43 /* Check for RFC 3986 Bracketed IPv6: "[2001:db8::1]:7960" or "[::1]:7960" */
44 if (url[0] == '[') {
45 const char* close_bracket = strchr(url, ']');
46 if (close_bracket) {
47 int hlen = (int)(close_bracket - (url + 1));
48 if (hlen > (int)(host_out_size - 1)) hlen = (int)(host_out_size - 1);
49 snprintf(host_out, host_out_size, "%.*s", hlen, url + 1);
50  
51 if (*(close_bracket + 1) == ':') {
52 port = (uint16_t)atoi(close_bracket + 2);
53 }
54 } else {
55 snprintf(host_out, host_out_size, "%.*s", (int)(host_out_size - 1), url);
56 }
57 } else {
58 /* Check if there is a path or query string */
59 const char *slash = strchr(url, '/');
60 const char *colon = strchr(url, ':');
61  
62 if (colon && (!slash || colon < slash)) {
63 int host_len = (int)(colon - url);
64 if (host_len > (int)(host_out_size - 1)) host_len = (int)(host_out_size - 1);
65 snprintf(host_out, host_out_size, "%.*s", host_len, url);
66 port = (uint16_t)atoi(colon + 1);
67 } else if (slash) {
68 int host_len = (int)(slash - url);
69 if (host_len > (int)(host_out_size - 1)) host_len = (int)(host_out_size - 1);
70 snprintf(host_out, host_out_size, "%.*s", host_len, url);
71 } else {
72 snprintf(host_out, host_out_size, "%.*s", (int)(host_out_size - 1), url);
73 }
74 }
75  
76 if (port_out) *port_out = port;
77 return true;
78 }
79  
80 static void avx_rx_parse_failover_metadata(avx_recv_ctx_t* slot, const char* xml) {
81 if (!slot || !xml) return;
82 const char* tag = strstr(xml, "openavx_failover");
83 if (!tag) tag = strstr(xml, "oavx_failover");
84 if (!tag) tag = strstr(xml, "failover");
85 if (!tag) return;
86  
87 /* Extract name */
88 char name_buf[256] = {0};
89 const char* p_name = strstr(tag, "name=\"");
90 if (p_name) {
91 p_name += 6;
92 const char* end = strchr(p_name, '\"');
93 if (end) {
94 size_t len = (size_t)(end - p_name);
95 if (len >= sizeof(name_buf)) len = sizeof(name_buf) - 1;
96 strncpy(name_buf, p_name, len);
97 name_buf[len] = '\0';
98 }
99 }
100  
101 /* Extract address or url */
102 char addr_buf[256] = {0};
103 const char* p_addr = strstr(tag, "address=\"");
104 if (!p_addr) p_addr = strstr(tag, "url=\"");
105 if (p_addr) {
106 p_addr = strchr(p_addr, '\"');
107 if (p_addr) {
108 p_addr++;
109 const char* end = strchr(p_addr, '\"');
110 if (end) {
111 size_t len = (size_t)(end - p_addr);
112 if (len >= sizeof(addr_buf)) len = sizeof(addr_buf) - 1;
113 strncpy(addr_buf, p_addr, len);
114 addr_buf[len] = '\0';
115 }
116 }
117 }
118  
119 if (addr_buf[0] != '\0' || name_buf[0] != '\0') {
120 snprintf(slot->failover_name, sizeof(slot->failover_name), "%s", name_buf);
121 snprintf(slot->failover_url, sizeof(slot->failover_url), "%s", addr_buf);
122 slot->has_failover = true;
123 }
124 }
125  
126 static void avx_rx_parse_tally_metadata_locked(avx_recv_ctx_t* slot, const char* xml) {
127 if (!slot || !xml) return;
128 if (strstr(xml, "tally") != NULL) {
129 const char *prog = strstr(xml, "on_program=\"");
130 const char *prev = strstr(xml, "on_preview=\"");
131 const char *rec = strstr(xml, "on_recording=\"");
132 if (!rec) rec = strstr(xml, "recording=\"");
133 uint8_t flags = OAVX_TALLY_NONE;
134 if (prog && strncmp(prog + 12, "true", 4) == 0) flags |= OAVX_TALLY_PROGRAM;
135 if (prev && strncmp(prev + 12, "true", 4) == 0) flags |= OAVX_TALLY_PREVIEW;
136 if (rec) {
137 const char *val = strchr(rec, '=');
138 if (val && (strncmp(val + 1, "\"true\"", 6) == 0 || strncmp(val + 2, "true", 4) == 0)) {
139 flags |= OAVX_TALLY_RECORDING;
140 }
141 }
142 slot->tally.flags = flags;
143 avx_cond_broadcast(&slot->tally_cond);
144 }
145 }
146  
147 static bool avx_tcp_probe(const char* host, uint16_t port, uint32_t timeout_ms) {
148 if (!host || host[0] == '\0') return false;
149  
150 char clean_host[128];
151 const char* h = host;
152 if (h[0] == '[') {
153 h++;
154 size_t len = strlen(h);
155 if (len > 0 && h[len - 1] == ']') len--;
156 if (len >= sizeof(clean_host)) len = sizeof(clean_host) - 1;
157 strncpy(clean_host, h, len);
158 clean_host[len] = '\0';
159 h = clean_host;
160 }
161 char port_str[16];
162 snprintf(port_str, sizeof(port_str), "%u", port);
163  
164 struct addrinfo hints;
165 memset(&hints, 0, sizeof(hints));
166 hints.ai_family = AF_UNSPEC;
167 hints.ai_socktype = SOCK_STREAM;
168 hints.ai_flags = AI_NUMERICSERV;
169  
170 struct addrinfo *res = NULL;
171 if (getaddrinfo(h, port_str, &hints, &res) != 0 || !res) return false;
172  
173 bool reachable = false;
174 for (struct addrinfo *rp = res; rp != NULL; rp = rp->ai_next) {
175 avx_socket_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
176 if (fd == AVX_INVALID_SOCKET) continue;
177  
178 avx_socket_set_nonblocking(fd, true);
179 int ret = connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen);
180 if (ret == 0) {
181 reachable = true;
182 avx_socket_close(fd);
183 break;
184 }
185 #ifdef _WIN32
186 if (WSAGetLastError() == WSAEWOULDBLOCK)
187 #else
188 if (errno == EINPROGRESS)
189 #endif
190 {
191 avx_pollfd_t pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
192 if (avx_poll(&pfd, 1, (int)timeout_ms) > 0 && (pfd.revents & POLLOUT)) {
193 int err = 0;
194 socklen_t elen = sizeof(err);
195 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&err, &elen) == 0 && err == 0) {
196 reachable = true;
197 }
198 }
199 }
200 avx_socket_close(fd);
201 if (reachable) break;
202 }
203 freeaddrinfo(res);
204 return reachable;
205 }
206  
207 static bool avx_recv_step_connect_locked(avx_recv_ctx_t* slot, uint32_t step_budget_ms);
208 static bool avx_recv_try_connect(avx_recv_ctx_t* slot);
209  
210 static void avx_recv_close_pending_locked(avx_recv_ctx_t* slot) {
211 if (!slot) return;
212 if (slot->pending_conn_fd != AVX_INVALID_SOCKET) {
213 avx_socket_close(slot->pending_conn_fd);
214 slot->pending_conn_fd = AVX_INVALID_SOCKET;
215 }
216 slot->pending_conn_start_ns = 0;
217 }
218  
219 static ssize_t recv_all_timeout(avx_socket_t fd, void* buf, size_t len, uint32_t timeout_ms) {
220 size_t total = 0;
221 char* p = (char*)buf;
222 int64_t deadline_ms = avx_time_ms() + (int64_t)timeout_ms;
223 while (total < len) {
224 int64_t rem = deadline_ms - avx_time_ms();
225 if (rem <= 0) return -1;
226 avx_pollfd_t pfd = { .fd = fd, .events = POLLIN, .revents = 0 };
227 int pr = avx_poll(&pfd, 1, (int)rem);
228 if (pr <= 0 || !(pfd.revents & POLLIN)) return -1;
229 ssize_t r = recv(fd, p + total, (int)(len - total), 0);
230 if (r <= 0) return r;
231 total += (size_t)r;
232 }
233 return (ssize_t)total;
234 }
235  
236 static uint64_t avx_get_raw_video_min_size(uint32_t fourcc, uint32_t w, uint32_t h) {
237 if (w == 0 || h == 0 || w > AVX_MAX_VIDEO_WIDTH || h > AVX_MAX_VIDEO_HEIGHT) {
238 return 0;
239 }
240 uint64_t pixels = (uint64_t)w * (uint64_t)h;
241 switch (fourcc) {
242 case OAVX_FOURCC_VIDEO_TYPE_UYVY:
243 return pixels * 2ULL;
244 case OAVX_FOURCC_VIDEO_TYPE_UYVA:
245 return pixels * 3ULL;
246 case OAVX_FOURCC_VIDEO_TYPE_RGBA:
247 case OAVX_FOURCC_VIDEO_TYPE_RGBX:
248 case OAVX_FOURCC_VIDEO_TYPE_BGRA:
249 case OAVX_FOURCC_VIDEO_TYPE_BGRX:
250 return pixels * 4ULL;
251 case OAVX_FOURCC_VIDEO_TYPE_P216:
252 return pixels * 4ULL;
253 case OAVX_FOURCC_VIDEO_TYPE_PA16:
254 return pixels * 6ULL;
255 case OAVX_FOURCC_VIDEO_TYPE_NV12: {
256 uint64_t uv_h = ((uint64_t)h + 1ULL) / 2ULL;
257 return pixels + (uint64_t)w * uv_h;
258 }
259 case OAVX_FOURCC_VIDEO_TYPE_I420:
260 case OAVX_FOURCC_VIDEO_TYPE_YV12: {
261 uint64_t w2 = ((uint64_t)w + 1ULL) / 2ULL;
262 uint64_t h2 = ((uint64_t)h + 1ULL) / 2ULL;
263 return pixels + 2ULL * (w2 * h2);
264 }
265 default:
266 return 0;
267 }
268 }
269  
270 void avx_setup_raw_video_planes(oavx_video_frame_t *vf, uint8_t *payload, size_t payload_len) {
271 if (!vf || !payload) return;
272 uint32_t w = vf->width;
273 uint32_t h = vf->height;
274  
275 vf->planes[0] = payload;
276 vf->planes[1] = NULL;
277 vf->planes[2] = NULL;
278 vf->planes[3] = NULL;
279 vf->strides[0] = 0;
280 vf->strides[1] = 0;
281 vf->strides[2] = 0;
282 vf->strides[3] = 0;
283  
284 if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
285 vf->strides[0] = (size_t)w * 2;
286 if (payload_len >= (size_t)w * h * 3) {
287 vf->planes[1] = payload + (size_t)w * h * 2;
288 vf->strides[1] = (size_t)w;
289 }
290 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
291 vf->strides[0] = (size_t)w * 2;
292 if (payload_len >= (size_t)w * h * 4) {
293 vf->planes[1] = payload + (size_t)w * h * 2;
294 vf->strides[1] = (size_t)w * 2;
295 }
296 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_PA16) {
297 vf->strides[0] = (size_t)w * 2;
298 if (payload_len >= (size_t)w * h * 6) {
299 vf->planes[1] = payload + (size_t)w * h * 2;
300 vf->strides[1] = (size_t)w * 2;
301 vf->planes[2] = payload + (size_t)w * h * 4;
302 vf->strides[2] = (size_t)w * 2;
303 }
304 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
305 vf->strides[0] = (size_t)w;
306 if (payload_len >= (size_t)w * h + (size_t)w * (((size_t)h + 1) / 2)) {
307 vf->planes[1] = payload + (size_t)w * h;
308 vf->strides[1] = (size_t)w;
309 }
310 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 || vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
311 uint32_t w2 = (w + 1) / 2;
312 uint32_t h2 = (h + 1) / 2;
313 vf->strides[0] = (size_t)w;
314 if (payload_len >= (size_t)w * h + 2ULL * ((size_t)w2 * h2)) {
315 vf->planes[1] = payload + (size_t)w * h;
316 vf->strides[1] = (size_t)w2;
317 vf->planes[2] = (uint8_t*)vf->planes[1] + (size_t)w2 * h2;
318 vf->strides[2] = (size_t)w2;
319 }
320 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA ||
321 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
322 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX ||
323 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
324 vf->strides[0] = (size_t)w * 4;
325 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 ||
326 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC ||
327 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01 ||
328 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_MJPEG ||
329 vf->fourcc == 0x47504A4D || vf->fourcc == 0x4A50474D ||
330 avx_is_speedhq_fourcc(vf->fourcc)) {
331 vf->strides[0] = payload_len;
332 } else {
333 vf->strides[0] = (h > 0) ? (size_t)(payload_len / h) : ((size_t)w * 2);
334 }
335 }
336  
337 static void avx_rx_execute_failover(avx_recv_ctx_t* slot, const char* reason) {
338 if (!slot || !slot->has_failover || slot->is_on_failover || slot->offline_mode) return;
339 if (slot->failover_url[0] == '\0') return;
340  
341 avx_trace_packet("[RX]", reason, slot->failover_url, strlen(slot->failover_url));
342  
343 /* Tear down dead/stalled connection */
344 avx_recv_close_pending_locked(slot);
345 if (slot->tcp_conn_fd != AVX_INVALID_SOCKET) {
346 shutdown(slot->tcp_conn_fd, AVX_SHUT_RDWR);
347 avx_socket_close(slot->tcp_conn_fd);
348 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
349 }
350 slot->connected = false;
351  
352 /* Preserve primary details if not already saved */
353 if (slot->primary_url[0] == '\0' && slot->target_url[0] != '\0') {
354 snprintf(slot->primary_url, sizeof(slot->primary_url), "%s", slot->target_url);
355 snprintf(slot->primary_name, sizeof(slot->primary_name), "%s", slot->target_name);
356 }
357  
358 /* Switch active target to failover */
359 snprintf(slot->target_url, sizeof(slot->target_url), "%s", slot->failover_url);
360 snprintf(slot->target_name, sizeof(slot->target_name), "%s", slot->failover_name);
361 slot->target_source.name = slot->target_name;
362 slot->target_source.address = slot->target_url;
363 slot->is_on_failover = true;
364 slot->primary_online_since_ns = 0;
365 slot->last_frame_recv_ns = avx_time_ns();
366 slot->last_connect_attempt_ns = 0;
367  
368 if (slot->video_decoder) {
369 avx_video_decoder_reset(slot->video_decoder);
370 }
371  
372 /* Immediately attempt connection to backup source */
373 avx_recv_try_connect(slot);
374 }
375  
376 static void avx_rx_execute_failback(avx_recv_ctx_t* slot) {
377 if (!slot || !slot->is_on_failover || slot->primary_url[0] == '\0') return;
378  
379 avx_trace_packet("[RX]", "FAILBACK CUTOVER (PRIMARY STABLE)", slot->primary_url, strlen(slot->primary_url));
380  
381 /* Disconnect from backup */
382 avx_recv_close_pending_locked(slot);
383 if (slot->tcp_conn_fd != AVX_INVALID_SOCKET) {
384 shutdown(slot->tcp_conn_fd, AVX_SHUT_RDWR);
385 avx_socket_close(slot->tcp_conn_fd);
386 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
387 }
388 slot->connected = false;
389  
390 /* Restore active target to primary */
391 snprintf(slot->target_url, sizeof(slot->target_url), "%s", slot->primary_url);
392 snprintf(slot->target_name, sizeof(slot->target_name), "%s", slot->primary_name);
393 slot->target_source.name = slot->target_name;
394 slot->target_source.address = slot->target_url;
395 slot->is_on_failover = false;
396 slot->primary_online_since_ns = 0;
397 slot->last_frame_recv_ns = avx_time_ns();
398 slot->last_connect_attempt_ns = 0;
399  
400 if (slot->video_decoder) {
401 avx_video_decoder_reset(slot->video_decoder);
402 }
403  
404 /* Reconnect to primary */
405 avx_recv_try_connect(slot);
406 }
407  
408 static bool avx_recv_finish_tcp_handshake_locked(avx_recv_ctx_t* slot, avx_socket_t fd,
409 const char* host, const char* target_url_snap) {
410 /* Unlock slot->lock during bounded XML handshake read so concurrent telemetry never stalls */
411 avx_mutex_unlock(&slot->lock);
412 uint32_t xml_len = 0;
413 bool hdr_ok = (recv_all_timeout(fd, &xml_len, sizeof(xml_len), 1500) == (ssize_t)sizeof(xml_len));
414 char* xml_data = NULL;
415 if (hdr_ok && xml_len > 0 && xml_len < 65536) {
416 xml_data = (char*)malloc(xml_len + 1);
417 if (xml_data && recv_all_timeout(fd, xml_data, xml_len, 1500) == (ssize_t)xml_len) {
418 xml_data[xml_len] = '\0';
419 } else {
420 free(xml_data);
421 xml_data = NULL;
422 }
423 }
424 avx_mutex_lock(&slot->lock);
425  
426 if (!hdr_ok || !slot->in_use || slot->offline_mode ||
427 strcmp(slot->target_url, target_url_snap) != 0) {
428 free(xml_data);
429 avx_socket_close(fd);
430 return false;
431 }
432  
433 if (xml_data) {
434 avx_trace_packet("[RX]", "TCP HANDSHAKE", xml_data, xml_len);
435 avx_rx_parse_failover_metadata(slot, xml_data);
436  
437 /* Parse UDP port and transport advertised by sender */
438 const char *uport = strstr(xml_data, "udp_port=\"");
439 if (uport) {
440 int up = atoi(uport + 10);
441 if (up > 0 && up <= 65535) {
442 memset(&slot->sender_udp_addr, 0, sizeof(slot->sender_udp_addr));
443 char clean_host[128];
444 const char *h = host;
445 if (h && h[0] == '[') {
446 const char *end = strchr(h, ']');
447 if (end) {
448 size_t len = (size_t)(end - (h + 1));
449 if (len < sizeof(clean_host)) {
450 memcpy(clean_host, h + 1, len);
451 clean_host[len] = '\0';
452 h = clean_host;
453 }
454 }
455 }
456  
457 struct in6_addr in6;
458 struct in_addr in4;
459 if (h && inet_pton(AF_INET6, h, &in6) == 1) {
460 struct sockaddr_in6 *s6 = (struct sockaddr_in6*)&slot->sender_udp_addr;
461 s6->sin6_family = AF_INET6;
462 s6->sin6_port = htons((uint16_t)up);
463 s6->sin6_addr = in6;
464 slot->has_sender_udp = true;
465 } else if (h && inet_pton(AF_INET, h, &in4) == 1) {
466 struct sockaddr_in *s4 = (struct sockaddr_in*)&slot->sender_udp_addr;
467 s4->sin_family = AF_INET;
468 s4->sin_port = htons((uint16_t)up);
469 s4->sin_addr = in4;
470 slot->has_sender_udp = true;
471 }
472 }
473 }
474 free(xml_data);
475 }
476  
477 slot->tcp_conn_fd = fd;
478 slot->connected = true;
479 slot->last_frame_recv_ns = avx_time_ns();
480  
481 if (!slot->is_on_failover && slot->target_url[0] != '\0') {
482 snprintf(slot->primary_url, sizeof(slot->primary_url), "%s", slot->target_url);
483 snprintf(slot->primary_name, sizeof(slot->primary_name), "%s", slot->target_name);
484 }
485  
486 if (slot->web_control_url[0] == '\0') {
487 if (strchr(host, ':')) {
488 snprintf(slot->web_control_url, sizeof(slot->web_control_url), "http://[%s]/", host);
489 } else {
490 snprintf(slot->web_control_url, sizeof(slot->web_control_url), "http://%s/", host);
491 }
492 }
493  
494 /* Send any registered connection metadata */
495 for (size_t m = 0; m < slot->num_conn_metadata; ++m) {
496 size_t mlen = strlen(slot->conn_metadata[m]);
497 AVX_PACKED_START
498 struct {
499 uint32_t magic;
500 int64_t timecode;
501 uint32_t payload_len;
502 } AVX_PACKED mhdr;
503 AVX_PACKED_END
504 mhdr.magic = slot->wire_profile.magic_metadata;
505 mhdr.timecode = 0;
506 mhdr.payload_len = (uint32_t)mlen;
507 send(fd, (const char*)&mhdr, sizeof(mhdr), MSG_NOSIGNAL);
508 send(fd, slot->conn_metadata[m], mlen, MSG_NOSIGNAL);
509 }
510  
511 /* Send transport negotiation XML to sender if RUDP or UDP active */
512 if ((slot->transport == OAVX_TRANSPORT_RUDP || slot->transport == OAVX_TRANSPORT_UDP) && slot->udp_port > 0) {
513 char codecs_str[64] = "";
514 bool can_av1 = avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_AV01);
515 bool can_hevc = avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_HEVC);
516 bool can_h264 = avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_H264);
517 snprintf(codecs_str, sizeof(codecs_str), "%s%s%s",
518 can_av1 ? "av1," : "",
519 can_hevc ? "hevc," : "",
520 can_h264 ? "h264," : "");
521 size_t c_len = strlen(codecs_str);
522 if (c_len > 0 && codecs_str[c_len - 1] == ',') codecs_str[c_len - 1] = '\0';
523 if (codecs_str[0] == '\0') snprintf(codecs_str, sizeof(codecs_str), "h264");
524  
525 const char *prof = (slot->bandwidth == OAVX_BANDWIDTH_HIGHEST) ? "lan" :
526 ((slot->bandwidth == OAVX_BANDWIDTH_LOWEST) ? "wan" : "auto");
527 char resp[256];
528 int rlen = snprintf(resp, sizeof(resp),
529 "<transport mode=\"%s\" port=\"%u\" codecs=\"%s\" profile=\"%s\"/>\n",
530 (slot->transport == OAVX_TRANSPORT_RUDP) ? "rudp" : "udp",
531 slot->udp_port, codecs_str, prof);
532 AVX_PACKED_START
533 struct {
534 uint32_t magic;
535 int64_t timecode;
536 uint32_t payload_len;
537 } AVX_PACKED mhdr;
538 AVX_PACKED_END
539 mhdr.magic = slot->wire_profile.magic_metadata;
540 mhdr.timecode = 0;
541 mhdr.payload_len = (uint32_t)rlen;
542 send(fd, (const char*)&mhdr, sizeof(mhdr), MSG_NOSIGNAL);
543 send(fd, resp, rlen, MSG_NOSIGNAL);
544  
545 /* Initial punch datagram to sender's UDP port */
546 if (slot->has_sender_udp && slot->udp_sock != AVX_INVALID_SOCKET) {
547 uint32_t ping_magic = slot->wire_profile.magic_udp ? slot->wire_profile.magic_udp : OAVX_UDP_MAGIC;
548 socklen_t slen = (slot->sender_udp_addr.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
549 sendto(slot->udp_sock, (const char*)&ping_magic, sizeof(ping_magic), 0,
550 (struct sockaddr*)&slot->sender_udp_addr, slen);
551 }
552 }
553  
554 return true;
555 }
556  
557 static bool avx_recv_step_connect_locked(avx_recv_ctx_t* slot, uint32_t step_budget_ms) {
558 if (!slot || slot->connected) return true;
559 if (slot->offline_mode || slot->target_url[0] == '\0') return false;
560  
561 char url_snap[256];
562 snprintf(url_snap, sizeof(url_snap), "%s", slot->target_url);
563  
564 char host[128] = {0};
565 uint16_t port = slot->wire_profile.base_port ? slot->wire_profile.base_port : AVX_DEFAULT_PORT;
566 if (!avx_parse_url_host_port(url_snap, port, host, sizeof(host), &port)) {
567 return false;
568 }
569  
570 if (slot->pending_conn_fd == AVX_INVALID_SOCKET) {
571 int64_t now_ns = avx_time_ns();
572 if (slot->last_connect_attempt_ns > 0 && (now_ns - slot->last_connect_attempt_ns) < 500000000LL) {
573 return false;
574 }
575  
576 avx_mutex_unlock(&slot->lock);
577 bool connected_now = false;
578 avx_socket_t new_fd = avx_socket_start_nonblocking_connect(host, port, &connected_now);
579 avx_mutex_lock(&slot->lock);
580  
581 if (!slot->in_use || slot->offline_mode || strcmp(slot->target_url, url_snap) != 0) {
582 if (new_fd != AVX_INVALID_SOCKET) avx_socket_close(new_fd);
583 return false;
584 }
585 if (new_fd == AVX_INVALID_SOCKET) {
586 slot->last_connect_attempt_ns = avx_time_ns();
587 return false;
588 }
589 if (connected_now) {
590 return avx_recv_finish_tcp_handshake_locked(slot, new_fd, host, url_snap);
591 }
592 slot->pending_conn_fd = new_fd;
593 slot->pending_conn_start_ns = avx_time_ns();
594 }
595  
596 avx_socket_t pfd_sock = slot->pending_conn_fd;
597 if (pfd_sock == AVX_INVALID_SOCKET) return false;
598  
599 avx_pollfd_t pfd = { .fd = pfd_sock, .events = POLLOUT, .revents = 0 };
600 avx_mutex_unlock(&slot->lock);
601 int pret = avx_poll(&pfd, 1, (int)step_budget_ms);
602 avx_mutex_lock(&slot->lock);
603  
604 if (!slot->in_use || slot->offline_mode || slot->pending_conn_fd != pfd_sock) {
605 return false;
606 }
607  
608 if (pret > 0 && (pfd.revents & POLLOUT) && !(pfd.revents & (POLLERR | POLLHUP | POLLNVAL))) {
609 int sock_err = 0;
610 socklen_t elen = sizeof(sock_err);
611 if (getsockopt(pfd_sock, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &elen) == 0 && sock_err == 0) {
612 slot->pending_conn_fd = AVX_INVALID_SOCKET;
613 slot->pending_conn_start_ns = 0;
614 avx_socket_set_nonblocking(pfd_sock, false);
615 avx_socket_set_keepalive(pfd_sock, 2, 1, 3);
616 avx_socket_set_tcp_nodelay(pfd_sock, true);
617 return avx_recv_finish_tcp_handshake_locked(slot, pfd_sock, host, url_snap);
618 }
619 /* Connect failed asynchronously (e.g. RST / ECONNREFUSED) */
620 avx_recv_close_pending_locked(slot);
621 slot->last_connect_attempt_ns = avx_time_ns();
622 return false;
623 }
624  
625 if (pret < 0 || (pfd.revents & (POLLERR | POLLHUP | POLLNVAL))) {
626 avx_recv_close_pending_locked(slot);
627 slot->last_connect_attempt_ns = avx_time_ns();
628 return false;
629 }
630  
631 /* Still in progress (WAN RTT or kernel SYN retry): preserve pending_conn_fd up to 2.2s */
632 if ((avx_time_ns() - slot->pending_conn_start_ns) >= 2200000000LL) {
633 avx_recv_close_pending_locked(slot);
634 slot->last_connect_attempt_ns = avx_time_ns();
635 }
636 return false;
637 }
638  
639 static bool avx_recv_try_connect(avx_recv_ctx_t* slot) {
640 return avx_recv_step_connect_locked(slot, 500);
641 }
642  
643 /*
644 * Allocates receiver session slot, configures requested color/bandwidth profiles,
645 * and binds optional UDP/RUDP listener socket for datagram transport.
646 */
647 OPENAVX_API avx_rx_instance_t avx_rx_create(const avx_rx_config_t* p_create_settings) {
648 avx_mutex_lock(&g_avx_state.global_lock);
649 if (!g_avx_state.initialized) {
650 avx_mutex_unlock(&g_avx_state.global_lock);
651 avx_engine_initialize();
652 avx_mutex_lock(&g_avx_state.global_lock);
653 }
654  
655 avx_recv_ctx_t* slot = NULL;
656 for (int i = 0; i < AVX_MAX_SESSIONS; ++i) {
657 if (!g_avx_state.recv_slots[i].in_use) {
658 slot = &g_avx_state.recv_slots[i];
659 memset(slot, 0, sizeof(*slot));
660 slot->in_use = true;
661 break;
662 }
663 }
664 avx_mutex_unlock(&g_avx_state.global_lock);
665  
666 if (!slot) return NULL;
667  
668 avx_mutex_init(&slot->lock);
669 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
670 slot->pending_conn_fd = AVX_INVALID_SOCKET;
671 slot->pending_conn_start_ns = 0;
672 slot->connected = false;
673 slot->video_buf = NULL;
674 slot->video_buf_size = 0;
675 slot->audio_buf = NULL;
676 slot->audio_buf_size = 0;
677 slot->metadata_buf = NULL;
678 slot->metadata_buf_size = 0;
679 slot->num_conn_metadata = 0;
680 slot->ptz_supported = true;
681 slot->recording_supported = true;
682 slot->is_recording = false;
683 slot->current_recording_filename[0] = '\0';
684 slot->current_recording_error[0] = '\0';
685 slot->web_control_url[0] = '\0';
686 slot->tally.flags = OAVX_TALLY_NONE;
687 avx_cond_init(&slot->tally_cond);
688  
689 const oavx_wire_profile_t *wp = (p_create_settings && p_create_settings->wire_profile)
690 ? p_create_settings->wire_profile : avx_wire_get_active_profile();
691 slot->wire_profile = *wp;
692  
693 if (p_create_settings) {
694 if (p_create_settings->source_to_connect_to.name) {
695 snprintf(slot->target_name, sizeof(slot->target_name), "%s", p_create_settings->source_to_connect_to.name);
696 snprintf(slot->primary_name, sizeof(slot->primary_name), "%s", p_create_settings->source_to_connect_to.name);
697 }
698 if (p_create_settings->source_to_connect_to.address) {
699 snprintf(slot->target_url, sizeof(slot->target_url), "%s", p_create_settings->source_to_connect_to.address);
700 snprintf(slot->primary_url, sizeof(slot->primary_url), "%s", p_create_settings->source_to_connect_to.address);
701 }
702 slot->target_source.name = slot->target_name;
703 slot->target_source.address = slot->target_url;
704 slot->color_format = p_create_settings->color_format;
705 slot->bandwidth = p_create_settings->bandwidth;
706 slot->allow_video_fields = p_create_settings->allow_video_fields;
707 if (p_create_settings->name) {
708 snprintf(slot->recv_name, sizeof(slot->recv_name), "%s", p_create_settings->name);
709 }
710 }
711  
712 slot->failover_timeout_ms = 500;
713 slot->auto_revert = false;
714 slot->revert_hold_ms = 3000;
715 slot->last_frame_recv_ns = avx_time_ns();
716 slot->offline_mode = false;
717  
718 slot->transport = p_create_settings ? p_create_settings->transport : OAVX_TRANSPORT_TCP;
719 slot->udp_sock = AVX_INVALID_SOCKET;
720 slot->udp_port = 0;
721 slot->rudp_receiver = NULL;
722 slot->has_sender_udp = false;
723  
724 slot->audio_decoder = NULL;
725 slot->audio_decoder_fourcc = 0;
726 slot->audio_decoder_channels = 0;
727 slot->audio_decoder_rate = 0;
728  
729 slot->video_decoder = NULL;
730 slot->video_decoder_fourcc = 0;
731 slot->video_decoder_width = 0;
732 slot->video_decoder_height = 0;
733  
734 if (slot->transport == OAVX_TRANSPORT_RUDP || slot->transport == OAVX_TRANSPORT_UDP) {
735 const char *rx_bind = NULL;
736 if (slot->target_url[0] == '[' || (strchr(slot->target_url, ':') && strchr(strchr(slot->target_url, ':') + 1, ':'))) {
737 rx_bind = "::";
738 }
739 slot->udp_sock = avx_udp_create_socket_bind(rx_bind, 0, true);
740 if (slot->udp_sock != AVX_INVALID_SOCKET) {
741 struct sockaddr_storage sin;
742 avx_socklen_t slen = sizeof(sin);
743 if (getsockname(slot->udp_sock, (struct sockaddr*)&sin, &slen) == 0) {
744 if (sin.ss_family == AF_INET6) {
745 slot->udp_port = ntohs(((struct sockaddr_in6*)&sin)->sin6_port);
746 } else {
747 slot->udp_port = ntohs(((struct sockaddr_in*)&sin)->sin_port);
748 }
749 }
750 if (slot->transport == OAVX_TRANSPORT_RUDP) {
751 slot->rudp_receiver = avx_udp_rudp_receiver_create(slot->udp_sock);
752 if (slot->rudp_receiver && p_create_settings && p_create_settings->passphrase) {
753 avx_udp_rudp_receiver_set_passphrase((avx_udp_rudp_receiver_t*)slot->rudp_receiver,
754 p_create_settings->passphrase,
755 p_create_settings->name);
756 }
757 }
758 }
759 }
760  
761 /* Attempt initial connection with bounded timeout (500ms); keeps pending_conn_fd alive across WAN RTT */
762 avx_mutex_lock(&slot->lock);
763 avx_recv_step_connect_locked(slot, 500);
764 avx_mutex_unlock(&slot->lock);
765  
766 return (avx_rx_instance_t)slot;
767 }
768  
769 OPENAVX_API void avx_rx_destroy(avx_rx_instance_t p_instance) {
770 if (!p_instance) return;
771 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
772  
773 /* Signal offline and shutdown sockets BEFORE acquiring slot->lock.
774 * This unblocks any concurrent thread blocked inside recv_all() or poll(),
775 * eliminating the teardown hang / deadlock. */
776 slot->offline_mode = true;
777 #if defined(AVX_OS_WINDOWS) || defined(_WIN32)
778 avx_socket_t conn_fd = slot->tcp_conn_fd;
779 if (conn_fd != AVX_INVALID_SOCKET) {
780 shutdown(conn_fd, AVX_SHUT_RDWR);
781 closesocket(conn_fd);
782 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
783 }
784 avx_socket_t pend_fd = slot->pending_conn_fd;
785 if (pend_fd != AVX_INVALID_SOCKET) {
786 shutdown(pend_fd, AVX_SHUT_RDWR);
787 closesocket(pend_fd);
788 slot->pending_conn_fd = AVX_INVALID_SOCKET;
789 }
790 avx_socket_t udp_fd = slot->udp_sock;
791 if (udp_fd != AVX_INVALID_SOCKET) {
792 shutdown(udp_fd, AVX_SHUT_RDWR);
793 closesocket(udp_fd);
794 slot->udp_sock = AVX_INVALID_SOCKET;
795 }
796 #else
797 avx_socket_t conn_fd = slot->tcp_conn_fd;
798 if (conn_fd != AVX_INVALID_SOCKET) {
799 shutdown(conn_fd, AVX_SHUT_RDWR);
800 }
801 avx_socket_t pend_fd = slot->pending_conn_fd;
802 if (pend_fd != AVX_INVALID_SOCKET) {
803 shutdown(pend_fd, AVX_SHUT_RDWR);
804 }
805 avx_socket_t udp_fd = slot->udp_sock;
806 if (udp_fd != AVX_INVALID_SOCKET) {
807 shutdown(udp_fd, AVX_SHUT_RDWR);
808 }
809 #endif
810  
811 /* Wait if a decoding operation is actively running in capture */
812 while (slot->decoding_video) {
813 avx_sleep_ms(1);
814 }
815  
816 avx_mutex_lock(&slot->lock);
817 avx_recv_close_pending_locked(slot);
818 if (slot->tcp_conn_fd != AVX_INVALID_SOCKET) {
819 avx_socket_close(slot->tcp_conn_fd);
820 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
821 }
822 slot->connected = false;
823  
824 if (slot->video_buf) {
825 free(slot->video_buf);
826 slot->video_buf = NULL;
827 slot->video_buf_size = 0;
828 }
829 if (slot->decompressed_buf) {
830 free(slot->decompressed_buf);
831 slot->decompressed_buf = NULL;
832 slot->decompressed_buf_size = 0;
833 }
834 if (slot->converted_buf) {
835 free(slot->converted_buf);
836 slot->converted_buf = NULL;
837 slot->converted_buf_size = 0;
838 }
839 if (slot->audio_buf) {
840 free(slot->audio_buf);
841 slot->audio_buf = NULL;
842 slot->audio_buf_size = 0;
843 }
844 if (slot->metadata_buf) {
845 free(slot->metadata_buf);
846 slot->metadata_buf = NULL;
847 slot->metadata_buf_size = 0;
848 }
849 if (slot->rudp_receiver) {
850 avx_udp_rudp_receiver_destroy((avx_udp_rudp_receiver_t*)slot->rudp_receiver);
851 slot->rudp_receiver = NULL;
852 }
853 if (slot->udp_sock != AVX_INVALID_SOCKET) {
854 avx_socket_close(slot->udp_sock);
855 slot->udp_sock = AVX_INVALID_SOCKET;
856 }
857 if (slot->audio_decoder) {
858 avx_audio_decoder_destroy(slot->audio_decoder);
859 slot->audio_decoder = NULL;
860 }
861 if (slot->video_decoder) {
862 avx_video_decoder_destroy(slot->video_decoder);
863 slot->video_decoder = NULL;
864 }
865 avx_mutex_unlock(&slot->lock);
866 avx_mutex_destroy(&slot->lock);
867 avx_cond_destroy(&slot->tally_cond);
868  
869 avx_mutex_lock(&g_avx_state.global_lock);
870 slot->in_use = false;
871 avx_mutex_unlock(&g_avx_state.global_lock);
872 }
873  
874 static avx_video_decoder_t *avx_rx_ensure_video_decoder_locked(
875 avx_recv_ctx_t *slot,
876 uint32_t fourcc,
877 uint32_t width,
878 uint32_t height)
879 {
880 if (!slot || width == 0 || height == 0 ||
881 width > AVX_MAX_VIDEO_WIDTH || height > AVX_MAX_VIDEO_HEIGHT) {
882 return NULL;
883 }
884  
885 if (!slot->video_decoder ||
886 slot->video_decoder_fourcc != fourcc ||
887 slot->video_decoder_width != width ||
888 slot->video_decoder_height != height) {
889 if (slot->video_decoder) {
890 avx_video_decoder_destroy(slot->video_decoder);
891 slot->video_decoder = NULL;
892 }
893 avx_video_dec_cfg_t cfg;
894 memset(&cfg, 0, sizeof(cfg));
895 cfg.fourcc = fourcc;
896 cfg.width = width;
897 cfg.height = height;
898 slot->video_decoder = avx_video_decoder_create(&cfg);
899 slot->video_decoder_fourcc = slot->video_decoder ? fourcc : 0;
900 slot->video_decoder_width = slot->video_decoder ? width : 0;
901 slot->video_decoder_height = slot->video_decoder ? height : 0;
902 }
903  
904 return slot->video_decoder;
905 }
906  
907 static bool avx_rx_is_compressed_video_fourcc(uint32_t fourcc) {
908 return avx_is_speedhq_fourcc(fourcc) ||
909 fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 || fourcc == 0x34363268 ||
910 fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC || fourcc == 0x43564568 ||
911 fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01 ||
912 fourcc == OAVX_FOURCC_VIDEO_TYPE_MJPEG || fourcc == 0x47504A4D || fourcc == 0x4A50474D;
913 }
914  
915 static int avx_rx_decode_video_payload(
916 avx_video_decoder_t *vdec,
917 const uint8_t *payload,
918 size_t payload_len,
919 oavx_video_frame_t *p_video_data)
920 {
921 if (!vdec || !payload || payload_len == 0 || !p_video_data) return AVX_VIDEO_CODEC_ERROR;
922  
923 oavx_video_frame_t decoded;
924 memset(&decoded, 0, sizeof(decoded));
925 int rc = avx_video_decoder_decode(vdec, payload, payload_len, &decoded);
926 if (rc != AVX_VIDEO_CODEC_OK) {
927 return rc;
928 }
929  
930 p_video_data->fourcc = decoded.fourcc;
931 if (decoded.width > 0) p_video_data->width = decoded.width;
932 if (decoded.height > 0) p_video_data->height = decoded.height;
933 for (int i = 0; i < 4; ++i) {
934 p_video_data->planes[i] = decoded.planes[i];
935 p_video_data->strides[i] = decoded.strides[i];
936 }
937 return AVX_VIDEO_CODEC_OK;
938 }
939  
940 static oavx_fourcc_video_type_e avx_rx_select_target_fourcc(
941 oavx_fourcc_video_type_e src_fourcc,
942 oavx_color_format_e color_fmt)
943 {
944 oavx_fourcc_video_type_e target_fourcc = src_fourcc;
945 if (color_fmt == OAVX_COLOR_FORMAT_RGBX_RGBA) {
946 if (src_fourcc != OAVX_FOURCC_VIDEO_TYPE_RGBA &&
947 src_fourcc != OAVX_FOURCC_VIDEO_TYPE_RGBX) {
948 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_RGBA;
949 }
950 } else if (color_fmt == OAVX_COLOR_FORMAT_BGRX_BGRA) {
951 if (src_fourcc != OAVX_FOURCC_VIDEO_TYPE_BGRA &&
952 src_fourcc != OAVX_FOURCC_VIDEO_TYPE_BGRX) {
953 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_BGRA;
954 }
955 } else if (color_fmt == OAVX_COLOR_FORMAT_UYVY_RGBA) {
956 if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
957 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
958 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_RGBA;
959 } else if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX ||
960 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX ||
961 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_P216 ||
962 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12 ||
963 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 ||
964 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
965 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_UYVY;
966 }
967 } else if (color_fmt == OAVX_COLOR_FORMAT_UYVY_BGRA) {
968 if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA ||
969 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
970 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_BGRA;
971 } else if (src_fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX ||
972 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX ||
973 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_P216 ||
974 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12 ||
975 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 ||
976 src_fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
977 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_UYVY;
978 }
979 } else if (color_fmt == OAVX_COLOR_FORMAT_P216) {
980 target_fourcc = OAVX_FOURCC_VIDEO_TYPE_P216;
981 }
982 return target_fourcc;
983 }
984  
985 static bool avx_rx_ensure_converted_buf(avx_recv_ctx_t *slot, size_t needed) {
986 if (slot->converted_buf_size < needed) {
987 uint8_t *nb = (uint8_t *)realloc(slot->converted_buf, needed);
988 if (!nb) return false;
989 slot->converted_buf = nb;
990 slot->converted_buf_size = needed;
991 }
992 return slot->converted_buf && slot->converted_buf_size >= needed;
993 }
994  
995 /*
996 * Converts native decoded pixel buffer to target requested color format
997 * using SIMD (e.g. UYVY to RGBA/BGRA/P216, NV12/I420 planar to UYVY).
998 */
999 static void avx_rx_convert_video_format(
1000 avx_recv_ctx_t *slot,
1001 oavx_color_format_e color_fmt,
1002 oavx_video_frame_t *vf)
1003 {
1004 if (!slot || !vf || !vf->planes[0] ||
1005 color_fmt == OAVX_COLOR_FORMAT_FASTEST ||
1006 color_fmt == OAVX_COLOR_FORMAT_COMPRESSED_V1) {
1007 return;
1008 }
1009  
1010 oavx_fourcc_video_type_e target_fourcc = avx_rx_select_target_fourcc(vf->fourcc, color_fmt);
1011 if (target_fourcc == vf->fourcc) return;
1012  
1013 int w = (int)vf->width;
1014 int h = (int)vf->height;
1015 if (w <= 0 || h <= 0 || w > AVX_MAX_VIDEO_WIDTH || h > AVX_MAX_VIDEO_HEIGHT) return;
1016  
1017 size_t bpp = (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) ? 2 : 4;
1018 uint64_t needed_u64 = (uint64_t)w * (uint64_t)h * (uint64_t)bpp;
1019 if (needed_u64 > AVX_MAX_DECOMPRESSED_FRAME_SIZE) return;
1020 size_t needed = (size_t)needed_u64;
1021 if (!avx_rx_ensure_converted_buf(slot, needed)) return;
1022  
1023 if (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA) {
1024 if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
1025 const uint8_t *alpha_src = vf->planes[1] ? vf->planes[1] : (vf->planes[0] + (size_t)w * h * 2);
1026 avx_color_uyva_to_rgba(vf->planes[0], alpha_src, slot->converted_buf, w, h);
1027 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
1028 avx_color_uyvy_to_rgba(vf->planes[0], slot->converted_buf, w, h);
1029 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
1030 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
1031 avx_color_rgba_to_bgra(vf->planes[0], slot->converted_buf, w, h);
1032 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
1033 avx_color_p216_to_rgba(vf->planes[0], slot->converted_buf, w, h);
1034 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
1035 avx_color_nv12_to_rgba(vf->planes[0], vf->strides[0],
1036 vf->planes[1], vf->strides[1],
1037 slot->converted_buf, (size_t)w * 4, w, h);
1038 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420) {
1039 avx_color_i420_to_rgba(vf->planes[0], vf->strides[0],
1040 vf->planes[1], vf->strides[1],
1041 vf->planes[2], vf->strides[2],
1042 slot->converted_buf, (size_t)w * 4, w, h);
1043 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
1044 avx_color_yv12_to_rgba(vf->planes[0], vf->strides[0],
1045 vf->planes[1], vf->strides[1],
1046 vf->planes[2], vf->strides[2],
1047 slot->converted_buf, (size_t)w * 4, w, h);
1048 } else {
1049 return;
1050 }
1051 } else if (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA) {
1052 if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
1053 const uint8_t *alpha_src = vf->planes[1] ? vf->planes[1] : (vf->planes[0] + (size_t)w * h * 2);
1054 avx_color_uyva_to_bgra(vf->planes[0], alpha_src, slot->converted_buf, w, h);
1055 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
1056 avx_color_uyvy_to_bgra(vf->planes[0], slot->converted_buf, w, h);
1057 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA ||
1058 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX) {
1059 avx_color_rgba_to_bgra(vf->planes[0], slot->converted_buf, w, h);
1060 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
1061 avx_color_p216_to_rgba(vf->planes[0], slot->converted_buf, w, h);
1062 avx_color_rgba_to_bgra(slot->converted_buf, slot->converted_buf, w, h);
1063 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
1064 avx_color_nv12_to_bgra(vf->planes[0], vf->strides[0],
1065 vf->planes[1], vf->strides[1],
1066 slot->converted_buf, (size_t)w * 4, w, h);
1067 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420) {
1068 avx_color_i420_to_rgba(vf->planes[0], vf->strides[0],
1069 vf->planes[1], vf->strides[1],
1070 vf->planes[2], vf->strides[2],
1071 slot->converted_buf, (size_t)w * 4, w, h);
1072 avx_color_rgba_to_bgra(slot->converted_buf, slot->converted_buf, w, h);
1073 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
1074 avx_color_yv12_to_rgba(vf->planes[0], vf->strides[0],
1075 vf->planes[1], vf->strides[1],
1076 vf->planes[2], vf->strides[2],
1077 slot->converted_buf, (size_t)w * 4, w, h);
1078 avx_color_rgba_to_bgra(slot->converted_buf, slot->converted_buf, w, h);
1079 } else {
1080 return;
1081 }
1082 } else if (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
1083 if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA ||
1084 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX) {
1085 avx_color_rgba_to_uyvy(vf->planes[0], slot->converted_buf, w, h);
1086 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
1087 vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
1088 avx_color_bgra_to_uyvy(vf->planes[0], slot->converted_buf, w, h);
1089 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
1090 avx_color_p216_to_uyvy(vf->planes[0], slot->converted_buf, w, h);
1091 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
1092 avx_color_nv12_to_uyvy(vf->planes[0], vf->strides[0],
1093 vf->planes[1], vf->strides[1],
1094 slot->converted_buf, (size_t)w * 2, w, h);
1095 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420) {
1096 avx_color_i420_to_uyvy(vf->planes[0], vf->strides[0],
1097 vf->planes[1], vf->strides[1],
1098 vf->planes[2], vf->strides[2],
1099 slot->converted_buf, (size_t)w * 2, w, h);
1100 } else if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
1101 avx_color_yv12_to_uyvy(vf->planes[0], vf->strides[0],
1102 vf->planes[1], vf->strides[1],
1103 vf->planes[2], vf->strides[2],
1104 slot->converted_buf, (size_t)w * 2, w, h);
1105 } else {
1106 return;
1107 }
1108 } else if (target_fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
1109 if (vf->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
1110 avx_color_uyvy_to_p216(vf->planes[0], slot->converted_buf, w, h);
1111 } else {
1112 return;
1113 }
1114 vf->planes[0] = slot->converted_buf;
1115 vf->planes[1] = slot->converted_buf + (size_t)w * h * 2ULL;
1116 vf->planes[2] = NULL;
1117 vf->planes[3] = NULL;
1118 vf->fourcc = target_fourcc;
1119 vf->strides[0] = (size_t)w * 2ULL;
1120 vf->strides[1] = (size_t)w * 2ULL;
1121 vf->strides[2] = 0;
1122 vf->strides[3] = 0;
1123 return;
1124 } else {
1125 return;
1126 }
1127  
1128 vf->planes[0] = slot->converted_buf;
1129 vf->planes[1] = NULL;
1130 vf->planes[2] = NULL;
1131 vf->planes[3] = NULL;
1132 vf->fourcc = target_fourcc;
1133 vf->strides[0] = (size_t)w * bpp;
1134 vf->strides[1] = 0;
1135 vf->strides[2] = 0;
1136 vf->strides[3] = 0;
1137 }
1138  
1139 static oavx_frame_type_t avx_rx_deliver_video_frame(
1140 avx_recv_ctx_t *slot,
1141 avx_video_decoder_t *vdec,
1142 oavx_color_format_e color_fmt,
1143 bool is_compressed,
1144 const char *metadata_str,
1145 uint32_t fourcc,
1146 uint32_t width,
1147 uint32_t height,
1148 int32_t fps_num,
1149 int32_t fps_den,
1150 int64_t timecode,
1151 uint8_t *payload,
1152 size_t payload_len,
1153 oavx_video_frame_t *p_video_data)
1154 {
1155 if (!p_video_data) {
1156 return OAVX_FRAME_TYPE_VIDEO;
1157 }
1158  
1159 memset(p_video_data, 0, sizeof(*p_video_data));
1160 p_video_data->width = width;
1161 p_video_data->height = height;
1162 p_video_data->framerate.num = (uint32_t)fps_num;
1163 p_video_data->framerate.den = (uint32_t)fps_den;
1164 p_video_data->aspect_ratio.num = width;
1165 p_video_data->aspect_ratio.den = height > 0 ? height : 1;
1166 p_video_data->scan_type = OAVX_SCAN_PROGRESSIVE;
1167 p_video_data->pts_ns = timecode;
1168 p_video_data->dts_ns = timecode;
1169 p_video_data->metadata = metadata_str;
1170 p_video_data->metadata_len = metadata_str ? strlen(metadata_str) : 0;
1171 p_video_data->user_ctx = NULL;
1172  
1173 int dec_ok = AVX_VIDEO_CODEC_ERROR;
1174 if (is_compressed) {
1175 if (color_fmt == OAVX_COLOR_FORMAT_FASTEST ||
1176 color_fmt == OAVX_COLOR_FORMAT_COMPRESSED_V1) {
1177 p_video_data->fourcc = (oavx_fourcc_video_type_e)fourcc;
1178 p_video_data->planes[0] = payload;
1179 p_video_data->strides[0] = payload_len;
1180 } else {
1181 dec_ok = avx_rx_decode_video_payload(vdec, payload, payload_len, p_video_data);
1182 if (dec_ok == AVX_VIDEO_CODEC_NEED_MORE_DATA) {
1183 return OAVX_FRAME_TYPE_NONE;
1184 }
1185 if (dec_ok != AVX_VIDEO_CODEC_OK) {
1186 /* Decoding unavailable or failed; deliver compressed frame */
1187 p_video_data->fourcc = (oavx_fourcc_video_type_e)fourcc;
1188 p_video_data->planes[0] = payload;
1189 p_video_data->strides[0] = payload_len;
1190 }
1191 }
1192 } else {
1193 p_video_data->fourcc = (oavx_fourcc_video_type_e)fourcc;
1194 avx_setup_raw_video_planes(p_video_data, payload, payload_len);
1195 }
1196  
1197 if (!is_compressed || dec_ok == AVX_VIDEO_CODEC_OK) {
1198 avx_rx_convert_video_format(slot, color_fmt, p_video_data);
1199 }
1200 return OAVX_FRAME_TYPE_VIDEO;
1201 }
1202  
1203 static oavx_frame_type_t avx_rx_process_compressed_audio(
1204 avx_recv_ctx_t *slot,
1205 uint32_t codec_fourcc,
1206 int32_t sample_rate,
1207 int32_t channels,
1208 int32_t samples,
1209 int64_t timecode,
1210 uint32_t payload_len,
1211 const uint8_t *payload_data,
1212 oavx_audio_frame_t *p_audio_data
1213 ) {
1214 if (channels <= 0 || channels > OAVX_MAX_AUDIO_CHANNELS || samples < 0 || samples > 192000 ||
1215 payload_len == 0 || payload_len > 16 * 1024 * 1024 ||
1216 sample_rate <= 0 || sample_rate > 192000) {
1217 return OAVX_FRAME_TYPE_ERROR;
1218 }
1219  
1220 if (!slot->audio_decoder || slot->audio_decoder_fourcc != codec_fourcc ||
1221 slot->audio_decoder_channels != channels || slot->audio_decoder_rate != sample_rate) {
1222 if (slot->audio_decoder) {
1223 avx_audio_decoder_destroy(slot->audio_decoder);
1224 slot->audio_decoder = NULL;
1225 }
1226 slot->audio_decoder = avx_audio_decoder_create(sample_rate, channels, codec_fourcc);
1227 slot->audio_decoder_fourcc = codec_fourcc;
1228 slot->audio_decoder_channels = channels;
1229 slot->audio_decoder_rate = sample_rate;
1230 }
1231  
1232 if (!slot->audio_decoder) {
1233 return OAVX_FRAME_TYPE_ERROR;
1234 }
1235  
1236 int max_dec_samples = samples > 0 ? samples : 4096;
1237 if (max_dec_samples < 960) max_dec_samples = 960;
1238 size_t needed_buf = (size_t)channels * (size_t)max_dec_samples * sizeof(float);
1239 if (slot->audio_buf_size < needed_buf) {
1240 float *new_buf = (float*)realloc(slot->audio_buf, needed_buf);
1241 if (!new_buf) return OAVX_FRAME_TYPE_ERROR;
1242 slot->audio_buf = new_buf;
1243 slot->audio_buf_size = needed_buf;
1244 }
1245  
1246 float *dec_planes[OAVX_MAX_AUDIO_CHANNELS];
1247 for (int c = 0; c < channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1248 dec_planes[c] = slot->audio_buf + (size_t)c * (size_t)max_dec_samples;
1249 }
1250  
1251 int decoded_frames = avx_audio_decoder_decode(slot->audio_decoder, codec_fourcc,
1252 payload_data, (size_t)payload_len,
1253 dec_planes, max_dec_samples);
1254 if (decoded_frames <= 0) {
1255 return OAVX_FRAME_TYPE_ERROR;
1256 }
1257  
1258 if (p_audio_data) {
1259 memset(p_audio_data, 0, sizeof(*p_audio_data));
1260 p_audio_data->sample_rate = (uint32_t)sample_rate;
1261 p_audio_data->channels = (uint16_t)channels;
1262 p_audio_data->frames = (uint32_t)decoded_frames;
1263 p_audio_data->format = OAVX_AUDIO_FMT_FLT_PLANAR;
1264 p_audio_data->stride_bytes = (size_t)decoded_frames * sizeof(float);
1265 p_audio_data->pts_ns = timecode;
1266 p_audio_data->channel_mask = avx_audio_layout_to_mask(avx_audio_layout_from_channels((uint16_t)channels));
1267 p_audio_data->metadata = NULL;
1268 p_audio_data->metadata_len = 0;
1269 p_audio_data->user_ctx = NULL;
1270 for (int c = 0; c < channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1271 p_audio_data->planes[c] = dec_planes[c];
1272 }
1273 for (int c = channels; c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1274 p_audio_data->planes[c] = NULL;
1275 }
1276 }
1277  
1278 slot->perf.audio_frames++;
1279 return OAVX_FRAME_TYPE_AUDIO;
1280 }
1281  
1282 static void avx_recv_update_video_telemetry_locked(
1283 avx_recv_ctx_t* slot,
1284 uint32_t fourcc,
1285 uint32_t width,
1286 uint32_t height,
1287 int32_t fps_n,
1288 int32_t fps_d,
1289 size_t wire_bytes,
1290 int64_t now_ns
1291 ) {
1292 slot->telem.total_bytes += wire_bytes;
1293 slot->telem.window_bytes += wire_bytes;
1294 slot->telem.window_frames++;
1295 slot->telem.last_fourcc = fourcc;
1296 slot->telem.last_width = width;
1297 slot->telem.last_height = height;
1298  
1299 if (slot->telem.last_frame_arrival_ns > 0) {
1300 int64_t dt_ns = now_ns - slot->telem.last_frame_arrival_ns;
1301 int64_t nominal_ns = (fps_n > 0 && fps_d > 0)
1302 ? ((int64_t)fps_d * 1000000000LL) / fps_n
1303 : 16666666LL;
1304 float diff_ms = fabsf((float)(dt_ns - nominal_ns) / 1000000.0f);
1305 if (slot->telem.inter_frame_jitter_ms == 0.0f) {
1306 slot->telem.inter_frame_jitter_ms = diff_ms;
1307 } else {
1308 slot->telem.inter_frame_jitter_ms = 0.85f * slot->telem.inter_frame_jitter_ms + 0.15f * diff_ms;
1309 }
1310 }
1311 slot->telem.last_frame_arrival_ns = now_ns;
1312 slot->last_frame_recv_ns = now_ns;
1313  
1314 if (slot->telem.last_window_time_ns == 0) {
1315 slot->telem.last_window_time_ns = now_ns;
1316 } else {
1317 int64_t elapsed_ns = now_ns - slot->telem.last_window_time_ns;
1318 if (elapsed_ns >= 500000000LL) { /* 500 ms sliding window */
1319 float elapsed_sec = (float)elapsed_ns / 1000000000.0f;
1320 slot->telem.instant_fps = (float)slot->telem.window_frames / elapsed_sec;
1321 slot->telem.instant_mbps = ((float)slot->telem.window_bytes * 8.0f) / (elapsed_sec * 1000000.0f);
1322 slot->telem.window_bytes = 0;
1323 slot->telem.window_frames = 0;
1324 slot->telem.last_window_time_ns = now_ns;
1325 }
1326 }
1327 }
1328  
1329 /*
1330 * Polls active stream for next media frame up to timeout_in_ms. Handles TCP
1331 * stream parsing, RUDP datagram reassembly, stall failover, and auto-revert.
1332 * Returned buffer memory is owned by receiver and valid until next receive call.
1333 */
1334 OPENAVX_API oavx_frame_type_t avx_rx_receive(
1335 avx_rx_instance_t p_instance,
1336 oavx_video_frame_t* p_video_data,
1337 oavx_audio_frame_t* p_audio_data,
1338 oavx_metadata_frame_t* metadata,
1339 uint32_t timeout_in_ms
1340 ) {
1341 if (!p_instance) return OAVX_FRAME_TYPE_ERROR;
1342 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
1343  
1344 avx_mutex_lock(&slot->lock);
1345 int64_t now_ns = avx_time_ns();
1346  
1347 /* 1. Check Debounced Auto-Revert if on failover */
1348 if (slot->auto_revert && slot->is_on_failover && slot->primary_url[0] != '\0' && !slot->offline_mode) {
1349 if (slot->last_probe_time_ns == 0 || (now_ns - slot->last_probe_time_ns) >= 1000000000LL) {
1350 slot->last_probe_time_ns = now_ns;
1351 char p_host[128] = {0};
1352 uint16_t p_port = slot->wire_profile.base_port ? slot->wire_profile.base_port : AVX_DEFAULT_PORT;
1353 if (avx_parse_url_host_port(slot->primary_url, p_port, p_host, sizeof(p_host), &p_port)) {
1354 if (avx_tcp_probe(p_host, p_port, 20)) {
1355 if (slot->primary_online_since_ns == 0) {
1356 slot->primary_online_since_ns = now_ns;
1357 } else if ((now_ns - slot->primary_online_since_ns) >= (int64_t)slot->revert_hold_ms * 1000000LL) {
1358 avx_rx_execute_failback(slot);
1359 }
1360 } else {
1361 slot->primary_online_since_ns = 0;
1362 }
1363 }
1364 }
1365 }
1366  
1367 /* 2. Check Stream Stall on Connected Stream */
1368 if (slot->connected) {
1369 uint32_t stall_threshold_ms = slot->failover_timeout_ms ? slot->failover_timeout_ms : 500;
1370 if (slot->has_failover && !slot->is_on_failover &&
1371 slot->last_frame_recv_ns != 0 &&
1372 (now_ns - slot->last_frame_recv_ns) > (int64_t)stall_threshold_ms * 1000000LL) {
1373 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (STREAM STALL)");
1374 }
1375 }
1376  
1377 /* 3. Reconnection / Initial Connection */
1378 if (!slot->connected) {
1379 bool had_pending = (slot->pending_conn_fd != AVX_INVALID_SOCKET);
1380 uint32_t step_budget = (timeout_in_ms > 0) ? timeout_in_ms : 25;
1381 if (step_budget > 500) step_budget = 500;
1382  
1383 if (!avx_recv_step_connect_locked(slot, step_budget)) {
1384 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0' &&
1385 slot->pending_conn_fd == AVX_INVALID_SOCKET) {
1386 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (PRIMARY UNREACHABLE)");
1387 }
1388 }
1389 if (!slot->connected) {
1390 bool has_pending_now = (slot->pending_conn_fd != AVX_INVALID_SOCKET);
1391 avx_mutex_unlock(&slot->lock);
1392 /* Only sleep if cooldown prevented polling a socket this iteration */
1393 if (!had_pending && !has_pending_now && timeout_in_ms > 0) {
1394 avx_sleep_ms(timeout_in_ms);
1395 }
1396 return OAVX_FRAME_TYPE_NONE;
1397 }
1398 }
1399  
1400 /* 3b. Datagram / RUDP Reception Path */
1401 if ((slot->transport == OAVX_TRANSPORT_RUDP || slot->transport == OAVX_TRANSPORT_UDP) && slot->has_sender_udp) {
1402 /* Check TCP for control / metadata packets non-blockingly */
1403 if (slot->tcp_conn_fd != AVX_INVALID_SOCKET) {
1404 avx_pollfd_t cpfd = { .fd = slot->tcp_conn_fd, .events = POLLIN, .revents = 0 };
1405 if (avx_poll(&cpfd, 1, 0) > 0 && (cpfd.revents & POLLIN)) {
1406 uint32_t cmagic = 0;
1407 #ifdef MSG_DONTWAIT
1408 const int recv_flags = MSG_DONTWAIT;
1409 #else
1410 const int recv_flags = 0;
1411 #endif
1412 if (recv(slot->tcp_conn_fd, (char*)&cmagic, sizeof(cmagic), recv_flags) == (ssize_t)sizeof(cmagic)) {
1413 if (cmagic == slot->wire_profile.magic_metadata ||
1414 (slot->wire_profile.compat_magic_metadata && cmagic == slot->wire_profile.compat_magic_metadata)) {
1415 AVX_PACKED_START
1416 struct {
1417 int64_t timecode;
1418 uint32_t payload_len;
1419 } AVX_PACKED mhdr;
1420 AVX_PACKED_END
1421 if (recv_all(slot->tcp_conn_fd, &mhdr, sizeof(mhdr)) == (ssize_t)sizeof(mhdr)) {
1422 if (mhdr.payload_len > 0 && mhdr.payload_len < 65536) {
1423 if (slot->metadata_buf_size < mhdr.payload_len + 1) {
1424 char* nb = (char*)realloc(slot->metadata_buf, mhdr.payload_len + 1);
1425 if (nb) {
1426 slot->metadata_buf = nb;
1427 slot->metadata_buf_size = mhdr.payload_len + 1;
1428 }
1429 }
1430 if (slot->metadata_buf && recv_all(slot->tcp_conn_fd, slot->metadata_buf, mhdr.payload_len) == (ssize_t)mhdr.payload_len) {
1431 slot->metadata_buf[mhdr.payload_len] = '\0';
1432 avx_rx_parse_tally_metadata_locked(slot, slot->metadata_buf);
1433 if (metadata) {
1434 metadata->length = mhdr.payload_len;
1435 metadata->pts_ns = mhdr.timecode;
1436 metadata->data = slot->metadata_buf;
1437 }
1438 avx_mutex_unlock(&slot->lock);
1439 return OAVX_FRAME_TYPE_METADATA;
1440 }
1441 }
1442 }
1443 }
1444 }
1445 }
1446 }
1447  
1448 /* Receive Media Frame via RUDP / UDP */
1449 if (!slot->video_buf || slot->video_buf_size < 8 * 1024 * 1024) {
1450 size_t new_sz = 8 * 1024 * 1024;
1451 uint8_t *nb = (uint8_t*)realloc(slot->video_buf, new_sz);
1452 if (nb) {
1453 slot->video_buf = nb;
1454 slot->video_buf_size = new_sz;
1455 }
1456 }
1457  
1458 size_t assembled_len = 0;
1459 uint32_t assembled_fourcc = 0;
1460 int64_t assembled_tc = 0;
1461 int ret = -1;
1462  
1463 if (slot->transport == OAVX_TRANSPORT_RUDP && slot->rudp_receiver) {
1464 ret = avx_udp_rudp_recv_frame((avx_udp_rudp_receiver_t*)slot->rudp_receiver,
1465 &slot->sender_udp_addr,
1466 slot->video_buf, slot->video_buf_size,
1467 &assembled_len, &assembled_fourcc, &assembled_tc,
1468 (int)timeout_in_ms);
1469 } else if (slot->udp_sock != AVX_INVALID_SOCKET) {
1470 ret = avx_udp_recv_frame(slot->udp_sock,
1471 slot->video_buf, slot->video_buf_size,
1472 &assembled_len, &assembled_fourcc, &assembled_tc,
1473 (int)timeout_in_ms);
1474 }
1475  
1476 if (ret == 0 && assembled_len > 0) {
1477 slot->last_frame_recv_ns = avx_time_ns();
1478  
1479 if (assembled_fourcc == OAVX_FOURCC_AUDIO_TYPE_FLTP) {
1480 if (assembled_len >= 28) {
1481 int32_t s_rate = 48000;
1482 int32_t s_channels = 2;
1483 int32_t s_samples = 0;
1484 int64_t s_tc = assembled_tc;
1485 memcpy(&s_rate, slot->video_buf + 4, sizeof(s_rate));
1486 memcpy(&s_channels, slot->video_buf + 8, sizeof(s_channels));
1487 memcpy(&s_samples, slot->video_buf + 12, sizeof(s_samples));
1488 memcpy(&s_tc, slot->video_buf + 16, sizeof(s_tc));
1489  
1490 size_t pcm_offset = 28;
1491 size_t pcm_bytes = assembled_len - pcm_offset;
1492  
1493 if (s_channels <= 0 || s_channels > OAVX_MAX_AUDIO_CHANNELS || s_samples < 0 || s_samples > 1920000 ||
1494 (uint64_t)s_channels * (uint64_t)s_samples * sizeof(float) > (uint64_t)pcm_bytes) {
1495 avx_mutex_unlock(&slot->lock);
1496 return OAVX_FRAME_TYPE_NONE;
1497 }
1498  
1499 if (p_audio_data) {
1500 memset(p_audio_data, 0, sizeof(*p_audio_data));
1501 p_audio_data->sample_rate = s_rate > 0 ? (uint32_t)s_rate : 48000;
1502 p_audio_data->channels = (uint16_t)s_channels;
1503 p_audio_data->frames = (uint32_t)s_samples;
1504 p_audio_data->format = OAVX_AUDIO_FMT_FLT_PLANAR;
1505 p_audio_data->pts_ns = s_tc;
1506 p_audio_data->stride_bytes = (size_t)s_samples * sizeof(float);
1507 p_audio_data->channel_mask = avx_audio_layout_to_mask(avx_audio_layout_from_channels((uint16_t)s_channels));
1508 for (int c = 0; c < s_channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1509 p_audio_data->planes[c] = (slot->video_buf && s_samples > 0)
1510 ? (slot->video_buf + pcm_offset + (size_t)c * p_audio_data->stride_bytes)
1511 : NULL;
1512 }
1513 for (int c = s_channels; c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1514 p_audio_data->planes[c] = NULL;
1515 }
1516 }
1517 slot->perf.audio_frames++;
1518 avx_mutex_unlock(&slot->lock);
1519 return OAVX_FRAME_TYPE_AUDIO;
1520 }
1521 } else if (assembled_fourcc == OAVX_FOURCC_AUDIO_TYPE_OPUS ||
1522 assembled_fourcc == OAVX_FOURCC_AUDIO_TYPE_ADPC) {
1523 if (assembled_len >= 32) {
1524 uint32_t c_fourcc = assembled_fourcc;
1525 int32_t c_rate = 48000;
1526 int32_t c_channels = 2;
1527 int32_t c_samples = 0;
1528 int64_t c_tc = assembled_tc;
1529 uint32_t c_payload_len = 0;
1530 memcpy(&c_fourcc, slot->video_buf + 4, sizeof(c_fourcc));
1531 memcpy(&c_rate, slot->video_buf + 8, sizeof(c_rate));
1532 memcpy(&c_channels, slot->video_buf + 12, sizeof(c_channels));
1533 memcpy(&c_samples, slot->video_buf + 16, sizeof(c_samples));
1534 memcpy(&c_tc, slot->video_buf + 20, sizeof(c_tc));
1535 memcpy(&c_payload_len, slot->video_buf + 28, sizeof(c_payload_len));
1536  
1537 if (32 + c_payload_len <= assembled_len) {
1538 oavx_frame_type_t ft = avx_rx_process_compressed_audio(
1539 slot, c_fourcc, c_rate, c_channels, c_samples, c_tc,
1540 c_payload_len, slot->video_buf + 32, p_audio_data);
1541 avx_mutex_unlock(&slot->lock);
1542 return ft;
1543 }
1544 }
1545 } else {
1546 /* Video frame */
1547 AVX_PACKED_START
1548 struct {
1549 uint32_t magic;
1550 uint32_t xres;
1551 uint32_t yres;
1552 uint32_t fourcc;
1553 int32_t frame_rate_n;
1554 int32_t frame_rate_d;
1555 int64_t timecode;
1556 uint32_t payload_len;
1557 } AVX_PACKED vhdr;
1558 AVX_PACKED_END
1559  
1560 if (assembled_len >= sizeof(vhdr)) {
1561 memcpy(&vhdr, slot->video_buf, sizeof(vhdr));
1562 uint8_t *raw_payload = slot->video_buf + sizeof(vhdr);
1563 size_t raw_payload_len = assembled_len - sizeof(vhdr);
1564  
1565 if (vhdr.xres == 0 || vhdr.yres == 0 ||
1566 vhdr.xres > AVX_MAX_VIDEO_WIDTH || vhdr.yres > AVX_MAX_VIDEO_HEIGHT ||
1567 vhdr.payload_len > raw_payload_len) {
1568 avx_mutex_unlock(&slot->lock);
1569 return OAVX_FRAME_TYPE_NONE;
1570 }
1571  
1572 bool is_compressed = avx_rx_is_compressed_video_fourcc(vhdr.fourcc);
1573 size_t frame_payload_len = (vhdr.payload_len > 0) ? (size_t)vhdr.payload_len : raw_payload_len;
1574 if (!is_compressed) {
1575 uint64_t min_raw = avx_get_raw_video_min_size(vhdr.fourcc, vhdr.xres, vhdr.yres);
1576 if (min_raw > 0 && (uint64_t)frame_payload_len < min_raw) {
1577 avx_mutex_unlock(&slot->lock);
1578 return OAVX_FRAME_TYPE_NONE;
1579 }
1580 }
1581  
1582 avx_recv_update_video_telemetry_locked(
1583 slot, vhdr.fourcc, vhdr.xres, vhdr.yres,
1584 vhdr.frame_rate_n, vhdr.frame_rate_d,
1585 assembled_len, avx_time_ns());
1586  
1587 slot->perf.video_frames++;
1588 oavx_color_format_e color_fmt = slot->color_format;
1589 const char *metadata_str = slot->last_video_metadata[0] ? slot->last_video_metadata : NULL;
1590 avx_video_decoder_t *vdec = NULL;
1591 if (is_compressed && p_video_data &&
1592 color_fmt != OAVX_COLOR_FORMAT_FASTEST &&
1593 color_fmt != OAVX_COLOR_FORMAT_COMPRESSED_V1) {
1594 vdec = avx_rx_ensure_video_decoder_locked(slot, vhdr.fourcc, vhdr.xres, vhdr.yres);
1595 }
1596 slot->decoding_video = true;
1597 avx_mutex_unlock(&slot->lock);
1598  
1599 oavx_frame_type_t ft = avx_rx_deliver_video_frame(
1600 slot, vdec, color_fmt, is_compressed, metadata_str,
1601 vhdr.fourcc, vhdr.xres, vhdr.yres,
1602 vhdr.frame_rate_n, vhdr.frame_rate_d, vhdr.timecode,
1603 raw_payload, frame_payload_len, p_video_data);
1604  
1605 avx_mutex_lock(&slot->lock);
1606 slot->decoding_video = false;
1607 avx_mutex_unlock(&slot->lock);
1608 return ft;
1609 }
1610 }
1611 }
1612 avx_mutex_unlock(&slot->lock);
1613 return OAVX_FRAME_TYPE_NONE;
1614 }
1615  
1616 avx_pollfd_t pfd = {
1617 .fd = slot->tcp_conn_fd,
1618 .events = POLLIN,
1619 .revents = 0
1620 };
1621  
1622 avx_mutex_unlock(&slot->lock);
1623 int poll_res = avx_poll(&pfd, 1, (int)timeout_in_ms);
1624 avx_mutex_lock(&slot->lock);
1625  
1626 if (slot->tcp_conn_fd == AVX_INVALID_SOCKET || !slot->connected) {
1627 avx_mutex_unlock(&slot->lock);
1628 return OAVX_FRAME_TYPE_NONE;
1629 }
1630  
1631 if (poll_res > 0 && (pfd.revents & (POLLHUP | POLLERR))) {
1632 avx_socket_close(slot->tcp_conn_fd);
1633 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1634 slot->connected = false;
1635 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1636 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT / POLLHUP)");
1637 }
1638 avx_mutex_unlock(&slot->lock);
1639 return OAVX_FRAME_TYPE_ERROR;
1640 }
1641  
1642 if (poll_res <= 0 || !(pfd.revents & POLLIN)) {
1643 int64_t curr_ns = avx_time_ns();
1644 uint32_t stall_threshold_ms = slot->failover_timeout_ms ? slot->failover_timeout_ms : 500;
1645 if (slot->has_failover && !slot->is_on_failover &&
1646 slot->last_frame_recv_ns != 0 &&
1647 (curr_ns - slot->last_frame_recv_ns) > (int64_t)stall_threshold_ms * 1000000LL) {
1648 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (STREAM STALL IN POLL)");
1649 }
1650 avx_mutex_unlock(&slot->lock);
1651 return OAVX_FRAME_TYPE_NONE;
1652 }
1653  
1654 /* Read packet magic (4 bytes) */
1655 uint32_t magic = 0;
1656 if (recv_all(slot->tcp_conn_fd, &magic, sizeof(magic)) != (ssize_t)sizeof(magic)) {
1657 avx_socket_close(slot->tcp_conn_fd);
1658 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1659 slot->connected = false;
1660 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1661 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1662 }
1663 avx_mutex_unlock(&slot->lock);
1664 return OAVX_FRAME_TYPE_ERROR;
1665 }
1666  
1667 if (magic == slot->wire_profile.magic_video ||
1668 (slot->wire_profile.compat_magic_video && magic == slot->wire_profile.compat_magic_video)) {
1669 AVX_PACKED_START
1670 struct {
1671 uint32_t xres;
1672 uint32_t yres;
1673 uint32_t fourcc;
1674 int32_t frame_rate_n;
1675 int32_t frame_rate_d;
1676 int64_t timecode;
1677 uint32_t payload_len;
1678 } AVX_PACKED vhdr;
1679 AVX_PACKED_END
1680  
1681 if (recv_all(slot->tcp_conn_fd, &vhdr, sizeof(vhdr)) != (ssize_t)sizeof(vhdr)) {
1682 avx_socket_close(slot->tcp_conn_fd);
1683 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1684 slot->connected = false;
1685 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1686 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1687 }
1688 avx_mutex_unlock(&slot->lock);
1689 return OAVX_FRAME_TYPE_ERROR;
1690 }
1691  
1692 /* Enforce security sanity bounds on video dimensions and payload */
1693 if (vhdr.xres == 0 || vhdr.yres == 0 ||
1694 vhdr.xres > AVX_MAX_VIDEO_WIDTH || vhdr.yres > AVX_MAX_VIDEO_HEIGHT ||
1695 vhdr.payload_len > 256 * 1024 * 1024) {
1696 avx_socket_close(slot->tcp_conn_fd);
1697 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1698 slot->connected = false;
1699 avx_mutex_unlock(&slot->lock);
1700 return OAVX_FRAME_TYPE_ERROR;
1701 }
1702  
1703 if (slot->video_buf_size < vhdr.payload_len) {
1704 uint8_t* new_buf = (uint8_t*)realloc(slot->video_buf, vhdr.payload_len);
1705 if (!new_buf) {
1706 avx_mutex_unlock(&slot->lock);
1707 return OAVX_FRAME_TYPE_ERROR;
1708 }
1709 slot->video_buf = new_buf;
1710 slot->video_buf_size = vhdr.payload_len;
1711 }
1712  
1713 if (recv_all(slot->tcp_conn_fd, slot->video_buf, vhdr.payload_len) != (ssize_t)vhdr.payload_len) {
1714 avx_socket_close(slot->tcp_conn_fd);
1715 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1716 slot->connected = false;
1717 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1718 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1719 }
1720 avx_mutex_unlock(&slot->lock);
1721 return OAVX_FRAME_TYPE_ERROR;
1722 }
1723  
1724 /* Check if incoming frame is compressed (SpeedHQ, H.264, HEVC, AV1) */
1725 bool is_compressed = avx_rx_is_compressed_video_fourcc(vhdr.fourcc);
1726  
1727 if (!is_compressed) {
1728 uint64_t min_raw = avx_get_raw_video_min_size(vhdr.fourcc, vhdr.xres, vhdr.yres);
1729 if (min_raw > 0 && (uint64_t)vhdr.payload_len < min_raw) {
1730 /* Corrupt or truncated raw video payload; drop connection */
1731 avx_socket_close(slot->tcp_conn_fd);
1732 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1733 slot->connected = false;
1734 avx_mutex_unlock(&slot->lock);
1735 return OAVX_FRAME_TYPE_ERROR;
1736 }
1737 }
1738  
1739 /* Telemetry tracking for video */
1740 size_t v_wire = sizeof(magic) + sizeof(vhdr) + vhdr.payload_len;
1741 avx_recv_update_video_telemetry_locked(
1742 slot, vhdr.fourcc, vhdr.xres, vhdr.yres,
1743 vhdr.frame_rate_n, vhdr.frame_rate_d,
1744 v_wire, avx_time_ns());
1745  
1746 slot->perf.video_frames++;
1747 oavx_color_format_e color_fmt = slot->color_format;
1748 const char *metadata_str = slot->last_video_metadata[0] ? slot->last_video_metadata : NULL;
1749 avx_video_decoder_t *vdec = NULL;
1750 if (is_compressed && p_video_data &&
1751 color_fmt != OAVX_COLOR_FORMAT_FASTEST &&
1752 color_fmt != OAVX_COLOR_FORMAT_COMPRESSED_V1) {
1753 vdec = avx_rx_ensure_video_decoder_locked(slot, vhdr.fourcc, vhdr.xres, vhdr.yres);
1754 }
1755 slot->decoding_video = true;
1756 avx_mutex_unlock(&slot->lock);
1757  
1758 oavx_frame_type_t ft = avx_rx_deliver_video_frame(
1759 slot, vdec, color_fmt, is_compressed, metadata_str,
1760 vhdr.fourcc, vhdr.xres, vhdr.yres,
1761 vhdr.frame_rate_n, vhdr.frame_rate_d, vhdr.timecode,
1762 slot->video_buf, vhdr.payload_len, p_video_data);
1763  
1764 avx_mutex_lock(&slot->lock);
1765 slot->decoding_video = false;
1766 avx_mutex_unlock(&slot->lock);
1767 return ft;
1768 }
1769 else if (magic == slot->wire_profile.magic_audio ||
1770 (slot->wire_profile.compat_magic_audio && magic == slot->wire_profile.compat_magic_audio)) {
1771 AVX_PACKED_START
1772 struct {
1773 int32_t sample_rate;
1774 int32_t channels;
1775 int32_t samples;
1776 int64_t timecode;
1777 uint32_t payload_len;
1778 } AVX_PACKED ahdr;
1779 AVX_PACKED_END
1780  
1781 if (recv_all(slot->tcp_conn_fd, &ahdr, sizeof(ahdr)) != (ssize_t)sizeof(ahdr)) {
1782 avx_socket_close(slot->tcp_conn_fd);
1783 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1784 slot->connected = false;
1785 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1786 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1787 }
1788 avx_mutex_unlock(&slot->lock);
1789 return OAVX_FRAME_TYPE_ERROR;
1790 }
1791  
1792 /* Enforce security sanity bounds on audio channels, samples, and payload */
1793 if (ahdr.channels <= 0 || ahdr.channels > 64 || ahdr.samples < 0 || ahdr.samples > 1920000 ||
1794 ahdr.payload_len > 16 * 1024 * 1024 ||
1795 (uint64_t)ahdr.channels * (uint64_t)ahdr.samples * sizeof(float) > (uint64_t)ahdr.payload_len) {
1796 avx_socket_close(slot->tcp_conn_fd);
1797 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1798 slot->connected = false;
1799 avx_mutex_unlock(&slot->lock);
1800 return OAVX_FRAME_TYPE_ERROR;
1801 }
1802  
1803 if (slot->audio_buf_size < ahdr.payload_len) {
1804 float* new_buf = (float*)realloc(slot->audio_buf, ahdr.payload_len);
1805 if (!new_buf) {
1806 avx_mutex_unlock(&slot->lock);
1807 return OAVX_FRAME_TYPE_ERROR;
1808 }
1809 slot->audio_buf = new_buf;
1810 slot->audio_buf_size = ahdr.payload_len;
1811 }
1812  
1813 if (recv_all(slot->tcp_conn_fd, slot->audio_buf, ahdr.payload_len) != (ssize_t)ahdr.payload_len) {
1814 avx_socket_close(slot->tcp_conn_fd);
1815 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1816 slot->connected = false;
1817 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1818 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1819 }
1820 avx_mutex_unlock(&slot->lock);
1821 return OAVX_FRAME_TYPE_ERROR;
1822 }
1823  
1824 if (p_audio_data) {
1825 memset(p_audio_data, 0, sizeof(*p_audio_data));
1826 p_audio_data->sample_rate = (uint32_t)ahdr.sample_rate;
1827 p_audio_data->channels = (uint16_t)ahdr.channels;
1828 p_audio_data->frames = (uint32_t)ahdr.samples;
1829 p_audio_data->format = OAVX_AUDIO_FMT_FLT_PLANAR;
1830 p_audio_data->stride_bytes = (size_t)ahdr.samples * sizeof(float);
1831 p_audio_data->pts_ns = ahdr.timecode;
1832 p_audio_data->metadata = NULL;
1833 p_audio_data->metadata_len = 0;
1834 p_audio_data->user_ctx = NULL;
1835 p_audio_data->channel_mask = avx_audio_layout_to_mask(avx_audio_layout_from_channels((uint16_t)ahdr.channels));
1836 for (int c = 0; c < ahdr.channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1837 p_audio_data->planes[c] = (slot->audio_buf && ahdr.samples > 0)
1838 ? (slot->audio_buf + (size_t)c * ahdr.samples)
1839 : NULL;
1840 }
1841 for (int c = ahdr.channels; c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1842 p_audio_data->planes[c] = NULL;
1843 }
1844 }
1845  
1846 /* Telemetry tracking for audio */
1847 size_t a_wire = sizeof(magic) + sizeof(ahdr) + ahdr.payload_len;
1848 slot->telem.total_bytes += a_wire;
1849 slot->telem.window_bytes += a_wire;
1850 slot->last_frame_recv_ns = avx_time_ns();
1851  
1852 slot->perf.audio_frames++;
1853 avx_mutex_unlock(&slot->lock);
1854 return OAVX_FRAME_TYPE_AUDIO;
1855 }
1856 else if (magic == OAVX_WIRE_MAGIC_AUDIO_COMP) {
1857 AVX_PACKED_START
1858 struct {
1859 uint32_t codec_fourcc; /* 'OPUS' or 'ADPC' */
1860 int32_t sample_rate;
1861 int32_t channels;
1862 int32_t samples;
1863 int64_t timecode;
1864 uint32_t payload_len;
1865 } AVX_PACKED cahdr;
1866 AVX_PACKED_END
1867  
1868 if (recv_all(slot->tcp_conn_fd, &cahdr, sizeof(cahdr)) != (ssize_t)sizeof(cahdr)) {
1869 avx_socket_close(slot->tcp_conn_fd);
1870 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1871 slot->connected = false;
1872 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1873 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1874 }
1875 avx_mutex_unlock(&slot->lock);
1876 return OAVX_FRAME_TYPE_ERROR;
1877 }
1878  
1879 /* Enforce security sanity bounds on compressed audio header */
1880 if (cahdr.channels <= 0 || cahdr.channels > OAVX_MAX_AUDIO_CHANNELS || cahdr.samples < 0 || cahdr.samples > 192000 ||
1881 cahdr.payload_len == 0 || cahdr.payload_len > 16 * 1024 * 1024 ||
1882 cahdr.sample_rate <= 0 || cahdr.sample_rate > 192000) {
1883 avx_socket_close(slot->tcp_conn_fd);
1884 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1885 slot->connected = false;
1886 avx_mutex_unlock(&slot->lock);
1887 return OAVX_FRAME_TYPE_ERROR;
1888 }
1889  
1890 if (slot->decompressed_buf_size < cahdr.payload_len) {
1891 uint8_t *new_buf = (uint8_t*)realloc(slot->decompressed_buf, cahdr.payload_len);
1892 if (!new_buf) {
1893 avx_mutex_unlock(&slot->lock);
1894 return OAVX_FRAME_TYPE_ERROR;
1895 }
1896 slot->decompressed_buf = new_buf;
1897 slot->decompressed_buf_size = cahdr.payload_len;
1898 }
1899  
1900 if (recv_all(slot->tcp_conn_fd, slot->decompressed_buf, cahdr.payload_len) != (ssize_t)cahdr.payload_len) {
1901 avx_socket_close(slot->tcp_conn_fd);
1902 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1903 slot->connected = false;
1904 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1905 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1906 }
1907 avx_mutex_unlock(&slot->lock);
1908 return OAVX_FRAME_TYPE_ERROR;
1909 }
1910  
1911 oavx_frame_type_t ft = avx_rx_process_compressed_audio(
1912 slot, cahdr.codec_fourcc, cahdr.sample_rate, cahdr.channels,
1913 cahdr.samples, cahdr.timecode, cahdr.payload_len,
1914 slot->decompressed_buf, p_audio_data);
1915  
1916 /* Telemetry tracking for audio */
1917 size_t a_wire = sizeof(magic) + sizeof(cahdr) + cahdr.payload_len;
1918 slot->telem.total_bytes += a_wire;
1919 slot->telem.window_bytes += a_wire;
1920 slot->last_frame_recv_ns = avx_time_ns();
1921  
1922 avx_mutex_unlock(&slot->lock);
1923 return ft;
1924 }
1925 else if (magic == slot->wire_profile.magic_metadata ||
1926 (slot->wire_profile.compat_magic_metadata && magic == slot->wire_profile.compat_magic_metadata)) {
1927 AVX_PACKED_START
1928 struct {
1929 int64_t timecode;
1930 uint32_t payload_len;
1931 } AVX_PACKED mhdr;
1932 AVX_PACKED_END
1933  
1934 if (recv_all(slot->tcp_conn_fd, &mhdr, sizeof(mhdr)) != (ssize_t)sizeof(mhdr)) {
1935 avx_socket_close(slot->tcp_conn_fd);
1936 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1937 slot->connected = false;
1938 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1939 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1940 }
1941 avx_mutex_unlock(&slot->lock);
1942 return OAVX_FRAME_TYPE_ERROR;
1943 }
1944  
1945 /* Enforce security sanity bounds on metadata payload */
1946 if (mhdr.payload_len > 16 * 1024 * 1024) {
1947 avx_socket_close(slot->tcp_conn_fd);
1948 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1949 slot->connected = false;
1950 avx_mutex_unlock(&slot->lock);
1951 return OAVX_FRAME_TYPE_ERROR;
1952 }
1953  
1954 if (slot->metadata_buf_size < mhdr.payload_len + 1) {
1955 char* new_buf = (char*)realloc(slot->metadata_buf, mhdr.payload_len + 1);
1956 if (!new_buf) {
1957 avx_mutex_unlock(&slot->lock);
1958 return OAVX_FRAME_TYPE_ERROR;
1959 }
1960 slot->metadata_buf = new_buf;
1961 slot->metadata_buf_size = mhdr.payload_len + 1;
1962 }
1963  
1964 if (recv_all(slot->tcp_conn_fd, slot->metadata_buf, mhdr.payload_len) != (ssize_t)mhdr.payload_len) {
1965 avx_socket_close(slot->tcp_conn_fd);
1966 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
1967 slot->connected = false;
1968 if (slot->has_failover && !slot->is_on_failover && slot->failover_url[0] != '\0') {
1969 avx_rx_execute_failover(slot, "FAILOVER TRIGGERED (SOCKET DISCONNECT)");
1970 }
1971 avx_mutex_unlock(&slot->lock);
1972 return OAVX_FRAME_TYPE_ERROR;
1973 }
1974 slot->metadata_buf[mhdr.payload_len] = '\0';
1975 snprintf(slot->last_video_metadata, sizeof(slot->last_video_metadata), "%s", slot->metadata_buf);
1976  
1977 /* Inspect XML metadata for PTZ and Recording status updates */
1978 if (strstr(slot->metadata_buf, "record_status") != NULL) {
1979 const char* rec = strstr(slot->metadata_buf, "recording=\"");
1980 if (rec) {
1981 slot->is_recording = (strncmp(rec + 11, "true", 4) == 0);
1982 }
1983 const char* fn = strstr(slot->metadata_buf, "filename=\"");
1984 if (fn) {
1985 const char* end = strchr(fn + 10, '\"');
1986 if (end) {
1987 size_t flen = (size_t)(end - (fn + 10));
1988 if (flen >= sizeof(slot->current_recording_filename)) flen = sizeof(slot->current_recording_filename) - 1;
1989 strncpy(slot->current_recording_filename, fn + 10, flen);
1990 slot->current_recording_filename[flen] = '\0';
1991 }
1992 }
1993 const char* err = strstr(slot->metadata_buf, "error=\"");
1994 if (err) {
1995 const char* end = strchr(err + 7, '\"');
1996 if (end) {
1997 size_t elen = (size_t)(end - (err + 7));
1998 if (elen >= sizeof(slot->current_recording_error)) elen = sizeof(slot->current_recording_error) - 1;
1999 strncpy(slot->current_recording_error, err + 7, elen);
2000 slot->current_recording_error[elen] = '\0';
2001 }
2002 }
2003 }
2004 if (strstr(slot->metadata_buf, "web_control") != NULL) {
2005 const char* u = strstr(slot->metadata_buf, "url=\"");
2006 if (u) {
2007 const char* end = strchr(u + 5, '\"');
2008 if (end) {
2009 size_t ulen = (size_t)(end - (u + 5));
2010 if (ulen >= sizeof(slot->web_control_url)) ulen = sizeof(slot->web_control_url) - 1;
2011 strncpy(slot->web_control_url, u + 5, ulen);
2012 slot->web_control_url[ulen] = '\0';
2013 }
2014 }
2015 }
2016 if (strstr(slot->metadata_buf, "failover") != NULL) {
2017 avx_rx_parse_failover_metadata(slot, slot->metadata_buf);
2018 }
2019 avx_rx_parse_tally_metadata_locked(slot, slot->metadata_buf);
2020  
2021 if (metadata) {
2022 metadata->length = mhdr.payload_len;
2023 metadata->pts_ns = mhdr.timecode;
2024 metadata->data = slot->metadata_buf;
2025 }
2026  
2027 avx_trace_packet("[RX]", "AVX METADATA FRAME", slot->metadata_buf, mhdr.payload_len);
2028  
2029 /* Telemetry tracking for metadata */
2030 size_t m_wire = sizeof(magic) + sizeof(mhdr) + mhdr.payload_len;
2031 slot->telem.total_bytes += m_wire;
2032 slot->telem.window_bytes += m_wire;
2033 slot->last_frame_recv_ns = avx_time_ns();
2034  
2035 slot->perf.metadata_frames++;
2036 avx_mutex_unlock(&slot->lock);
2037 return OAVX_FRAME_TYPE_METADATA;
2038 }
2039  
2040 avx_mutex_unlock(&slot->lock);
2041 return OAVX_FRAME_TYPE_NONE;
2042 }
2043  
2044 /*
2045 * Releases video frame back to receiver instance. Buffers are reused
2046 * internally for subsequent frames; caller must not use data after release.
2047 */
2048 void avx_rx_free_video(avx_rx_instance_t p_instance, const oavx_video_frame_t* p_video_data) {
2049 (void)p_instance;
2050 (void)p_video_data;
2051 /* In openavx, video buffer memory is reused inside the receiver instance for zero allocations */
2052 }
2053  
2054 /* Releases audio frame back to receiver internal buffer pool. */
2055 void avx_rx_free_audio(avx_rx_instance_t p_instance, const oavx_audio_frame_t* p_audio_data) {
2056 (void)p_instance;
2057 (void)p_audio_data;
2058 /* Reused inside receiver instance */
2059 }
2060  
2061 void avx_rx_free_metadata(avx_rx_instance_t p_instance, const oavx_metadata_frame_t* metadata) {
2062 (void)p_instance;
2063 (void)metadata;
2064 }
2065  
2066 bool avx_rx_send_metadata(avx_rx_instance_t p_instance, const oavx_metadata_frame_t* metadata) {
2067 if (!p_instance || !metadata || !metadata->data) return false;
2068 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2069  
2070 avx_mutex_lock(&slot->lock);
2071 if (!slot->connected || slot->tcp_conn_fd == AVX_INVALID_SOCKET) {
2072 avx_mutex_unlock(&slot->lock);
2073 return false;
2074 }
2075  
2076 size_t len = metadata->length > 0 ? metadata->length : strlen(metadata->data);
2077  
2078 AVX_PACKED_START
2079 struct {
2080 uint32_t magic;
2081 int64_t timecode;
2082 uint32_t payload_len;
2083 } AVX_PACKED hdr;
2084 AVX_PACKED_END
2085  
2086 hdr.magic = slot->wire_profile.magic_metadata;
2087 hdr.timecode = metadata->pts_ns;
2088 hdr.payload_len = (uint32_t)len;
2089  
2090 ssize_t ret1 = send(slot->tcp_conn_fd, (const char*)&hdr, sizeof(hdr), MSG_NOSIGNAL);
2091 ssize_t ret2 = send(slot->tcp_conn_fd, (const char*)metadata->data, len, MSG_NOSIGNAL);
2092  
2093 bool ok = (ret1 == (ssize_t)sizeof(hdr) && ret2 == (ssize_t)len);
2094 if (ok) {
2095 avx_trace_packet("[TX]", "AVX METADATA (UPSTREAM)", metadata->data, len);
2096 }
2097 avx_mutex_unlock(&slot->lock);
2098 return ok;
2099 }
2100  
2101 bool avx_rx_set_tally(avx_rx_instance_t p_instance, const oavx_tally_t* p_tally) {
2102 if (!p_instance || !p_tally) return false;
2103 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2104 char tally_xml[256];
2105 int len = snprintf(tally_xml, sizeof(tally_xml),
2106 "<%s on_program=\"%s\" on_preview=\"%s\" on_recording=\"%s\"/>\n",
2107 slot->wire_profile.tally_tag ? slot->wire_profile.tally_tag : OAVX_WIRE_TALLY_TAG,
2108 (p_tally->flags & OAVX_TALLY_PROGRAM) ? "true" : "false",
2109 (p_tally->flags & OAVX_TALLY_PREVIEW) ? "true" : "false",
2110 (p_tally->flags & OAVX_TALLY_RECORDING) ? "true" : "false");
2111  
2112 oavx_metadata_frame_t meta = {
2113 .length = (size_t)len,
2114 .pts_ns = 0,
2115 .data = tally_xml
2116 };
2117 bool ok = avx_rx_send_metadata(p_instance, &meta);
2118 avx_mutex_lock(&slot->lock);
2119 slot->tally = *p_tally;
2120 avx_cond_broadcast(&slot->tally_cond);
2121 avx_mutex_unlock(&slot->lock);
2122 return ok;
2123 }
2124  
2125 bool avx_rx_get_tally(avx_rx_instance_t p_instance, oavx_tally_t* p_tally, uint32_t timeout_in_ms) {
2126 if (!p_instance || !p_tally) return false;
2127 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2128  
2129 avx_mutex_lock(&slot->lock);
2130 if (timeout_in_ms > 0 && !(slot->tally.flags & (OAVX_TALLY_PROGRAM | OAVX_TALLY_PREVIEW | OAVX_TALLY_RECORDING))) {
2131 avx_cond_timedwait(&slot->tally_cond, &slot->lock, timeout_in_ms);
2132 }
2133 *p_tally = slot->tally;
2134 avx_mutex_unlock(&slot->lock);
2135 return true;
2136 }
2137  
2138 bool avx_rx_get_performance(avx_rx_instance_t p_instance, oavx_performance_t* p_total, oavx_performance_t* p_dropped) {
2139 if (!p_instance) return false;
2140 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2141 avx_mutex_lock(&slot->lock);
2142 if (p_total) *p_total = slot->perf;
2143 if (p_dropped) memset(p_dropped, 0, sizeof(*p_dropped));
2144 avx_mutex_unlock(&slot->lock);
2145 return true;
2146 }
2147  
2148 bool avx_rx_get_queue(avx_rx_instance_t p_instance, oavx_queue_t* p_total) {
2149 if (!p_instance || !p_total) return false;
2150 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2151 avx_mutex_lock(&slot->lock);
2152 *p_total = slot->queue;
2153 avx_mutex_unlock(&slot->lock);
2154 return true;
2155 }
2156  
2157 OPENAVX_API bool avx_rx_get_telemetry(avx_rx_instance_t p_instance, oavx_telemetry_t *out) {
2158 if (!p_instance || !out) return false;
2159 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2160 memset(out, 0, sizeof(*out));
2161  
2162 avx_mutex_lock(&slot->lock);
2163  
2164 int64_t now_ns = avx_time_ns();
2165 float fps = slot->telem.instant_fps;
2166 float mbps = slot->telem.instant_mbps;
2167  
2168 if (slot->telem.last_frame_arrival_ns > 0 && (now_ns - slot->telem.last_frame_arrival_ns) > 1000000000LL) {
2169 fps = 0.0f;
2170 mbps = 0.0f;
2171 } else if (fps == 0.0f && slot->telem.window_frames > 0 && slot->telem.last_window_time_ns > 0) {
2172 int64_t elapsed_ns = now_ns - slot->telem.last_window_time_ns;
2173 if (elapsed_ns >= 10000000LL) {
2174 float elapsed_sec = (float)elapsed_ns / 1000000000.0f;
2175 fps = (float)slot->telem.window_frames / elapsed_sec;
2176 mbps = ((float)slot->telem.window_bytes * 8.0f) / (elapsed_sec * 1000000.0f);
2177 }
2178 }
2179  
2180 out->video_frames_total = slot->perf.video_frames;
2181 out->audio_frames_total = slot->perf.audio_frames;
2182 out->metadata_frames_total = slot->perf.metadata_frames;
2183 out->dropped_frames_total = 0;
2184 out->fps = fps;
2185 out->bitrate_mbps = mbps;
2186 out->total_wire_bytes = slot->telem.total_bytes;
2187 out->inter_frame_jitter_ms = slot->telem.inter_frame_jitter_ms;
2188 out->fourcc = slot->telem.last_fourcc;
2189 out->width = slot->telem.last_width;
2190 out->height = slot->telem.last_height;
2191 out->is_connected = slot->connected && (slot->tcp_conn_fd != AVX_INVALID_SOCKET);
2192  
2193 if (slot->target_url[0]) {
2194 snprintf(out->remote_endpoint, sizeof(out->remote_endpoint), "%.127s", slot->target_url);
2195 } else if (slot->target_name[0]) {
2196 snprintf(out->remote_endpoint, sizeof(out->remote_endpoint), "%.127s", slot->target_name);
2197 }
2198  
2199 avx_socket_t sock = slot->tcp_conn_fd;
2200 avx_mutex_unlock(&slot->lock);
2201  
2202 if (sock != AVX_INVALID_SOCKET) {
2203 avx_socket_get_diagnostics(sock, &out->kernel_rtt_ms, &out->tcp_retransmissions,
2204 &out->socket_send_q_bytes, &out->socket_recv_q_bytes);
2205 if (out->socket_recv_q_bytes >= 2000000) {
2206 out->congestion_level = 2;
2207 } else if (out->socket_recv_q_bytes >= 500000) {
2208 out->congestion_level = 1;
2209 } else {
2210 out->congestion_level = 0;
2211 }
2212 }
2213  
2214 return true;
2215 }
2216  
2217 void avx_rx_clear_connection_metadata(avx_rx_instance_t p_instance) {
2218 if (!p_instance) return;
2219 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2220 avx_mutex_lock(&slot->lock);
2221 slot->num_conn_metadata = 0;
2222 avx_mutex_unlock(&slot->lock);
2223 }
2224  
2225 void avx_rx_add_connection_metadata(avx_rx_instance_t p_instance, const oavx_metadata_frame_t* metadata) {
2226 if (!p_instance || !metadata || !metadata->data) return;
2227 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2228 avx_mutex_lock(&slot->lock);
2229 if (slot->num_conn_metadata < 16) {
2230 snprintf(slot->conn_metadata[slot->num_conn_metadata],
2231 sizeof(slot->conn_metadata[0]), "%s", metadata->data);
2232 slot->num_conn_metadata++;
2233 }
2234 avx_mutex_unlock(&slot->lock);
2235 }
2236  
2237 int avx_rx_get_connection_count(avx_rx_instance_t p_instance) {
2238 if (!p_instance) return 0;
2239 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2240 avx_mutex_lock(&slot->lock);
2241 int active = slot->connected ? 1 : 0;
2242 avx_mutex_unlock(&slot->lock);
2243 return active;
2244 }
2245  
2246 /*
2247 * Connects receiver to a new upstream source. Closes any existing connection,
2248 * aborts pending async handshakes, and resets video/audio decoder state.
2249 */
2250 void avx_rx_connect(avx_rx_instance_t p_instance, const oavx_endpoint_t* p_src) {
2251 if (!p_instance) return;
2252 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2253  
2254 avx_mutex_lock(&slot->lock);
2255 avx_recv_close_pending_locked(slot);
2256 if (slot->tcp_conn_fd != AVX_INVALID_SOCKET) {
2257 avx_socket_close(slot->tcp_conn_fd);
2258 slot->tcp_conn_fd = AVX_INVALID_SOCKET;
2259 }
2260 slot->connected = false;
2261 slot->is_on_failover = false;
2262 slot->last_connect_attempt_ns = 0;
2263  
2264 if (p_src) {
2265 if (p_src->name) {
2266 snprintf(slot->target_name, sizeof(slot->target_name), "%s", p_src->name);
2267 snprintf(slot->primary_name, sizeof(slot->primary_name), "%s", p_src->name);
2268 }
2269 if (p_src->address) {
2270 snprintf(slot->target_url, sizeof(slot->target_url), "%s", p_src->address);
2271 snprintf(slot->primary_url, sizeof(slot->primary_url), "%s", p_src->address);
2272 }
2273 slot->target_source.name = slot->target_name;
2274 slot->target_source.address = slot->target_url;
2275 avx_recv_try_connect(slot);
2276 }
2277 avx_mutex_unlock(&slot->lock);
2278 }
2279  
2280 void avx_rx_set_failover(avx_rx_instance_t p_instance, const oavx_endpoint_t* p_failover_source) {
2281 if (!p_instance) return;
2282 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2283 avx_mutex_lock(&slot->lock);
2284 if (p_failover_source && (p_failover_source->address != NULL || p_failover_source->name != NULL)) {
2285 if (p_failover_source->name) {
2286 snprintf(slot->failover_name, sizeof(slot->failover_name), "%s", p_failover_source->name);
2287 } else {
2288 slot->failover_name[0] = '\0';
2289 }
2290 if (p_failover_source->address) {
2291 snprintf(slot->failover_url, sizeof(slot->failover_url), "%s", p_failover_source->address);
2292 } else {
2293 slot->failover_url[0] = '\0';
2294 }
2295 slot->has_failover = (slot->failover_url[0] != '\0' || slot->failover_name[0] != '\0');
2296 } else {
2297 slot->has_failover = false;
2298 slot->failover_name[0] = '\0';
2299 slot->failover_url[0] = '\0';
2300 }
2301 avx_mutex_unlock(&slot->lock);
2302 }
2303  
2304 bool avx_rx_is_on_failover(avx_rx_instance_t p_instance) {
2305 if (!p_instance) return false;
2306 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2307 avx_mutex_lock(&slot->lock);
2308 bool on_failover = slot->is_on_failover;
2309 avx_mutex_unlock(&slot->lock);
2310 return on_failover;
2311 }
2312  
2313 void avx_rx_set_failover_timeout(avx_rx_instance_t p_instance, uint32_t timeout_ms) {
2314 if (!p_instance) return;
2315 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2316 avx_mutex_lock(&slot->lock);
2317 slot->failover_timeout_ms = timeout_ms;
2318 avx_mutex_unlock(&slot->lock);
2319 }
2320  
2321 void avx_rx_set_auto_revert(avx_rx_instance_t p_instance, bool auto_revert, uint32_t hold_time_ms) {
2322 if (!p_instance) return;
2323 avx_recv_ctx_t* slot = (avx_recv_ctx_t*)p_instance;
2324 avx_mutex_lock(&slot->lock);
2325 slot->auto_revert = auto_revert;
2326 slot->revert_hold_ms = hold_time_ms ? hold_time_ms : 3000;
2327 avx_mutex_unlock(&slot->lock);
2328 }
2329  
2330 /*
2331 * Transmits upstream transport/codec profile request (e.g. "wan" for H.264
2332 * simulcast) to sender over active control channel.
2333 */
2334 OPENAVX_API bool avx_rx_request_profile(avx_rx_instance_t p_instance, const char *profile) {
2335 if (!p_instance || !profile) return false;
2336 avx_recv_ctx_t *slot = (avx_recv_ctx_t*)p_instance;
2337 avx_mutex_lock(&slot->lock);
2338 if (slot->tcp_conn_fd == AVX_INVALID_SOCKET || !slot->connected) {
2339 avx_mutex_unlock(&slot->lock);
2340 return false;
2341 }
2342  
2343 char codecs_str[64] = "";
2344 if (avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_AV01)) strncat(codecs_str, "av1,", sizeof(codecs_str) - strlen(codecs_str) - 1);
2345 if (avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_HEVC)) strncat(codecs_str, "hevc,", sizeof(codecs_str) - strlen(codecs_str) - 1);
2346 if (avx_video_decoder_has_backend(OAVX_FOURCC_VIDEO_TYPE_H264)) strncat(codecs_str, "h264,", sizeof(codecs_str) - strlen(codecs_str) - 1);
2347 size_t clen = strlen(codecs_str);
2348 if (clen > 0 && codecs_str[clen - 1] == ',') codecs_str[clen - 1] = '\0';
2349 if (codecs_str[0] == '\0') snprintf(codecs_str, sizeof(codecs_str), "h264");
2350  
2351 char resp[256];
2352 int rlen = snprintf(resp, sizeof(resp),
2353 "<transport mode=\"%s\" port=\"%u\" codecs=\"%s\" profile=\"%s\"/>\n",
2354 (slot->transport == OAVX_TRANSPORT_RUDP) ? "rudp" : (slot->transport == OAVX_TRANSPORT_UDP ? "udp" : "tcp"),
2355 slot->udp_port, codecs_str, profile);
2356  
2357 AVX_PACKED_START
2358 struct {
2359 uint32_t magic;
2360 int64_t timecode;
2361 uint32_t payload_len;
2362 } AVX_PACKED mhdr;
2363 AVX_PACKED_END
2364 mhdr.magic = slot->wire_profile.magic_metadata;
2365 mhdr.timecode = 0;
2366 mhdr.payload_len = (uint32_t)rlen;
2367  
2368 ssize_t s1 = send(slot->tcp_conn_fd, (const char*)&mhdr, sizeof(mhdr), MSG_NOSIGNAL);
2369 ssize_t s2 = send(slot->tcp_conn_fd, resp, rlen, MSG_NOSIGNAL);
2370 avx_mutex_unlock(&slot->lock);
2371 return (s1 == (ssize_t)sizeof(mhdr) && s2 == (ssize_t)rlen);
2372 }