Raw ↗
+ +
9a12521 fix(ci): resolve windows strcasecmp linkage and macos test failures
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 * src/avx_send.c - Stream transmitter, session coordinator, and media ingest
7 */
8  
9 #include "avx_send_internal.h"
10 #include <stdlib.h>
11 #include <string.h>
12 #ifndef _WIN32
13 #include <strings.h>
14 #endif
15 #include <stdio.h>
16 #include <time.h>
17  
18 /*
19 * Allocates transmission session slot, sets up multi-client transmit queues,
20 * discovers bind IP / network interfaces, and starts background mDNS announce.
21 */
22 OPENAVX_API avx_tx_instance_t avx_tx_create(const avx_tx_config_t* p_create_settings) {
23 avx_mutex_lock(&g_avx_state.global_lock);
24 if (!g_avx_state.initialized) {
25 avx_mutex_unlock(&g_avx_state.global_lock);
26 avx_engine_initialize();
27 avx_mutex_lock(&g_avx_state.global_lock);
28 }
29  
30 /* Initialize PCAP dump if requested via environment */
31 const char* pcap_env = getenv("OPENAVX_DUMP_PCAP");
32 if (pcap_env) {
33 avx_pcap_init(pcap_env);
34 }
35  
36 avx_send_ctx_t* slot = NULL;
37 for (int i = 0; i < AVX_MAX_SESSIONS; ++i) {
38 if (!g_avx_state.send_slots[i].in_use) {
39 slot = &g_avx_state.send_slots[i];
40 memset(slot, 0, sizeof(*slot));
41 slot->in_use = true;
42 break;
43 }
44 }
45 avx_mutex_unlock(&g_avx_state.global_lock);
46  
47 if (!slot) return NULL;
48  
49 avx_mutex_init(&slot->lock);
50 avx_cond_init(&slot->tally_cond);
51 slot->tcp_listen_fd = AVX_INVALID_SOCKET;
52 slot->tcp_client_fd = AVX_INVALID_SOCKET;
53  
54 /* Initialize multi-client slots */
55 for (int c = 0; c < AVX_MAX_CLIENTS; ++c) {
56 slot->clients[c].fd = AVX_INVALID_SOCKET;
57 slot->clients[c].connected_time_ns = 0;
58 slot->clients[c].dropped_frames = 0;
59 slot->clients[c].tally.flags = OAVX_TALLY_NONE;
60 slot->clients[c].parent_ctx = slot;
61 slot->clients[c].client_index = c;
62 slot->clients[c].tx_thread = 0;
63 slot->clients[c].tx_thread_active = false;
64 slot->clients[c].queue_head = 0;
65 slot->clients[c].queue_tail = 0;
66 slot->clients[c].queue_count = 0;
67 slot->clients[c].video_queued = 0;
68 slot->clients[c].congestion_level = 0;
69 slot->clients[c].frame_seq = 0;
70 slot->clients[c].audio_packets_sent = 0;
71 slot->clients[c].video_packets_sent = 0;
72 slot->clients[c].tcp_bytes_submitted = 0;
73 slot->clients[c].last_acked_bytes = 0;
74 slot->clients[c].rate_window_start_acked = 0;
75 slot->clients[c].rate_window_start_sub = 0;
76 slot->clients[c].rate_window_start_ns = 0;
77 slot->clients[c].rate_window_throttled = false;
78 slot->clients[c].tx_bytes_per_sec = -1.0f;
79 slot->clients[c].last_rtt_ms = 0.0f;
80 slot->clients[c].last_rtt_sample_ns = 0;
81 slot->clients[c].tx_running = false;
82 avx_mutex_init(&slot->clients[c].tx_lock);
83 avx_cond_init(&slot->clients[c].tx_cond);
84 }
85 slot->active_clients = 0;
86 slot->video_pool_next = 0;
87 for (int v = 0; v < AVX_TX_VIDEO_POOL_SIZE; ++v) {
88 memset(&slot->video_pool[v], 0, sizeof(avx_tx_video_slot_t));
89 }
90  
91 const char *group_env = getenv("OPENAVX_GROUPS");
92 const avx_config_t *cfg = avx_config_get();
93  
94 /* Resolve configurable max_clients (default 32, ceiling 64) */
95 int max_clients = AVX_DEFAULT_MAX_CLIENTS;
96 if (cfg && cfg->max_clients > 0) {
97 max_clients = cfg->max_clients;
98 }
99 const char *env_max = getenv("OPENAVX_MAX_CLIENTS");
100 if (env_max && atoi(env_max) > 0) {
101 max_clients = atoi(env_max);
102 }
103 if (p_create_settings && p_create_settings->max_connections > 0) {
104 max_clients = (int)p_create_settings->max_connections;
105 }
106 if (max_clients < 1) max_clients = 1;
107 if (max_clients > AVX_MAX_CLIENTS) max_clients = AVX_MAX_CLIENTS;
108 slot->max_clients = max_clients;
109  
110 const oavx_wire_profile_t *wp = (p_create_settings && p_create_settings->wire_profile)
111 ? p_create_settings->wire_profile : avx_wire_get_active_profile();
112 slot->wire_profile = *wp;
113 slot->port = wp->base_port ? wp->base_port : AVX_DEFAULT_PORT;
114  
115 slot->running = true;
116 slot->client_rx_running = false;
117 slot->client_rx_thread = 0;
118 slot->num_conn_metadata = 0;
119 slot->has_new_metadata = false;
120  
121 if (p_create_settings && p_create_settings->name) {
122 snprintf(slot->name, sizeof(slot->name), "%s", p_create_settings->name);
123 } else {
124 snprintf(slot->name, sizeof(slot->name), "OpenAVX (Output)");
125 }
126  
127 if (p_create_settings && p_create_settings->groups && p_create_settings->groups[0] != '\0') {
128 snprintf(slot->groups, sizeof(slot->groups), "%s", p_create_settings->groups);
129 } else if (group_env && group_env[0] != '\0') {
130 snprintf(slot->groups, sizeof(slot->groups), "%s", group_env);
131 } else if (cfg && cfg->channels_publish[0] != '\0') {
132 snprintf(slot->groups, sizeof(slot->groups), "%s", cfg->channels_publish);
133 } else {
134 snprintf(slot->groups, sizeof(slot->groups), "public");
135 }
136  
137 /* Determine configured interface or bind IP according to 4-tier precedence:
138 * 1. Explicit API setting (p_create_settings->bind_ip)
139 * 2. Environment variable (OPENAVX_BIND_IP / OPENAVX_NIC)
140 * 3. Config file setting (cfg->bind_ip)
141 * 4. Automatic local IP detection
142 */
143 const char *bind_target = NULL;
144 if (p_create_settings && p_create_settings->bind_ip && p_create_settings->bind_ip[0] != '\0') {
145 bind_target = p_create_settings->bind_ip;
146 } else {
147 const char *env_bind = getenv("OPENAVX_BIND_IP");
148 if (!env_bind || env_bind[0] == '\0') {
149 env_bind = getenv("OPENAVX_NIC");
150 }
151 if (env_bind && env_bind[0] != '\0') {
152 bind_target = env_bind;
153 } else if (cfg && cfg->bind_ip[0] != '\0') {
154 bind_target = cfg->bind_ip;
155 }
156 }
157  
158 slot->bind_ip[0] = '\0';
159 slot->advertised_ip[0] = '\0';
160  
161 if (bind_target && bind_target[0] != '\0') {
162 if (avx_net_resolve_interface_or_ip(bind_target, slot->bind_ip, sizeof(slot->bind_ip))) {
163 memcpy(slot->advertised_ip, slot->bind_ip, sizeof(slot->advertised_ip));
164 slot->advertised_ip[sizeof(slot->advertised_ip) - 1] = '\0';
165 } else {
166 oavx_log_write(OAVX_LOG_WARN, "tx",
167 "Could not resolve network interface/IP '%s', falling back to default interface",
168 bind_target);
169 slot->bind_ip[0] = '\0';
170 }
171 }
172  
173 if (slot->advertised_ip[0] == '\0') {
174 avx_net_get_default_ip(slot->advertised_ip, sizeof(slot->advertised_ip));
175 }
176  
177 slot->clock_video = p_create_settings ? p_create_settings->clock_video : true;
178 slot->clock_audio = p_create_settings ? p_create_settings->clock_audio : true;
179  
180 slot->transport = p_create_settings ? p_create_settings->transport : OAVX_TRANSPORT_TCP;
181 slot->udp_sock = AVX_INVALID_SOCKET;
182 slot->udp_port = 0;
183 slot->rudp_sender = NULL;
184 slot->nack_thread = 0;
185 slot->nack_thread_active = false;
186 slot->nack_thread_running = false;
187 slot->rate_ctl = avx_rate_controller_create(NULL);
188  
189 slot->audio_comp_mode = OAVX_AUDIO_COMPRESSION_OFF;
190 slot->audio_target_bitrate_kbps = 0;
191 slot->audio_encoder = NULL;
192 slot->audio_comp_active = false;
193 slot->audio_enc_channels = 0;
194 slot->audio_enc_sample_rate = 0;
195  
196 slot->video_encoder = NULL;
197 slot->video_enc_fourcc = 0;
198 slot->video_enc_width = 0;
199 slot->video_enc_height = 0;
200 slot->video_quality = 0;
201 slot->video_codec_fourcc = p_create_settings ? p_create_settings->video_codec_fourcc : 0;
202 slot->video_bitrate_kbps = p_create_settings ? p_create_settings->video_bitrate_kbps : 0;
203 slot->keyframe_interval = p_create_settings ? p_create_settings->keyframe_interval : 0;
204  
205 slot->wan_client_count = 0;
206 slot->wan_codec_fourcc = 0;
207 slot->wan_encoder = NULL;
208 slot->wan_enc_fourcc = 0;
209 slot->wan_enc_width = 0;
210 slot->wan_enc_height = 0;
211 slot->wan_enc_bitrate_kbps = 0;
212  
213 slot->rtsp_server = NULL;
214 slot->web_server = NULL;
215  
216 if (slot->transport == OAVX_TRANSPORT_RUDP || slot->transport == OAVX_TRANSPORT_UDP) {
217 uint16_t udp_p = slot->port + 1;
218 const char *bind_addr = (slot->bind_ip[0] != '\0') ? slot->bind_ip : NULL;
219 slot->udp_sock = avx_udp_create_socket_bind(bind_addr, udp_p, true);
220 if (slot->udp_sock == AVX_INVALID_SOCKET) {
221 for (uint16_t alt = slot->port + 2; alt <= slot->port + 30; ++alt) {
222 slot->udp_sock = avx_udp_create_socket_bind(bind_addr, alt, true);
223 if (slot->udp_sock != AVX_INVALID_SOCKET) {
224 udp_p = alt;
225 break;
226 }
227 }
228 }
229 if (slot->udp_sock != AVX_INVALID_SOCKET) {
230 slot->udp_port = udp_p;
231 if (slot->transport == OAVX_TRANSPORT_RUDP) {
232 slot->rudp_sender = avx_udp_rudp_sender_create(slot->udp_sock, 64);
233 if (slot->rudp_sender) {
234 if (slot->rate_ctl) {
235 avx_rate_controller_apply_to_sender(slot->rate_ctl, slot->rudp_sender);
236 }
237 if (p_create_settings && p_create_settings->passphrase) {
238 avx_udp_rudp_sender_set_passphrase((avx_udp_rudp_sender_t*)slot->rudp_sender,
239 p_create_settings->passphrase,
240 p_create_settings->name);
241 }
242 slot->nack_thread_running = true;
243 if (avx_thread_create(&slot->nack_thread, avx_send_nack_service_worker, slot) == 0) {
244 slot->nack_thread_active = true;
245 }
246 }
247 }
248 }
249 }
250  
251 /* Start TCP Server */
252 avx_send_start_listener(slot);
253  
254 if (strchr(slot->advertised_ip, ':')) {
255 snprintf(slot->url, sizeof(slot->url), "[%s]:%u", slot->advertised_ip, slot->port);
256 } else {
257 snprintf(slot->url, sizeof(slot->url), "%s:%u", slot->advertised_ip, slot->port);
258 }
259 slot->source_info.name = slot->name;
260 slot->source_info.address = slot->url;
261 slot->source_info.port = slot->port;
262 slot->source_info.group = slot->groups;
263  
264 /* Broadcast source via mDNS (UDP 5353) with specific egress binding */
265 slot->last_mdns_broadcast_ns = avx_time_ns();
266 avx_mdns_broadcast_source_ex(slot->name, slot->port, slot->advertised_ip);
267  
268 /* Register with Discovery Server(s) if configured */
269 slot->discovery_server_sock = AVX_INVALID_SOCKET;
270 slot->num_discovery_server_socks = 0;
271 for (int s = 0; s < 8; ++s) {
272 slot->discovery_server_socks[s] = AVX_INVALID_SOCKET;
273 }
274 const char *ds_env = getenv("OPENAVX_DISCOVERY_SERVER");
275 const char *ds_targets = (ds_env && ds_env[0] != '\0') ? ds_env : (cfg ? cfg->discovery_servers : "");
276  
277 if (ds_targets && ds_targets[0] != '\0') {
278 char my_url[256];
279 if (strchr(slot->advertised_ip, ':')) {
280 snprintf(my_url, sizeof(my_url), "[%s]:%u", slot->advertised_ip, slot->port);
281 } else {
282 snprintf(my_url, sizeof(my_url), "%s:%u", slot->advertised_ip, slot->port);
283 }
284  
285 char targets_copy[512];
286 snprintf(targets_copy, sizeof(targets_copy), "%s", ds_targets);
287  
288 char *saveptr = NULL;
289 char *token = strtok_r(targets_copy, ",; \t", &saveptr);
290 while (token && slot->num_discovery_server_socks < (int)(sizeof(slot->discovery_server_socks)/sizeof(slot->discovery_server_socks[0]))) {
291 char srv_ip[64] = "127.0.0.1";
292 uint16_t srv_port = AVX_DISCOVERY_SERVER_DEFAULT_PORT;
293 char *colon = strchr(token, ':');
294 if (colon) {
295 *colon = '\0';
296 srv_port = (uint16_t)atoi(colon + 1);
297 }
298 snprintf(srv_ip, sizeof(srv_ip), "%s", token);
299  
300 int fd = avx_discovery_client_register(srv_ip, srv_port, slot->name, my_url, slot->groups);
301 if (fd >= 0) {
302 slot->discovery_server_socks[slot->num_discovery_server_socks++] = (avx_socket_t)fd;
303 }
304 token = strtok_r(NULL, ",; \t", &saveptr);
305 }
306 if (slot->num_discovery_server_socks > 0) {
307 slot->discovery_server_sock = slot->discovery_server_socks[0];
308 }
309 }
310  
311 return (avx_tx_instance_t)slot;
312 }
313  
314 OPENAVX_API void avx_tx_destroy(avx_tx_instance_t p_instance) {
315 if (!p_instance) return;
316 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
317  
318 avx_send_stop_listener(slot);
319 avx_mutex_destroy(&slot->lock);
320 avx_cond_destroy(&slot->tally_cond);
321  
322 for (int c = 0; c < AVX_MAX_CLIENTS; ++c) {
323 avx_mutex_destroy(&slot->clients[c].tx_lock);
324 avx_cond_destroy(&slot->clients[c].tx_cond);
325 }
326  
327 for (int v = 0; v < AVX_TX_VIDEO_POOL_SIZE; ++v) {
328 if (slot->video_pool[v].payload) {
329 free(slot->video_pool[v].payload);
330 slot->video_pool[v].payload = NULL;
331 }
332 if (slot->video_pool[v].metadata_buf) {
333 free(slot->video_pool[v].metadata_buf);
334 slot->video_pool[v].metadata_buf = NULL;
335 }
336 }
337  
338 for (int i = 0; i < slot->num_discovery_server_socks; ++i) {
339 if (slot->discovery_server_socks[i] != AVX_INVALID_SOCKET) {
340 avx_socket_close(slot->discovery_server_socks[i]);
341 slot->discovery_server_socks[i] = AVX_INVALID_SOCKET;
342 }
343 }
344 slot->num_discovery_server_socks = 0;
345  
346 if (slot->discovery_server_sock != AVX_INVALID_SOCKET) {
347 avx_socket_close(slot->discovery_server_sock);
348 slot->discovery_server_sock = AVX_INVALID_SOCKET;
349 }
350  
351 if (slot->compressed_buf) {
352 free(slot->compressed_buf);
353 slot->compressed_buf = NULL;
354 slot->compressed_buf_size = 0;
355 }
356  
357 if (slot->nack_thread_active) {
358 slot->nack_thread_running = false;
359 avx_thread_join(slot->nack_thread);
360 slot->nack_thread_active = false;
361 }
362 if (slot->rudp_sender) {
363 avx_udp_rudp_sender_destroy((avx_udp_rudp_sender_t*)slot->rudp_sender);
364 slot->rudp_sender = NULL;
365 }
366 if (slot->udp_sock != AVX_INVALID_SOCKET) {
367 avx_socket_close(slot->udp_sock);
368 slot->udp_sock = AVX_INVALID_SOCKET;
369 }
370  
371 if (slot->audio_encoder) {
372 avx_audio_encoder_destroy(slot->audio_encoder);
373 slot->audio_encoder = NULL;
374 }
375  
376 if (slot->video_encoder) {
377 avx_video_encoder_destroy(slot->video_encoder);
378 slot->video_encoder = NULL;
379 }
380  
381 if (slot->wan_encoder) {
382 avx_video_encoder_destroy(slot->wan_encoder);
383 slot->wan_encoder = NULL;
384 }
385  
386 if (slot->rate_ctl) {
387 avx_rate_controller_destroy(slot->rate_ctl);
388 slot->rate_ctl = NULL;
389 }
390  
391 if (slot->rtsp_server) {
392 avx_rtsp_server_destroy((avx_rtsp_server_t*)slot->rtsp_server);
393 slot->rtsp_server = NULL;
394 }
395  
396 if (slot->web_server) {
397 avx_web_server_destroy((avx_web_server_t*)slot->web_server);
398 slot->web_server = NULL;
399 }
400  
401 avx_mutex_lock(&g_avx_state.global_lock);
402 slot->in_use = false;
403 avx_mutex_unlock(&g_avx_state.global_lock);
404 }
405  
406 static void avx_pack_video_frame(const oavx_video_frame_t *src, uint8_t *dst, size_t dst_len) {
407 if (!src || !dst || src->width == 0 || src->height == 0 || dst_len == 0) return;
408 uint32_t w = src->width;
409 uint32_t h = src->height;
410 size_t s0 = src->strides[0];
411 size_t s1 = src->strides[1];
412 size_t s2 = src->strides[2];
413 const uint8_t *p0 = src->planes[0];
414 const uint8_t *p1 = src->planes[1];
415 const uint8_t *p2 = src->planes[2];
416  
417 if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 ||
418 src->fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC ||
419 src->fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01 ||
420 src->fourcc == 0x47504A4D ||
421 src->fourcc == 0x4A50474D) {
422 size_t copy_sz = (s0 > 0 && s0 <= dst_len) ? s0 : dst_len;
423 memcpy(dst, p0, copy_sz);
424 return;
425 }
426  
427 if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVY) {
428 size_t row_bytes = (size_t)w * 2;
429 if (s0 == 0 || s0 == row_bytes) {
430 size_t copy_sz = row_bytes * h;
431 if (copy_sz > dst_len) copy_sz = dst_len;
432 memcpy(dst, p0, copy_sz);
433 } else {
434 for (uint32_t y = 0; y < h; ++y) {
435 memcpy(dst + (size_t)y * row_bytes, p0 + y * s0, row_bytes);
436 }
437 }
438 return;
439 }
440  
441 if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
442 size_t yuv_row = (size_t)w * 2;
443 size_t src_yuv_stride = (s0 > 0) ? s0 : yuv_row;
444 for (uint32_t y = 0; y < h; ++y) {
445 memcpy(dst + (size_t)y * yuv_row, p0 + y * src_yuv_stride, yuv_row);
446 }
447 uint8_t *alpha_dst = dst + (size_t)w * h * 2;
448 const uint8_t *alpha_src = p1 ? p1 : (p0 + (size_t)h * src_yuv_stride);
449 size_t src_alpha_stride = (s1 > 0) ? s1 : (size_t)w;
450 for (uint32_t y = 0; y < h; ++y) {
451 memcpy(alpha_dst + (size_t)y * w, alpha_src + y * src_alpha_stride, w);
452 }
453 } else if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
454 size_t row_bytes = (size_t)w * 2;
455 size_t src_y_stride = (s0 > 0) ? s0 : row_bytes;
456 for (uint32_t y = 0; y < h; ++y) {
457 memcpy(dst + (size_t)y * row_bytes, p0 + y * src_y_stride, row_bytes);
458 }
459 uint8_t *uv_dst = dst + (size_t)w * h * 2;
460 const uint8_t *uv_src = p1 ? p1 : (p0 + (size_t)h * src_y_stride);
461 size_t src_uv_stride = (s1 > 0) ? s1 : row_bytes;
462 for (uint32_t y = 0; y < h; ++y) {
463 memcpy(uv_dst + (size_t)y * row_bytes, uv_src + y * src_uv_stride, row_bytes);
464 }
465 } else if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_PA16) {
466 size_t row_bytes = (size_t)w * 2;
467 size_t src_y_stride = (s0 > 0) ? s0 : row_bytes;
468 for (uint32_t y = 0; y < h; ++y) {
469 memcpy(dst + (size_t)y * row_bytes, p0 + y * src_y_stride, row_bytes);
470 }
471 uint8_t *uv_dst = dst + (size_t)w * h * 2;
472 const uint8_t *uv_src = p1 ? p1 : (p0 + (size_t)h * src_y_stride);
473 size_t src_uv_stride = (s1 > 0) ? s1 : row_bytes;
474 for (uint32_t y = 0; y < h; ++y) {
475 memcpy(uv_dst + (size_t)y * row_bytes, uv_src + y * src_uv_stride, row_bytes);
476 }
477 uint8_t *a_dst = dst + (size_t)w * h * 4;
478 const uint8_t *a_src = p2 ? p2 : (uv_src + (size_t)h * src_uv_stride);
479 size_t src_a_stride = (s2 > 0) ? s2 : row_bytes;
480 for (uint32_t y = 0; y < h; ++y) {
481 memcpy(a_dst + (size_t)y * row_bytes, a_src + y * src_a_stride, row_bytes);
482 }
483 } else if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12) {
484 size_t y_row = (size_t)w;
485 size_t src_y_stride = (s0 > 0) ? s0 : y_row;
486 for (uint32_t y = 0; y < h; ++y) {
487 memcpy(dst + (size_t)y * y_row, p0 + y * src_y_stride, y_row);
488 }
489 uint8_t *uv_dst = dst + (size_t)w * h;
490 const uint8_t *uv_src = p1 ? p1 : (p0 + (size_t)h * src_y_stride);
491 size_t src_uv_stride = (s1 > 0) ? s1 : y_row;
492 uint32_t h2 = (h + 1) / 2;
493 for (uint32_t y = 0; y < h2; ++y) {
494 memcpy(uv_dst + (size_t)y * y_row, uv_src + y * src_uv_stride, y_row);
495 }
496 } else if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 || src->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
497 size_t y_row = (size_t)w;
498 size_t src_y_stride = (s0 > 0) ? s0 : y_row;
499 for (uint32_t y = 0; y < h; ++y) {
500 memcpy(dst + (size_t)y * y_row, p0 + y * src_y_stride, y_row);
501 }
502 uint32_t w2 = (w + 1) / 2;
503 uint32_t h2 = (h + 1) / 2;
504 uint8_t *u_dst = dst + (size_t)w * h;
505 uint8_t *v_dst = u_dst + (size_t)w2 * h2;
506 const uint8_t *u_src = p1 ? p1 : (p0 + (size_t)h * src_y_stride);
507 size_t src_u_stride = (s1 > 0) ? s1 : w2;
508 const uint8_t *v_src = p2 ? p2 : (u_src + (size_t)h2 * src_u_stride);
509 size_t src_v_stride = (s2 > 0) ? s2 : w2;
510 if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
511 uint8_t *tmp = u_dst; u_dst = v_dst; v_dst = tmp;
512 }
513 for (uint32_t y = 0; y < h2; ++y) {
514 memcpy(u_dst + (size_t)y * w2, u_src + y * src_u_stride, w2);
515 memcpy(v_dst + (size_t)y * w2, v_src + y * src_v_stride, w2);
516 }
517 } else {
518 size_t bpp = 2;
519 if (src->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA || src->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
520 src->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX || src->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
521 bpp = 4;
522 }
523 size_t row_bytes = (size_t)w * bpp;
524 if (s0 == 0 || s0 == row_bytes) {
525 size_t copy_sz = row_bytes * h;
526 if (copy_sz > dst_len) copy_sz = dst_len;
527 memcpy(dst, p0, copy_sz);
528 } else {
529 for (uint32_t y = 0; y < h; ++y) {
530 memcpy(dst + (size_t)y * row_bytes, p0 + y * s0, row_bytes);
531 }
532 }
533 }
534 }
535  
536 /*
537 * Acquires a slot from circulating video pool (AVX_TX_VIDEO_POOL_SIZE). Encodes
538 * frame once (primary codec and optional WAN simulcast), then distributes
539 * references to active client queues. Drops frame if all pool slots are in-flight.
540 */
541 OPENAVX_API void avx_tx_send_video(avx_tx_instance_t p_instance, const oavx_video_frame_t* p_video_data) {
542 if (!p_instance || !p_video_data) return;
543 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
544  
545 avx_mutex_lock(&slot->lock);
546 slot->video_frames_sent++;
547  
548 int rtsp_clients = slot->rtsp_server ? avx_rtsp_server_get_client_count((avx_rtsp_server_t*)slot->rtsp_server) : 0;
549 int web_clients = slot->web_server ? avx_web_server_get_client_count((avx_web_server_t*)slot->web_server) : 0;
550  
551 if ((slot->active_clients > 0 || rtsp_clients > 0 || web_clients > 0) && p_video_data->planes[0]) {
552 /* Find free slot in shared circulating video pool */
553 int pool_idx = -1;
554 for (int i = 0; i < AVX_TX_VIDEO_POOL_SIZE; ++i) {
555 int candidate = (slot->video_pool_next + i) % AVX_TX_VIDEO_POOL_SIZE;
556 if (slot->video_pool[candidate].refcount == 0 && !slot->video_pool[candidate].in_flight) {
557 pool_idx = candidate;
558 slot->video_pool[candidate].in_flight = true;
559 slot->video_pool_next = (candidate + 1) % AVX_TX_VIDEO_POOL_SIZE;
560 break;
561 }
562 }
563  
564 if (pool_idx < 0) {
565 /* All pool slots are referenced in active queues; drop frame to prevent stalling caller */
566 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
567 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
568 slot->clients[i].dropped_frames++;
569 }
570 }
571 avx_mutex_unlock(&slot->lock);
572 return;
573 }
574  
575 /* Check whether input is already compressed passthrough */
576 bool is_compressed_passthrough = (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_H264 ||
577 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_HEVC ||
578 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_AV01 ||
579 p_video_data->fourcc == 0x47504A4D ||
580 p_video_data->fourcc == 0x4A50474D);
581  
582 uint32_t target_comp_fourcc = 0;
583 if (!is_compressed_passthrough) {
584 if (slot->video_codec_fourcc != 0) {
585 target_comp_fourcc = slot->video_codec_fourcc;
586 } else if (avx_is_speedhq_fourcc((uint32_t)p_video_data->fourcc)) {
587 target_comp_fourcc = (uint32_t)p_video_data->fourcc;
588 }
589 }
590  
591 /* Snapshot settings and release slot->lock during CPU-intensive video compression
592 * so concurrent audio packets (48kHz) are enqueued without lock contention spikes */
593 avx_video_encoder_t *venc = NULL;
594 if (target_comp_fourcc != 0) {
595 uint32_t req_fourcc = target_comp_fourcc;
596 uint32_t req_w = p_video_data->width;
597 uint32_t req_h = p_video_data->height;
598 if (!slot->video_encoder ||
599 slot->video_enc_fourcc != req_fourcc ||
600 slot->video_enc_width != req_w ||
601 slot->video_enc_height != req_h) {
602 if (slot->video_encoder) {
603 avx_video_encoder_destroy(slot->video_encoder);
604 slot->video_encoder = NULL;
605 }
606 avx_video_enc_cfg_t vcfg;
607 memset(&vcfg, 0, sizeof(vcfg));
608 vcfg.fourcc = req_fourcc;
609 vcfg.width = req_w;
610 vcfg.height = req_h;
611 uint8_t eff_quality = slot->video_quality;
612 if (eff_quality == 0 && slot->rate_ctl) {
613 eff_quality = avx_rate_controller_get_quality(slot->rate_ctl);
614 }
615 vcfg.quality = eff_quality;
616 vcfg.bitrate_kbps = slot->video_bitrate_kbps;
617 vcfg.keyframe_interval = slot->keyframe_interval;
618 vcfg.fps_num = (int32_t)p_video_data->framerate.num;
619 vcfg.fps_den = (int32_t)p_video_data->framerate.den;
620 slot->video_encoder = avx_video_encoder_create(&vcfg);
621 slot->video_enc_fourcc = slot->video_encoder ? req_fourcc : 0;
622 slot->video_enc_width = slot->video_encoder ? req_w : 0;
623 slot->video_enc_height = slot->video_encoder ? req_h : 0;
624 }
625 venc = slot->video_encoder;
626 }
627  
628 /* Secondary On-Demand Hardware WAN Simulcast Encoder */
629 avx_video_encoder_t *wan_enc = NULL;
630 uint32_t wan_fourcc = 0;
631 int wan_clients = slot->wan_client_count;
632 if (wan_clients > 0 && !is_compressed_passthrough) {
633 wan_fourcc = slot->wan_codec_fourcc ? slot->wan_codec_fourcc : OAVX_FOURCC_VIDEO_TYPE_H264;
634 uint32_t req_w = p_video_data->width;
635 uint32_t req_h = p_video_data->height;
636 uint32_t wan_br_kbps = 4000;
637 if (slot->rate_ctl) {
638 wan_br_kbps = avx_rate_controller_get_target_bitrate(slot->rate_ctl) / 1000;
639 if (wan_br_kbps < 500) wan_br_kbps = 500;
640 if (wan_br_kbps > 50000) wan_br_kbps = 50000;
641 }
642 if (!slot->wan_encoder ||
643 slot->wan_enc_fourcc != wan_fourcc ||
644 slot->wan_enc_width != req_w ||
645 slot->wan_enc_height != req_h) {
646 if (slot->wan_encoder) {
647 avx_video_encoder_destroy(slot->wan_encoder);
648 slot->wan_encoder = NULL;
649 }
650 avx_video_enc_cfg_t wcfg;
651 memset(&wcfg, 0, sizeof(wcfg));
652 wcfg.fourcc = wan_fourcc;
653 wcfg.width = req_w;
654 wcfg.height = req_h;
655 wcfg.quality = 0;
656 wcfg.bitrate_kbps = wan_br_kbps;
657 wcfg.keyframe_interval = slot->keyframe_interval ? slot->keyframe_interval : 60;
658 wcfg.fps_num = (int32_t)p_video_data->framerate.num;
659 wcfg.fps_den = (int32_t)p_video_data->framerate.den;
660 slot->wan_encoder = avx_video_encoder_create(&wcfg);
661 slot->wan_enc_fourcc = slot->wan_encoder ? wan_fourcc : 0;
662 slot->wan_enc_width = slot->wan_encoder ? req_w : 0;
663 slot->wan_enc_height = slot->wan_encoder ? req_h : 0;
664 slot->wan_enc_bitrate_kbps = wan_br_kbps;
665 }
666 wan_enc = slot->wan_encoder;
667 }
668  
669 uint32_t magic_video = slot->wire_profile.magic_video;
670 uint32_t magic_metadata = slot->wire_profile.magic_metadata;
671 void *rtsp_srv = slot->rtsp_server;
672 void *web_srv = slot->web_server;
673 avx_mutex_unlock(&slot->lock);
674  
675 avx_tx_video_slot_t *vslot = &slot->video_pool[pool_idx];
676  
677 AVX_PACKED_START
678 struct {
679 uint32_t magic;
680 uint32_t xres;
681 uint32_t yres;
682 uint32_t fourcc;
683 int32_t frame_rate_n;
684 int32_t frame_rate_d;
685 int64_t timecode;
686 uint32_t payload_len;
687 } AVX_PACKED hdr;
688 AVX_PACKED_END
689  
690 size_t frame_bytes = 0;
691 uint32_t w = p_video_data->width;
692 uint32_t h = p_video_data->height;
693 size_t s0 = p_video_data->strides[0];
694  
695 if (is_compressed_passthrough) {
696 frame_bytes = s0;
697 } else if (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_P216) {
698 frame_bytes = (size_t)w * h * 4;
699 } else if (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_PA16) {
700 frame_bytes = (size_t)w * h * 6;
701 } else if (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_UYVA) {
702 frame_bytes = (size_t)w * h * 3;
703 } else if (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_NV12 ||
704 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_I420 ||
705 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_YV12) {
706 frame_bytes = (size_t)w * h * 3 / 2;
707 } else if (p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBA ||
708 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_RGBX ||
709 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRA ||
710 p_video_data->fourcc == OAVX_FOURCC_VIDEO_TYPE_BGRX) {
711 frame_bytes = (size_t)w * h * 4;
712 } else if (w > 0 && h > 0) {
713 frame_bytes = (size_t)w * h * 2; /* UYVY default */
714 } else if (s0 > 0) {
715 frame_bytes = s0;
716 }
717 uint32_t fourcc = (uint32_t)p_video_data->fourcc;
718  
719 /* Prepare per-frame metadata header if present */
720 bool has_metadata = (p_video_data->metadata && p_video_data->metadata[0] != '\0');
721 size_t mlen = 0;
722 AVX_PACKED_START
723 struct {
724 uint32_t magic;
725 int64_t timecode;
726 uint32_t payload_len;
727 } AVX_PACKED mhdr;
728 AVX_PACKED_END
729 if (has_metadata) {
730 mlen = p_video_data->metadata_len > 0 ? p_video_data->metadata_len : strlen(p_video_data->metadata);
731 mhdr.magic = magic_metadata;
732 mhdr.timecode = p_video_data->dts_ns != 0 ? p_video_data->dts_ns : p_video_data->pts_ns;
733 mhdr.payload_len = (uint32_t)mlen;
734  
735 memcpy(vslot->metadata_hdr, &mhdr, sizeof(mhdr));
736 vslot->metadata_hdr_len = sizeof(mhdr);
737  
738 if (vslot->metadata_buf) free(vslot->metadata_buf);
739 vslot->metadata_buf = (uint8_t*)malloc(mlen + 1);
740 if (vslot->metadata_buf) {
741 memcpy(vslot->metadata_buf, p_video_data->metadata, mlen);
742 vslot->metadata_buf[mlen] = '\0';
743 vslot->metadata_len = mlen;
744 } else {
745 vslot->metadata_len = 0;
746 vslot->metadata_hdr_len = 0;
747 }
748 } else {
749 if (vslot->metadata_buf) {
750 free(vslot->metadata_buf);
751 vslot->metadata_buf = NULL;
752 }
753 vslot->metadata_len = 0;
754 vslot->metadata_hdr_len = 0;
755 }
756  
757 /* If compression (H.264, HEVC, SpeedHQ) is active */
758 if (target_comp_fourcc != 0) {
759 size_t max_out = (size_t)p_video_data->width * p_video_data->height * 4;
760 if (max_out < 1048576) max_out = 1048576;
761 if (vslot->payload_capacity < max_out) {
762 uint8_t *nb = (uint8_t*)realloc(vslot->payload, max_out);
763 if (nb) {
764 vslot->payload = nb;
765 vslot->payload_capacity = max_out;
766 }
767 }
768 if (vslot->payload) {
769 size_t actual_out = 0;
770 int enc_ret = -1;
771 if (venc) {
772 bool is_kf = false;
773 enc_ret = avx_video_encoder_encode(venc, p_video_data,
774 vslot->payload, vslot->payload_capacity,
775 &actual_out, &is_kf);
776 }
777 if (enc_ret == 0 && actual_out > 0) {
778 frame_bytes = actual_out;
779 fourcc = target_comp_fourcc;
780 vslot->payload_size = actual_out;
781 } else {
782 /* Compression failed or encoder unavailable: fallback to raw packing */
783 fourcc = (uint32_t)p_video_data->fourcc;
784 if (avx_is_speedhq_fourcc(fourcc)) {
785 const uint8_t *alpha_plane = p_video_data->planes[1];
786 if (!alpha_plane && (fourcc == OAVX_FOURCC_VIDEO_TYPE_SHQ3 ||
787 fourcc == OAVX_FOURCC_VIDEO_TYPE_SHQ1 ||
788 fourcc == OAVX_FOURCC_VIDEO_TYPE_SHQ5 ||
789 fourcc == OAVX_FOURCC_VIDEO_TYPE_SHQ7 ||
790 fourcc == OAVX_FOURCC_VIDEO_TYPE_SHQ9)) {
791 alpha_plane = p_video_data->planes[0] + (size_t)p_video_data->width * p_video_data->height * 2;
792 }
793 if (alpha_plane) {
794 fourcc = (uint32_t)OAVX_FOURCC_VIDEO_TYPE_UYVA;
795 frame_bytes = (size_t)w * h * 3;
796 } else {
797 fourcc = (uint32_t)OAVX_FOURCC_VIDEO_TYPE_UYVY;
798 frame_bytes = (size_t)w * h * 2;
799 }
800 }
801 if (vslot->payload_capacity < frame_bytes) {
802 uint8_t *nb = (uint8_t*)realloc(vslot->payload, frame_bytes);
803 if (nb) {
804 vslot->payload = nb;
805 vslot->payload_capacity = frame_bytes;
806 }
807 }
808 if (vslot->payload) {
809 oavx_video_frame_t raw_frame = *p_video_data;
810 raw_frame.fourcc = (oavx_fourcc_video_type_e)fourcc;
811 avx_pack_video_frame(&raw_frame, vslot->payload, frame_bytes);
812 vslot->payload_size = frame_bytes;
813 }
814 }
815 }
816 } else {
817 /* Raw video copy into pool slot */
818 if (vslot->payload_capacity < frame_bytes) {
819 uint8_t *nb = (uint8_t*)realloc(vslot->payload, frame_bytes);
820 if (nb) {
821 vslot->payload = nb;
822 vslot->payload_capacity = frame_bytes;
823 }
824 }
825 if (vslot->payload) {
826 avx_pack_video_frame(p_video_data, vslot->payload, frame_bytes);
827 vslot->payload_size = frame_bytes;
828 }
829 }
830  
831 hdr.magic = magic_video;
832 hdr.xres = (uint32_t)p_video_data->width;
833 hdr.yres = (uint32_t)p_video_data->height;
834 hdr.fourcc = fourcc;
835 hdr.frame_rate_n = (int32_t)p_video_data->framerate.num;
836 hdr.frame_rate_d = (int32_t)p_video_data->framerate.den;
837 hdr.timecode = p_video_data->dts_ns != 0 ? p_video_data->dts_ns : p_video_data->pts_ns;
838 hdr.payload_len = (uint32_t)frame_bytes;
839  
840 memcpy(vslot->header, &hdr, sizeof(hdr));
841 vslot->header_len = sizeof(hdr);
842 vslot->pts_ns = p_video_data->pts_ns;
843  
844 /* Feed auxiliary RTSP and Web preview servers */
845 avx_send_feed_aux_servers(rtsp_srv, web_srv, fourcc, vslot->payload, vslot->payload_size, p_video_data->pts_ns);
846  
847 /* Encode secondary compressed simulcast frame for WAN clients if active */
848 avx_tx_shared_pkt_t *wan_shared_pkt = NULL;
849 if (wan_clients > 0 && wan_enc) {
850 size_t max_wan_out = (size_t)p_video_data->width * p_video_data->height;
851 if (max_wan_out < 1048576) max_wan_out = 1048576;
852 uint8_t *wan_buf = (uint8_t*)malloc(sizeof(hdr) + max_wan_out);
853 if (wan_buf) {
854 size_t actual_wan = 0;
855 bool is_kf = false;
856 int enc_ret = avx_video_encoder_encode(wan_enc, p_video_data,
857 wan_buf + sizeof(hdr), max_wan_out,
858 &actual_wan, &is_kf);
859 if (enc_ret == 0 && actual_wan > 0) {
860 AVX_PACKED_START
861 struct {
862 uint32_t magic;
863 uint32_t xres;
864 uint32_t yres;
865 uint32_t fourcc;
866 int32_t frame_rate_n;
867 int32_t frame_rate_d;
868 int64_t timecode;
869 uint32_t payload_len;
870 } AVX_PACKED wan_hdr;
871 AVX_PACKED_END
872 wan_hdr.magic = magic_video;
873 wan_hdr.xres = (uint32_t)p_video_data->width;
874 wan_hdr.yres = (uint32_t)p_video_data->height;
875 wan_hdr.fourcc = wan_fourcc;
876 wan_hdr.frame_rate_n = (int32_t)p_video_data->framerate.num;
877 wan_hdr.frame_rate_d = (int32_t)p_video_data->framerate.den;
878 wan_hdr.timecode = p_video_data->dts_ns != 0 ? p_video_data->dts_ns : p_video_data->pts_ns;
879 wan_hdr.payload_len = (uint32_t)actual_wan;
880 memcpy(wan_buf, &wan_hdr, sizeof(wan_hdr));
881  
882 wan_shared_pkt = (avx_tx_shared_pkt_t*)calloc(1, sizeof(avx_tx_shared_pkt_t));
883 if (wan_shared_pkt) {
884 wan_shared_pkt->data = wan_buf;
885 wan_shared_pkt->size = sizeof(wan_hdr) + actual_wan;
886 wan_shared_pkt->refcount = 0;
887 } else {
888 free(wan_buf);
889 }
890 } else {
891 free(wan_buf);
892 }
893 }
894 }
895  
896 /* Re-acquire slot->lock to safely enqueue to clients and update counters */
897 avx_mutex_lock(&slot->lock);
898 vslot->in_flight = false;
899 vslot->refcount = 0;
900 int enqueued_count = 0;
901 size_t wire_bytes = sizeof(hdr) + frame_bytes + (has_metadata ? (sizeof(mhdr) + mlen) : 0);
902 int64_t now_ns = avx_time_ns();
903 float target_fps = (p_video_data->framerate.den > 0 && p_video_data->framerate.num > 0)
904 ? ((float)p_video_data->framerate.num / (float)p_video_data->framerate.den)
905 : 60.0f;
906 if (target_fps < 1.0f) target_fps = 1.0f;
907 if (target_fps > 240.0f) target_fps = 240.0f;
908  
909 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
910 if (slot->clients[i].fd == AVX_INVALID_SOCKET) continue;
911  
912 avx_mutex_lock(&slot->clients[i].tx_lock);
913 if (!slot->clients[i].tx_running) {
914 avx_mutex_unlock(&slot->clients[i].tx_lock);
915 continue;
916 }
917  
918 slot->clients[i].frame_seq++;
919  
920 /* 1. Reserved Slot Headroom for Audio:
921 * Video is strictly prohibited from occupying the final 4 slots of the queue.
922 * This guarantees that audio and metadata frames always have space available. */
923 if (slot->clients[i].queue_count >= (AVX_CLIENT_QUEUE_DEPTH - 4)) {
924 slot->clients[i].dropped_frames++;
925 avx_mutex_unlock(&slot->clients[i].tx_lock);
926 continue;
927 }
928  
929 bool client_is_wan = slot->clients[i].is_wan_client && (wan_shared_pkt != NULL);
930 size_t client_wire_bytes = client_is_wan ? wan_shared_pkt->size : wire_bytes;
931  
932 /* 2. Congestion Detection & Adaptive Temporal Decimation */
933 uint32_t cadence = 1;
934 slot->clients[i].congestion_level = avx_send_evaluate_client_congestion(
935 &slot->clients[i], now_ns, client_wire_bytes, target_fps, &cadence);
936  
937 if ((slot->clients[i].frame_seq % cadence) != 0) {
938 /* Decimate: skip this frame cleanly without enqueuing */
939 slot->clients[i].dropped_frames++;
940 avx_mutex_unlock(&slot->clients[i].tx_lock);
941 continue;
942 }
943  
944 int tail = slot->clients[i].queue_tail;
945 slot->clients[i].queue[tail].type = AVX_QUEUE_ITEM_VIDEO;
946 if (client_is_wan) {
947 slot->clients[i].queue[tail].video_pool_idx = -1;
948 slot->clients[i].queue[tail].shared_pkt = wan_shared_pkt;
949 wan_shared_pkt->refcount++;
950 } else {
951 slot->clients[i].queue[tail].video_pool_idx = pool_idx;
952 slot->clients[i].queue[tail].shared_pkt = NULL;
953 vslot->refcount++;
954 }
955 slot->clients[i].queue_tail = (tail + 1) % AVX_CLIENT_QUEUE_DEPTH;
956 slot->clients[i].queue_count++;
957 slot->clients[i].video_queued++;
958 slot->clients[i].video_packets_sent++;
959  
960 enqueued_count++;
961  
962 avx_cond_signal(&slot->clients[i].tx_cond);
963 avx_mutex_unlock(&slot->clients[i].tx_lock);
964 }
965  
966 if (wan_shared_pkt && wan_shared_pkt->refcount == 0) {
967 if (wan_shared_pkt->data) free(wan_shared_pkt->data);
968 free(wan_shared_pkt);
969 }
970  
971 if (enqueued_count > 0) {
972 /* Telemetry tracking for video */
973 slot->telem.total_bytes += (wire_bytes * enqueued_count);
974 slot->telem.window_bytes += (wire_bytes * enqueued_count);
975 slot->telem.window_frames++;
976 slot->telem.last_fourcc = p_video_data->fourcc;
977 slot->telem.last_width = p_video_data->width;
978 slot->telem.last_height = p_video_data->height;
979  
980 if (slot->telem.last_window_time_ns == 0) {
981 slot->telem.last_window_time_ns = now_ns;
982 } else {
983 int64_t elapsed_ns = now_ns - slot->telem.last_window_time_ns;
984 if (elapsed_ns >= 500000000LL) { /* 500 ms sliding window */
985 float elapsed_sec = (float)elapsed_ns / 1000000000.0f;
986 slot->telem.instant_fps = (float)slot->telem.window_frames / elapsed_sec;
987 slot->telem.instant_mbps = ((float)slot->telem.window_bytes * 8.0f) / (elapsed_sec * 1000000.0f);
988 slot->telem.window_bytes = 0;
989 slot->telem.window_frames = 0;
990 slot->telem.last_window_time_ns = now_ns;
991 avx_send_profiles_tick(slot, now_ns / 1000000LL);
992 }
993 }
994  
995 avx_trace_packet("[TX]", "AVX VIDEO FRAME", &hdr, sizeof(hdr));
996 size_t sample_cap = hdr.payload_len > 1024 ? 1024 : hdr.payload_len;
997 size_t snap_len = sizeof(hdr) + sample_cap;
998 uint8_t *snap = (uint8_t*)malloc(snap_len);
999 if (snap) {
1000 memcpy(snap, &hdr, sizeof(hdr));
1001 memcpy(snap + sizeof(hdr), vslot->payload, sample_cap);
1002 avx_pcap_write_tcp(htonl(0x7F000001), slot->port, htonl(0x7F000001), 54321, 100, 1, 0x18, snap, snap_len);
1003 free(snap);
1004 }
1005 }
1006 } else {
1007 slot->telem.last_fourcc = p_video_data->fourcc;
1008 slot->telem.last_width = p_video_data->width;
1009 slot->telem.last_height = p_video_data->height;
1010 }
1011 avx_mutex_unlock(&slot->lock);
1012 }
1013  
1014 void avx_tx_send_video_async(avx_tx_instance_t p_instance, const oavx_video_frame_t* p_video_data) {
1015 avx_tx_send_video(p_instance, p_video_data);
1016 }
1017  
1018 /*
1019 * Distributes shared refcounted audio packet to client queues. Preempts and
1020 * evicts queued video frames if client queue is full to prevent audio dropouts.
1021 */
1022 static void avx_tx_enqueue_audio_shared_pkt(
1023 avx_send_ctx_t *slot,
1024 avx_tx_shared_pkt_t *pkt,
1025 const void *hdr_ptr,
1026 size_t hdr_len,
1027 const void *sample_ptr,
1028 size_t sample_len
1029 ) {
1030 pkt->refcount = 0;
1031 int enqueued_count = 0;
1032  
1033 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
1034 if (slot->clients[i].fd == AVX_INVALID_SOCKET) continue;
1035  
1036 avx_mutex_lock(&slot->clients[i].tx_lock);
1037 if (!slot->clients[i].tx_running) {
1038 avx_mutex_unlock(&slot->clients[i].tx_lock);
1039 continue;
1040 }
1041  
1042 /* Priority Preemption: Audio frames must NEVER be dropped if video frames are queued.
1043 * If the queue is full (queue_count >= AVX_CLIENT_QUEUE_DEPTH), evict the oldest
1044 * video frame to immediately create a free slot for this audio frame! */
1045 if (slot->clients[i].queue_count >= AVX_CLIENT_QUEUE_DEPTH) {
1046 int head = slot->clients[i].queue_head;
1047 int evict_idx = -1;
1048 for (int q = 0; q < slot->clients[i].queue_count; ++q) {
1049 int idx = (head + q) % AVX_CLIENT_QUEUE_DEPTH;
1050 if (slot->clients[i].queue[idx].type == AVX_QUEUE_ITEM_VIDEO) {
1051 evict_idx = idx;
1052 break;
1053 }
1054 }
1055  
1056 if (evict_idx >= 0) {
1057 int p_idx = slot->clients[i].queue[evict_idx].video_pool_idx;
1058 if (p_idx >= 0 && p_idx < AVX_TX_VIDEO_POOL_SIZE) {
1059 if (slot->video_pool[p_idx].refcount > 0) {
1060 slot->video_pool[p_idx].refcount--;
1061 }
1062 }
1063 if (slot->clients[i].video_queued > 0) {
1064 slot->clients[i].video_queued--;
1065 }
1066 slot->clients[i].dropped_frames++;
1067  
1068 /* Shift items between evict_idx and tail - 1 */
1069 int cur = evict_idx;
1070 int tail = slot->clients[i].queue_tail;
1071 int last = (tail - 1 + AVX_CLIENT_QUEUE_DEPTH) % AVX_CLIENT_QUEUE_DEPTH;
1072 while (cur != last) {
1073 int next = (cur + 1) % AVX_CLIENT_QUEUE_DEPTH;
1074 slot->clients[i].queue[cur] = slot->clients[i].queue[next];
1075 cur = next;
1076 }
1077 slot->clients[i].queue[last].type = AVX_QUEUE_ITEM_NONE;
1078 slot->clients[i].queue[last].shared_pkt = NULL;
1079 slot->clients[i].queue_tail = last;
1080 slot->clients[i].queue_count--;
1081 }
1082 }
1083  
1084 if (slot->clients[i].queue_count < AVX_CLIENT_QUEUE_DEPTH) {
1085 int tail = slot->clients[i].queue_tail;
1086 slot->clients[i].queue[tail].type = AVX_QUEUE_ITEM_AUDIO;
1087 slot->clients[i].queue[tail].video_pool_idx = -1;
1088 slot->clients[i].queue[tail].shared_pkt = pkt;
1089 slot->clients[i].queue_tail = (tail + 1) % AVX_CLIENT_QUEUE_DEPTH;
1090 slot->clients[i].queue_count++;
1091 slot->clients[i].audio_packets_sent++;
1092  
1093 pkt->refcount++;
1094 enqueued_count++;
1095  
1096 avx_cond_signal(&slot->clients[i].tx_cond);
1097 } else {
1098 slot->clients[i].dropped_frames++;
1099 }
1100 avx_mutex_unlock(&slot->clients[i].tx_lock);
1101 }
1102  
1103 if (enqueued_count == 0) {
1104 free(pkt->data);
1105 free(pkt);
1106 } else {
1107 /* Telemetry tracking for audio */
1108 size_t a_wire = pkt->size * enqueued_count;
1109 slot->telem.total_bytes += a_wire;
1110 slot->telem.window_bytes += a_wire;
1111  
1112 if (hdr_ptr && hdr_len > 0) {
1113 avx_trace_packet("[TX]", "AVX AUDIO FRAME", hdr_ptr, hdr_len);
1114 size_t sample_cap = sample_len > 512 ? 512 : sample_len;
1115 size_t snap_len = hdr_len + sample_cap;
1116 uint8_t *snap = (uint8_t*)malloc(snap_len);
1117 if (snap) {
1118 memcpy(snap, hdr_ptr, hdr_len);
1119 if (sample_ptr && sample_cap > 0) {
1120 memcpy(snap + hdr_len, sample_ptr, sample_cap);
1121 }
1122 avx_pcap_write_tcp(htonl(0x7F000001), slot->port, htonl(0x7F000001), 54321, 200, 1, 0x18, snap, snap_len);
1123 free(snap);
1124 }
1125 }
1126 }
1127 }
1128  
1129 /*
1130 * Ingests planar float audio. Evaluates congestion for adaptive Opus/ADPCM
1131 * compression; otherwise packages uncompressed 32-bit float PCM.
1132 */
1133 OPENAVX_API void avx_tx_send_audio(avx_tx_instance_t p_instance, const oavx_audio_frame_t* p_audio_data) {
1134 if (!p_instance || !p_audio_data) return;
1135 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1136  
1137 avx_mutex_lock(&slot->lock);
1138 slot->audio_frames_sent++;
1139  
1140 if (slot->active_clients > 0 && p_audio_data->planes[0] && p_audio_data->frames > 0) {
1141 /* Adaptive compression mode evaluation */
1142 if (slot->audio_comp_mode == OAVX_AUDIO_COMPRESSION_ADAPTIVE) {
1143 bool congested = false;
1144 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
1145 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
1146 if (slot->clients[i].congestion_level > 0 || slot->clients[i].queue_count > 0) {
1147 congested = true;
1148 break;
1149 }
1150 }
1151 }
1152 if (!congested && slot->audio_comp_active && slot->audio_encoder) {
1153 /* Link cleared: flush pending compressed accumulator before switching back to uncompressed */
1154 uint8_t f_buf[65536];
1155 size_t f_size = 0;
1156 int f_samples = 0;
1157 int64_t f_pts = 0;
1158 uint32_t f_fourcc = 0;
1159 if (avx_audio_encoder_flush(slot->audio_encoder, f_buf, sizeof(f_buf),
1160 &f_size, &f_samples, &f_pts, &f_fourcc)) {
1161 AVX_PACKED_START
1162 struct {
1163 uint32_t magic;
1164 uint32_t codec_fourcc;
1165 int32_t sample_rate;
1166 int32_t channels;
1167 int32_t samples;
1168 int64_t timecode;
1169 uint32_t payload_len;
1170 } AVX_PACKED fhdr;
1171 AVX_PACKED_END
1172  
1173 fhdr.magic = OAVX_WIRE_MAGIC_AUDIO_COMP;
1174 fhdr.codec_fourcc = f_fourcc;
1175 fhdr.sample_rate = (int32_t)p_audio_data->sample_rate;
1176 fhdr.channels = (int32_t)p_audio_data->channels;
1177 fhdr.samples = (int32_t)f_samples;
1178 fhdr.timecode = f_pts;
1179 fhdr.payload_len = (uint32_t)f_size;
1180  
1181 avx_tx_shared_pkt_t *fpkt = (avx_tx_shared_pkt_t*)malloc(sizeof(avx_tx_shared_pkt_t));
1182 if (fpkt) {
1183 fpkt->size = sizeof(fhdr) + f_size;
1184 fpkt->data = (uint8_t*)malloc(fpkt->size);
1185 if (fpkt->data) {
1186 memcpy(fpkt->data, &fhdr, sizeof(fhdr));
1187 memcpy(fpkt->data + sizeof(fhdr), f_buf, f_size);
1188 avx_tx_enqueue_audio_shared_pkt(slot, fpkt, &fhdr, sizeof(fhdr), f_buf, f_size);
1189 } else {
1190 free(fpkt);
1191 }
1192 }
1193 }
1194 }
1195 slot->audio_comp_active = congested;
1196 }
1197  
1198 bool separate_planes = (p_audio_data->channels > 1 &&
1199 p_audio_data->planes[1] != NULL &&
1200 p_audio_data->planes[1] != (void*)((float*)p_audio_data->planes[0] + p_audio_data->frames));
1201  
1202 if (slot->audio_comp_active) {
1203 /* Create or reconfigure encoder instance as necessary */
1204 if (!slot->audio_encoder || slot->audio_enc_channels != (int)p_audio_data->channels ||
1205 slot->audio_enc_sample_rate != (int)p_audio_data->sample_rate) {
1206 if (slot->audio_encoder) {
1207 avx_audio_encoder_destroy(slot->audio_encoder);
1208 }
1209 avx_audio_codec_type_e codec_pref = (p_audio_data->channels <= 8) ? AVX_AUDIO_CODEC_OPUS : AVX_AUDIO_CODEC_ADPCM;
1210 slot->audio_encoder = avx_audio_encoder_create((int)p_audio_data->sample_rate,
1211 (int)p_audio_data->channels,
1212 codec_pref,
1213 slot->audio_target_bitrate_kbps);
1214 slot->audio_enc_channels = (int)p_audio_data->channels;
1215 slot->audio_enc_sample_rate = (int)p_audio_data->sample_rate;
1216 }
1217  
1218 if (slot->audio_encoder) {
1219 const float* in_planes[OAVX_MAX_AUDIO_CHANNELS];
1220 for (int c = 0; c < (int)p_audio_data->channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1221 if (separate_planes) {
1222 in_planes[c] = (const float*)p_audio_data->planes[c];
1223 } else {
1224 in_planes[c] = (const float*)p_audio_data->planes[0] + (size_t)c * p_audio_data->frames;
1225 }
1226 }
1227 avx_audio_encoder_feed(slot->audio_encoder, in_planes, (int)p_audio_data->frames, p_audio_data->pts_ns);
1228  
1229 uint8_t comp_buf[65536];
1230 size_t comp_size = 0;
1231 int out_samples = 0;
1232 int64_t out_pts = 0;
1233 uint32_t out_fourcc = 0;
1234  
1235 while (avx_audio_encoder_pull(slot->audio_encoder, comp_buf, sizeof(comp_buf),
1236 &comp_size, &out_samples, &out_pts, &out_fourcc)) {
1237 AVX_PACKED_START
1238 struct {
1239 uint32_t magic; /* OAVX_WIRE_MAGIC_AUDIO_COMP ('AVXO') */
1240 uint32_t codec_fourcc; /* 'OPUS' or 'ADPC' */
1241 int32_t sample_rate;
1242 int32_t channels;
1243 int32_t samples;
1244 int64_t timecode;
1245 uint32_t payload_len;
1246 } AVX_PACKED chdr;
1247 AVX_PACKED_END
1248  
1249 chdr.magic = OAVX_WIRE_MAGIC_AUDIO_COMP;
1250 chdr.codec_fourcc = out_fourcc;
1251 chdr.sample_rate = (int32_t)p_audio_data->sample_rate;
1252 chdr.channels = (int32_t)p_audio_data->channels;
1253 chdr.samples = (int32_t)out_samples;
1254 chdr.timecode = out_pts;
1255 chdr.payload_len = (uint32_t)comp_size;
1256  
1257 avx_tx_shared_pkt_t *pkt = (avx_tx_shared_pkt_t*)malloc(sizeof(avx_tx_shared_pkt_t));
1258 if (!pkt) break;
1259  
1260 pkt->size = sizeof(chdr) + comp_size;
1261 pkt->data = (uint8_t*)malloc(pkt->size);
1262 if (!pkt->data) {
1263 free(pkt);
1264 break;
1265 }
1266  
1267 memcpy(pkt->data, &chdr, sizeof(chdr));
1268 memcpy(pkt->data + sizeof(chdr), comp_buf, comp_size);
1269  
1270 avx_tx_enqueue_audio_shared_pkt(slot, pkt, &chdr, sizeof(chdr), comp_buf, comp_size);
1271 }
1272  
1273 avx_mutex_unlock(&slot->lock);
1274 return;
1275 }
1276 }
1277  
1278 /* Uncompressed fallback / legacy ('AVXA') */
1279 AVX_PACKED_START
1280 struct {
1281 uint32_t magic;
1282 int32_t sample_rate;
1283 int32_t channels;
1284 int32_t samples;
1285 int64_t timecode;
1286 uint32_t payload_len;
1287 } AVX_PACKED hdr;
1288 AVX_PACKED_END
1289  
1290 hdr.magic = slot->wire_profile.magic_audio;
1291 hdr.sample_rate = (int32_t)p_audio_data->sample_rate;
1292 hdr.channels = (int32_t)p_audio_data->channels;
1293 hdr.samples = (int32_t)p_audio_data->frames;
1294 hdr.timecode = p_audio_data->pts_ns;
1295  
1296 size_t audio_bytes = (size_t)p_audio_data->channels * p_audio_data->frames * sizeof(float);
1297 hdr.payload_len = (uint32_t)audio_bytes;
1298  
1299 avx_tx_shared_pkt_t *pkt = (avx_tx_shared_pkt_t*)malloc(sizeof(avx_tx_shared_pkt_t));
1300 if (!pkt) {
1301 avx_mutex_unlock(&slot->lock);
1302 return;
1303 }
1304  
1305 pkt->size = sizeof(hdr) + audio_bytes;
1306 pkt->data = (uint8_t*)malloc(pkt->size);
1307 if (!pkt->data) {
1308 free(pkt);
1309 avx_mutex_unlock(&slot->lock);
1310 return;
1311 }
1312  
1313 memcpy(pkt->data, &hdr, sizeof(hdr));
1314 if (separate_planes) {
1315 size_t ch_bytes = (size_t)p_audio_data->frames * sizeof(float);
1316 for (uint16_t c = 0; c < p_audio_data->channels && c < OAVX_MAX_AUDIO_CHANNELS; ++c) {
1317 if (p_audio_data->planes[c]) {
1318 memcpy(pkt->data + sizeof(hdr) + c * ch_bytes, p_audio_data->planes[c], ch_bytes);
1319 } else {
1320 memset(pkt->data + sizeof(hdr) + c * ch_bytes, 0, ch_bytes);
1321 }
1322 }
1323 } else {
1324 memcpy(pkt->data + sizeof(hdr), p_audio_data->planes[0], audio_bytes);
1325 }
1326  
1327 avx_tx_enqueue_audio_shared_pkt(slot, pkt, &hdr, sizeof(hdr), p_audio_data->planes[0], audio_bytes);
1328 }
1329 avx_mutex_unlock(&slot->lock);
1330 }
1331  
1332 void avx_tx_set_audio_compression(avx_tx_instance_t p_instance, oavx_audio_compression_mode_e mode, int target_bitrate_kbps) {
1333 if (!p_instance) return;
1334 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1335 avx_mutex_lock(&slot->lock);
1336 slot->audio_comp_mode = mode;
1337 slot->audio_target_bitrate_kbps = target_bitrate_kbps;
1338 if (mode == OAVX_AUDIO_COMPRESSION_MANUAL) {
1339 slot->audio_comp_active = true;
1340 } else if (mode == OAVX_AUDIO_COMPRESSION_OFF) {
1341 slot->audio_comp_active = false;
1342 if (slot->audio_encoder) {
1343 avx_audio_encoder_destroy(slot->audio_encoder);
1344 slot->audio_encoder = NULL;
1345 slot->audio_enc_channels = 0;
1346 slot->audio_enc_sample_rate = 0;
1347 }
1348 }
1349 avx_mutex_unlock(&slot->lock);
1350 }
1351  
1352 void avx_tx_set_video_quality(avx_tx_instance_t p_instance, uint8_t quality) {
1353 if (!p_instance) return;
1354 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1355 if (quality != 0) {
1356 if (quality < 20) quality = 20;
1357 if (quality > 98) quality = 98;
1358 }
1359 avx_mutex_lock(&slot->lock);
1360 slot->video_quality = quality;
1361 if (slot->video_encoder) {
1362 avx_video_encoder_set_quality(slot->video_encoder, quality);
1363 }
1364 avx_mutex_unlock(&slot->lock);
1365 }
1366  
1367 uint8_t avx_tx_get_video_quality(avx_tx_instance_t p_instance) {
1368 if (!p_instance) return 0;
1369 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1370 avx_mutex_lock(&slot->lock);
1371 uint8_t q = slot->video_quality;
1372 avx_mutex_unlock(&slot->lock);
1373 return q ? q : avx_speedhq_get_quality();
1374 }
1375  
1376 void avx_tx_set_video_compression(avx_tx_instance_t p_instance, uint32_t target_fourcc, uint32_t bitrate_kbps) {
1377 if (!p_instance) return;
1378 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1379 avx_mutex_lock(&slot->lock);
1380 slot->video_codec_fourcc = target_fourcc;
1381 slot->video_bitrate_kbps = bitrate_kbps;
1382 if (slot->video_encoder) {
1383 avx_video_encoder_destroy(slot->video_encoder);
1384 slot->video_encoder = NULL;
1385 slot->video_enc_fourcc = 0;
1386 slot->video_enc_width = 0;
1387 slot->video_enc_height = 0;
1388 }
1389 avx_mutex_unlock(&slot->lock);
1390 }
1391  
1392 uint32_t avx_tx_get_video_compression(avx_tx_instance_t p_instance) {
1393 if (!p_instance) return 0;
1394 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1395 avx_mutex_lock(&slot->lock);
1396 uint32_t fcc = slot->video_codec_fourcc;
1397 avx_mutex_unlock(&slot->lock);
1398 return fcc;
1399 }
1400  
1401 void avx_tx_send_metadata(avx_tx_instance_t p_instance, const oavx_metadata_frame_t* metadata) {
1402 if (!p_instance || !metadata || !metadata->data) return;
1403 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1404  
1405 avx_mutex_lock(&slot->lock);
1406 if (slot->active_clients > 0) {
1407 size_t len = metadata->length > 0 ? metadata->length : strlen(metadata->data);
1408  
1409 AVX_PACKED_START
1410 struct {
1411 uint32_t magic;
1412 int64_t timecode;
1413 uint32_t payload_len;
1414 } AVX_PACKED hdr;
1415 AVX_PACKED_END
1416  
1417 hdr.magic = slot->wire_profile.magic_metadata;
1418 hdr.timecode = metadata->pts_ns;
1419 hdr.payload_len = (uint32_t)len;
1420  
1421 avx_tx_shared_pkt_t *pkt = (avx_tx_shared_pkt_t*)malloc(sizeof(avx_tx_shared_pkt_t));
1422 if (!pkt) {
1423 avx_mutex_unlock(&slot->lock);
1424 return;
1425 }
1426  
1427 pkt->size = sizeof(hdr) + len;
1428 pkt->data = (uint8_t*)malloc(pkt->size);
1429 if (!pkt->data) {
1430 free(pkt);
1431 avx_mutex_unlock(&slot->lock);
1432 return;
1433 }
1434  
1435 memcpy(pkt->data, &hdr, sizeof(hdr));
1436 memcpy(pkt->data + sizeof(hdr), metadata->data, len);
1437  
1438 pkt->refcount = 0;
1439 int enqueued_count = 0;
1440  
1441 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
1442 if (slot->clients[i].fd == AVX_INVALID_SOCKET) continue;
1443  
1444 avx_mutex_lock(&slot->clients[i].tx_lock);
1445 if (!slot->clients[i].tx_running) {
1446 avx_mutex_unlock(&slot->clients[i].tx_lock);
1447 continue;
1448 }
1449  
1450 if (slot->clients[i].queue_count >= AVX_CLIENT_QUEUE_DEPTH) {
1451 slot->clients[i].dropped_frames++;
1452 avx_mutex_unlock(&slot->clients[i].tx_lock);
1453 continue;
1454 }
1455  
1456 int tail = slot->clients[i].queue_tail;
1457 slot->clients[i].queue[tail].type = AVX_QUEUE_ITEM_METADATA;
1458 slot->clients[i].queue[tail].video_pool_idx = -1;
1459 slot->clients[i].queue[tail].shared_pkt = pkt;
1460 slot->clients[i].queue_tail = (tail + 1) % AVX_CLIENT_QUEUE_DEPTH;
1461 slot->clients[i].queue_count++;
1462  
1463 pkt->refcount++;
1464 enqueued_count++;
1465  
1466 avx_cond_signal(&slot->clients[i].tx_cond);
1467 avx_mutex_unlock(&slot->clients[i].tx_lock);
1468 }
1469  
1470 if (enqueued_count == 0) {
1471 free(pkt->data);
1472 free(pkt);
1473 } else {
1474 /* Telemetry tracking for metadata */
1475 slot->metadata_frames_sent++;
1476 size_t m_wire = (sizeof(hdr) + len) * enqueued_count;
1477 slot->telem.total_bytes += m_wire;
1478 slot->telem.window_bytes += m_wire;
1479  
1480 avx_trace_packet("[TX]", "AVX METADATA FRAME", metadata->data, len);
1481  
1482 /* Write to PCAP */
1483 size_t snap_len = sizeof(hdr) + len;
1484 uint8_t *snap = (uint8_t*)malloc(snap_len);
1485 if (snap) {
1486 memcpy(snap, &hdr, sizeof(hdr));
1487 memcpy(snap + sizeof(hdr), metadata->data, len);
1488 avx_pcap_write_tcp(htonl(0x7F000001), slot->port, htonl(0x7F000001), 54321, 300, 1, 0x18, snap, snap_len);
1489 free(snap);
1490 }
1491 }
1492 }
1493 avx_mutex_unlock(&slot->lock);
1494 }
1495  
1496 bool avx_tx_get_tally(avx_tx_instance_t p_instance, oavx_tally_t* p_tally, uint32_t timeout_in_ms) {
1497 if (!p_instance || !p_tally) return false;
1498 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1499  
1500 avx_mutex_lock(&slot->lock);
1501 if (timeout_in_ms > 0 && !(slot->tally.flags & (OAVX_TALLY_PROGRAM | OAVX_TALLY_PREVIEW | OAVX_TALLY_RECORDING))) {
1502 avx_cond_timedwait(&slot->tally_cond, &slot->lock, timeout_in_ms);
1503 }
1504 *p_tally = slot->tally;
1505 avx_mutex_unlock(&slot->lock);
1506 return true;
1507 }
1508  
1509 bool avx_tx_set_tally(avx_tx_instance_t p_instance, const oavx_tally_t* p_tally) {
1510 if (!p_instance || !p_tally) return false;
1511 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1512  
1513 avx_mutex_lock(&slot->lock);
1514 slot->tally = *p_tally;
1515 avx_cond_broadcast(&slot->tally_cond);
1516 if (slot->web_server) {
1517 avx_web_server_broadcast_tally((avx_web_server_t*)slot->web_server, &slot->tally);
1518 }
1519  
1520 char tally_xml[256];
1521 int len = snprintf(tally_xml, sizeof(tally_xml),
1522 "<%s on_program=\"%s\" on_preview=\"%s\" on_recording=\"%s\"/>\n",
1523 slot->wire_profile.tally_tag ? slot->wire_profile.tally_tag : OAVX_WIRE_TALLY_TAG,
1524 (p_tally->flags & OAVX_TALLY_PROGRAM) ? "true" : "false",
1525 (p_tally->flags & OAVX_TALLY_PREVIEW) ? "true" : "false",
1526 (p_tally->flags & OAVX_TALLY_RECORDING) ? "true" : "false");
1527 avx_mutex_unlock(&slot->lock);
1528  
1529 oavx_metadata_frame_t meta = {
1530 .length = (size_t)len,
1531 .pts_ns = 0,
1532 .data = tally_xml
1533 };
1534 avx_tx_send_metadata(p_instance, &meta);
1535 return true;
1536 }
1537  
1538 void avx_tx_clear_connection_metadata(avx_tx_instance_t p_instance) {
1539 if (!p_instance) return;
1540 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1541 avx_mutex_lock(&slot->lock);
1542 slot->num_conn_metadata = 0;
1543 avx_mutex_unlock(&slot->lock);
1544 }
1545  
1546 void avx_tx_add_connection_metadata(avx_tx_instance_t p_instance, const oavx_metadata_frame_t* metadata) {
1547 if (!p_instance || !metadata || !metadata->data) return;
1548 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1549 avx_mutex_lock(&slot->lock);
1550 if (slot->num_conn_metadata < 16) {
1551 snprintf(slot->conn_metadata[slot->num_conn_metadata],
1552 sizeof(slot->conn_metadata[0]), "%s", metadata->data);
1553 slot->num_conn_metadata++;
1554 }
1555 avx_mutex_unlock(&slot->lock);
1556 }
1557  
1558 /*
1559 * Configures secondary backup endpoint and broadcasts failover XML descriptor
1560 * to all connected receivers for instant client-side switchover on disconnect.
1561 */
1562 void avx_tx_set_failover(avx_tx_instance_t p_instance, const oavx_endpoint_t* p_failover_source) {
1563 if (!p_instance) return;
1564 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1565 avx_mutex_lock(&slot->lock);
1566  
1567 /* Remove any existing failover metadata from conn_metadata */
1568 size_t w = 0;
1569 for (size_t r = 0; r < slot->num_conn_metadata; ++r) {
1570 if (strstr(slot->conn_metadata[r], "failover") == NULL) {
1571 if (w != r) {
1572 snprintf(slot->conn_metadata[w], sizeof(slot->conn_metadata[0]),
1573 "%s", slot->conn_metadata[r]);
1574 }
1575 w++;
1576 }
1577 }
1578 slot->num_conn_metadata = w;
1579  
1580 if (p_failover_source && (p_failover_source->address != NULL || p_failover_source->name != NULL)) {
1581 if (p_failover_source->name) {
1582 snprintf(slot->failover_name, sizeof(slot->failover_name), "%s", p_failover_source->name);
1583 } else {
1584 slot->failover_name[0] = '\0';
1585 }
1586 if (p_failover_source->address) {
1587 snprintf(slot->failover_url, sizeof(slot->failover_url), "%s", p_failover_source->address);
1588 } else {
1589 slot->failover_url[0] = '\0';
1590 }
1591 slot->failover_source.name = slot->failover_name;
1592 slot->failover_source.address = slot->failover_url;
1593 slot->has_failover = true;
1594  
1595 /* Build XML failover metadata packet */
1596 char meta_xml[512];
1597 snprintf(meta_xml, sizeof(meta_xml),
1598 "<openavx_failover name=\"%s\" address=\"%s\"/>\n",
1599 slot->failover_name, slot->failover_url);
1600  
1601 /* Add to conn_metadata for future receivers */
1602 if (slot->num_conn_metadata < 16) {
1603 snprintf(slot->conn_metadata[slot->num_conn_metadata],
1604 sizeof(slot->conn_metadata[0]), "%s", meta_xml);
1605 slot->num_conn_metadata++;
1606 }
1607  
1608 /* Broadcast immediately to all currently connected clients */
1609 size_t mlen = strlen(meta_xml);
1610 AVX_PACKED_START
1611 struct {
1612 uint32_t magic;
1613 int64_t timecode;
1614 uint32_t payload_len;
1615 } AVX_PACKED mhdr;
1616 AVX_PACKED_END
1617 mhdr.magic = slot->wire_profile.magic_metadata;
1618 mhdr.timecode = 0;
1619 mhdr.payload_len = (uint32_t)mlen;
1620  
1621 for (int i = 0; i < slot->max_clients; ++i) {
1622 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
1623 send(slot->clients[i].fd, (const char*)&mhdr, sizeof(mhdr), MSG_NOSIGNAL);
1624 send(slot->clients[i].fd, meta_xml, mlen, MSG_NOSIGNAL);
1625 }
1626 }
1627 } else {
1628 slot->has_failover = false;
1629 slot->failover_name[0] = '\0';
1630 slot->failover_url[0] = '\0';
1631 }
1632  
1633 avx_mutex_unlock(&slot->lock);
1634 }
1635  
1636 int avx_tx_get_connection_count(avx_tx_instance_t p_instance, uint32_t timeout_in_ms) {
1637 if (!p_instance) return 0;
1638 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1639 uint32_t elapsed = 0;
1640 while (1) {
1641 avx_mutex_lock(&slot->lock);
1642 int active = slot->active_clients;
1643 avx_mutex_unlock(&slot->lock);
1644 if (active > 0 || elapsed >= timeout_in_ms) {
1645 return active;
1646 }
1647 avx_sleep_ms(5);
1648 elapsed += 5;
1649 }
1650 }
1651  
1652 OPENAVX_API const oavx_endpoint_t* avx_tx_get_source(avx_tx_instance_t p_instance) {
1653 if (!p_instance) return NULL;
1654 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1655 return &slot->source_info;
1656 }
1657  
1658 oavx_frame_type_t avx_tx_capture_metadata(
1659 avx_tx_instance_t p_instance,
1660 oavx_metadata_frame_t* metadata,
1661 uint32_t timeout_in_ms
1662 ) {
1663 if (!p_instance || !metadata) return OAVX_FRAME_TYPE_ERROR;
1664 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1665  
1666 uint32_t elapsed = 0;
1667 while (elapsed <= timeout_in_ms) {
1668 avx_mutex_lock(&slot->lock);
1669 if (slot->has_new_metadata) {
1670 size_t len = strlen(slot->last_metadata);
1671 char* buf = (char*)malloc(len + 1);
1672 if (buf) {
1673 memcpy(buf, slot->last_metadata, len + 1);
1674 metadata->data = buf;
1675 metadata->length = len;
1676 metadata->pts_ns = 0;
1677 slot->has_new_metadata = false;
1678 avx_mutex_unlock(&slot->lock);
1679 return OAVX_FRAME_TYPE_METADATA;
1680 }
1681 }
1682 avx_mutex_unlock(&slot->lock);
1683  
1684 if (timeout_in_ms == 0) break;
1685 avx_sleep_ms(5);
1686 elapsed += 5;
1687 }
1688  
1689 return OAVX_FRAME_TYPE_NONE;
1690 }
1691  
1692 void avx_tx_free_metadata(
1693 avx_tx_instance_t p_instance,
1694 const oavx_metadata_frame_t* metadata
1695 ) {
1696 (void)p_instance;
1697 if (!metadata) return;
1698 if (metadata->data) {
1699 free(metadata->data);
1700 }
1701 }
1702  
1703 OPENAVX_API bool avx_tx_get_telemetry(avx_tx_instance_t p_instance, oavx_telemetry_t *out) {
1704 if (!p_instance || !out) return false;
1705 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1706 memset(out, 0, sizeof(*out));
1707  
1708 avx_mutex_lock(&slot->lock);
1709  
1710 int64_t now_ns = avx_time_ns();
1711 float fps = slot->telem.instant_fps;
1712 float mbps = slot->telem.instant_mbps;
1713  
1714 if (slot->telem.last_window_time_ns > 0 && (now_ns - slot->telem.last_window_time_ns) > 1000000000LL && slot->telem.window_frames == 0) {
1715 fps = 0.0f;
1716 mbps = 0.0f;
1717 } else if (fps == 0.0f && slot->telem.window_frames > 0 && slot->telem.last_window_time_ns > 0) {
1718 int64_t elapsed_ns = now_ns - slot->telem.last_window_time_ns;
1719 if (elapsed_ns >= 10000000LL) {
1720 float elapsed_sec = (float)elapsed_ns / 1000000000.0f;
1721 fps = (float)slot->telem.window_frames / elapsed_sec;
1722 mbps = ((float)slot->telem.window_bytes * 8.0f) / (elapsed_sec * 1000000.0f);
1723 }
1724 }
1725  
1726 uint64_t total_dropped = 0;
1727 uint32_t max_congestion = 0;
1728 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
1729 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
1730 total_dropped += slot->clients[i].dropped_frames;
1731 if (slot->clients[i].congestion_level > max_congestion) {
1732 max_congestion = slot->clients[i].congestion_level;
1733 }
1734 }
1735 }
1736  
1737 out->video_frames_total = slot->video_frames_sent;
1738 out->audio_frames_total = slot->audio_frames_sent;
1739 out->metadata_frames_total = slot->metadata_frames_sent;
1740 out->dropped_frames_total = total_dropped;
1741 out->fps = fps;
1742 out->bitrate_mbps = mbps;
1743 out->total_wire_bytes = slot->telem.total_bytes;
1744 out->inter_frame_jitter_ms = 0.0f;
1745 out->fourcc = slot->telem.last_fourcc;
1746 out->width = slot->telem.last_width;
1747 out->height = slot->telem.last_height;
1748 out->is_connected = (slot->active_clients > 0);
1749 out->congestion_level = max_congestion;
1750  
1751 if (slot->url[0]) {
1752 snprintf(out->remote_endpoint, sizeof(out->remote_endpoint), "%.127s", slot->url);
1753 } else {
1754 snprintf(out->remote_endpoint, sizeof(out->remote_endpoint), "0.0.0.0:%u", slot->port);
1755 }
1756  
1757 avx_socket_t client_sock = slot->tcp_client_fd;
1758 void *rudp_s = slot->rudp_sender;
1759 oavx_transport_e tx_transport = slot->transport;
1760 avx_mutex_unlock(&slot->lock);
1761  
1762 if (tx_transport == OAVX_TRANSPORT_RUDP && rudp_s) {
1763 avx_rudp_telemetry_t r_telem;
1764 if (avx_udp_rudp_sender_get_telemetry((avx_udp_rudp_sender_t*)rudp_s, &r_telem)) {
1765 out->kernel_rtt_ms = (float)r_telem.srtt_ms;
1766 out->tcp_retransmissions = (uint32_t)r_telem.packets_retransmitted;
1767 }
1768 } else if (client_sock != AVX_INVALID_SOCKET) {
1769 avx_socket_get_diagnostics(client_sock, &out->kernel_rtt_ms, &out->tcp_retransmissions,
1770 &out->socket_send_q_bytes, &out->socket_recv_q_bytes);
1771 }
1772  
1773 return true;
1774 }
1775  
1776 OPENAVX_API struct avx_rate_controller_t* avx_tx_get_rate_controller(avx_tx_instance_t p_instance) {
1777 if (!p_instance) return NULL;
1778 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1779 return slot->rate_ctl;
1780 }
1781  
1782 OPENAVX_API int avx_tx_get_wan_client_count(avx_tx_instance_t p_instance) {
1783 if (!p_instance) return 0;
1784 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1785 avx_mutex_lock(&slot->lock);
1786 int count = slot->wan_client_count;
1787 avx_mutex_unlock(&slot->lock);
1788 return count;
1789 }
1790  
1791 OPENAVX_API uint32_t avx_tx_get_wan_codec_fourcc(avx_tx_instance_t p_instance) {
1792 if (!p_instance) return 0;
1793 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1794 avx_mutex_lock(&slot->lock);
1795 uint32_t fourcc = slot->wan_codec_fourcc;
1796 avx_mutex_unlock(&slot->lock);
1797 return fourcc;
1798 }
1799  
1800 OPENAVX_API bool avx_tx_is_wan_encoder_active(avx_tx_instance_t p_instance) {
1801 if (!p_instance) return false;
1802 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1803 avx_mutex_lock(&slot->lock);
1804 bool active = (slot->wan_encoder != NULL);
1805 avx_mutex_unlock(&slot->lock);
1806 return active;
1807 }
1808  
1809 /*
1810 * Sets transmission profile for a specific client (e.g. "wan" for secondary
1811 * hardware-compressed simulcast). Spawns or tears down WAN encoder on demand.
1812 */
1813 OPENAVX_API bool avx_tx_set_client_profile(avx_tx_instance_t p_instance, int client_idx, const char *profile) {
1814 if (!p_instance || !profile || client_idx < 0 || client_idx >= AVX_MAX_CLIENTS) return false;
1815 avx_send_ctx_t* slot = (avx_send_ctx_t*)p_instance;
1816 avx_mutex_lock(&slot->lock);
1817 if (slot->clients[client_idx].fd == AVX_INVALID_SOCKET) {
1818 avx_mutex_unlock(&slot->lock);
1819 return false;
1820 }
1821  
1822 bool is_wan = (strcasecmp(profile, "wan") == 0);
1823 if (is_wan && !slot->clients[client_idx].is_wan_registered) {
1824 slot->clients[client_idx].is_wan_client = true;
1825 slot->clients[client_idx].is_wan_registered = true;
1826 slot->wan_client_count++;
1827 if (slot->wan_codec_fourcc == 0) {
1828 slot->wan_codec_fourcc = slot->clients[client_idx].negotiated_codec_fourcc
1829 ? slot->clients[client_idx].negotiated_codec_fourcc
1830 : OAVX_FOURCC_VIDEO_TYPE_H264;
1831 }
1832 if (slot->wan_encoder) {
1833 avx_video_encoder_request_keyframe(slot->wan_encoder);
1834 }
1835 } else if (!is_wan && slot->clients[client_idx].is_wan_registered) {
1836 slot->clients[client_idx].is_wan_client = false;
1837 slot->clients[client_idx].is_wan_registered = false;
1838 if (slot->wan_client_count > 0) slot->wan_client_count--;
1839 if (slot->wan_client_count == 0 && slot->wan_encoder) {
1840 avx_video_encoder_destroy(slot->wan_encoder);
1841 slot->wan_encoder = NULL;
1842 slot->wan_enc_width = 0;
1843 slot->wan_enc_height = 0;
1844 slot->wan_enc_fourcc = 0;
1845 }
1846 if (slot->video_encoder) {
1847 avx_video_encoder_request_keyframe(slot->video_encoder);
1848 }
1849 }
1850 avx_mutex_unlock(&slot->lock);
1851 return true;
1852 }