Raw ↗
+ +
b0d80ca chore(release): bump version to v0.2.2 and finalize release docs/docker
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_send_client.c - Client network connections, listener daemon, and async TX/RX workers
7 */
8  
9 #include "avx_send_internal.h"
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include <time.h>
14  
15 bool avx_socket_send_all(avx_socket_t fd, const void* buf, size_t len) {
16 if (fd == AVX_INVALID_SOCKET || !buf || len == 0) return true;
17 const char* ptr = (const char*)buf;
18 size_t remaining = len;
19 while (remaining > 0) {
20 ssize_t n = send(fd, ptr, remaining, MSG_NOSIGNAL);
21 if (n <= 0) {
22 return false;
23 }
24 ptr += n;
25 remaining -= (size_t)n;
26 }
27 return true;
28 }
29  
30 bool avx_send_video_datagram(
31 avx_send_ctx_t *slot,
32 avx_client_slot_t *client,
33 const avx_tx_video_slot_t *vslot,
34 bool use_rudp)
35 {
36 size_t max_udp_payload = (size_t)AVX_UDP_MAX_FRAGS * (size_t)AVX_UDP_MAX_FRAG_SIZE;
37 size_t total_sz = vslot->header_len + vslot->payload_size;
38 if (total_sz > max_udp_payload) {
39 return false;
40 }
41  
42 uint32_t seq = ((uint32_t)client->video_packets_sent) & 0x7FFFFFFFu;
43 uint32_t fourcc = 0;
44 int64_t tc = 0;
45 if (vslot->header_len >= 32) {
46 memcpy(&fourcc, vslot->header + 12, sizeof(fourcc));
47 memcpy(&tc, vslot->header + 24, sizeof(tc));
48 }
49  
50 uint8_t *bundle = (uint8_t*)malloc(total_sz);
51 if (!bundle) return false;
52  
53 memcpy(bundle, vslot->header, vslot->header_len);
54 if (vslot->payload_size > 0 && vslot->payload) {
55 memcpy(bundle + vslot->header_len, vslot->payload, vslot->payload_size);
56 }
57  
58 int rc = use_rudp
59 ? avx_udp_rudp_send_frame(slot->rudp_sender, &client->udp_dest_addr, seq, fourcc, tc, bundle, total_sz)
60 : avx_udp_send_frame(slot->udp_sock, &client->udp_dest_addr, seq, fourcc, tc, bundle, total_sz);
61 free(bundle);
62 return (rc == 0);
63 }
64  
65 void avx_send_recalculate_tally_locked(avx_send_ctx_t* slot) {
66 uint8_t aggregate_flags = OAVX_TALLY_NONE;
67 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
68 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
69 aggregate_flags |= slot->clients[i].tally.flags;
70 }
71 }
72 if (slot->tally.flags != aggregate_flags) {
73 slot->tally.flags = aggregate_flags;
74 avx_cond_broadcast(&slot->tally_cond);
75 if (slot->web_server) {
76 avx_web_server_broadcast_tally((avx_web_server_t*)slot->web_server, &slot->tally);
77 }
78 }
79 }
80  
81 void avx_send_remove_client_locked(avx_send_ctx_t* slot, int index) {
82 if (index < 0 || index >= AVX_MAX_CLIENTS) return;
83 if (slot->clients[index].fd != AVX_INVALID_SOCKET) {
84 shutdown(slot->clients[index].fd, AVX_SHUT_RDWR);
85 avx_socket_close(slot->clients[index].fd);
86 slot->clients[index].fd = AVX_INVALID_SOCKET;
87 slot->clients[index].tally.flags = OAVX_TALLY_NONE;
88 slot->clients[index].connected_time_ns = 0;
89 if (slot->active_clients > 0) {
90 slot->active_clients--;
91 }
92  
93 /* Signal client's async tx_worker to stop */
94 avx_mutex_lock(&slot->clients[index].tx_lock);
95 slot->clients[index].tx_running = false;
96 avx_cond_broadcast(&slot->clients[index].tx_cond);
97 avx_mutex_unlock(&slot->clients[index].tx_lock);
98 }
99  
100 if (slot->clients[index].is_wan_registered) {
101 slot->clients[index].is_wan_registered = false;
102 slot->clients[index].is_wan_client = false;
103 if (slot->wan_client_count > 0) slot->wan_client_count--;
104 if (slot->wan_client_count == 0 && slot->wan_encoder) {
105 avx_video_encoder_destroy(slot->wan_encoder);
106 slot->wan_encoder = NULL;
107 slot->wan_enc_width = 0;
108 slot->wan_enc_height = 0;
109 slot->wan_enc_fourcc = 0;
110 }
111 }
112  
113 /* Update legacy alias */
114 slot->tcp_client_fd = AVX_INVALID_SOCKET;
115 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
116 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
117 slot->tcp_client_fd = slot->clients[i].fd;
118 break;
119 }
120 }
121 avx_send_recalculate_tally_locked(slot);
122 }
123  
124 /* Background worker servicing RUDP retransmission NACKs and driving periodic rate control ticks. */
125 void* avx_send_nack_service_worker(void* arg) {
126 avx_send_ctx_t* slot = (avx_send_ctx_t*)arg;
127 if (!slot) return NULL;
128 int64_t last_rc_tick_ms = 0;
129 while (slot->running && slot->nack_thread_running) {
130 if (slot->rudp_sender) {
131 avx_udp_rudp_sender_service_nacks(slot->rudp_sender);
132 }
133 int64_t now_ms = avx_time_ns() / 1000000LL;
134 if (now_ms - last_rc_tick_ms >= 50) {
135 avx_send_profiles_tick(slot, now_ms);
136 last_rc_tick_ms = now_ms;
137 }
138 avx_sleep_ms(1);
139 }
140 return NULL;
141 }
142  
143 void avx_client_queue_drain(avx_send_ctx_t* slot, avx_client_slot_t* client) {
144 if (!slot || !client) return;
145 avx_queue_item_t local_items[AVX_CLIENT_QUEUE_DEPTH];
146 int count = 0;
147  
148 avx_mutex_lock(&client->tx_lock);
149 while (client->queue_count > 0 && count < AVX_CLIENT_QUEUE_DEPTH) {
150 local_items[count++] = client->queue[client->queue_head];
151 client->queue[client->queue_head].type = AVX_QUEUE_ITEM_NONE;
152 client->queue[client->queue_head].shared_pkt = NULL;
153 client->queue_head = (client->queue_head + 1) % AVX_CLIENT_QUEUE_DEPTH;
154 client->queue_count--;
155 }
156 client->video_queued = 0;
157 avx_mutex_unlock(&client->tx_lock);
158  
159 if (count > 0) {
160 avx_mutex_lock(&slot->lock);
161 for (int i = 0; i < count; ++i) {
162 if (local_items[i].type == AVX_QUEUE_ITEM_VIDEO) {
163 if (local_items[i].shared_pkt) {
164 local_items[i].shared_pkt->refcount--;
165 if (local_items[i].shared_pkt->refcount <= 0) {
166 if (local_items[i].shared_pkt->data) free(local_items[i].shared_pkt->data);
167 free(local_items[i].shared_pkt);
168 }
169 } else {
170 int p_idx = local_items[i].video_pool_idx;
171 if (p_idx >= 0 && p_idx < AVX_TX_VIDEO_POOL_SIZE) {
172 if (slot->video_pool[p_idx].refcount > 0) {
173 slot->video_pool[p_idx].refcount--;
174 }
175 }
176 }
177 } else if (local_items[i].type == AVX_QUEUE_ITEM_AUDIO || local_items[i].type == AVX_QUEUE_ITEM_METADATA) {
178 if (local_items[i].shared_pkt) {
179 local_items[i].shared_pkt->refcount--;
180 if (local_items[i].shared_pkt->refcount <= 0) {
181 if (local_items[i].shared_pkt->data) free(local_items[i].shared_pkt->data);
182 free(local_items[i].shared_pkt);
183 }
184 }
185 }
186 }
187 avx_mutex_unlock(&slot->lock);
188 }
189 }
190  
191 /* Per-client worker transmitting queued video, audio, and metadata packets across TCP/UDP/RUDP. */
192 void* avx_send_client_tx_worker(void* arg) {
193 avx_client_slot_t* client = (avx_client_slot_t*)arg;
194 if (!client) return NULL;
195 avx_send_ctx_t* slot = client->parent_ctx;
196 int c_idx = client->client_index;
197  
198 while (1) {
199 avx_mutex_lock(&client->tx_lock);
200 while (client->tx_running && client->queue_count == 0) {
201 avx_cond_wait(&client->tx_cond, &client->tx_lock);
202 }
203  
204 if (!client->tx_running && client->queue_count == 0) {
205 avx_mutex_unlock(&client->tx_lock);
206 break;
207 }
208  
209 avx_queue_item_t item = client->queue[client->queue_head];
210 client->queue[client->queue_head].type = AVX_QUEUE_ITEM_NONE;
211 client->queue[client->queue_head].shared_pkt = NULL;
212 client->queue_head = (client->queue_head + 1) % AVX_CLIENT_QUEUE_DEPTH;
213 client->queue_count--;
214 if (item.type == AVX_QUEUE_ITEM_VIDEO) {
215 if (client->video_queued > 0) client->video_queued--;
216 }
217  
218 avx_socket_t fd = client->fd;
219 avx_mutex_unlock(&client->tx_lock);
220  
221 bool send_ok = true;
222 uint64_t tcp_sent_bytes = 0;
223 if (fd != AVX_INVALID_SOCKET) {
224 if (item.type == AVX_QUEUE_ITEM_VIDEO) {
225 if (item.shared_pkt && item.shared_pkt->data && item.shared_pkt->size > 0) {
226 /* WAN Compressed Simulcast Frame (H.264 / HEVC / AV1) */
227 if (client->transport == OAVX_TRANSPORT_RUDP && slot->rudp_sender && client->has_udp_dest) {
228 uint32_t seq = ((uint32_t)client->video_packets_sent) & 0x7FFFFFFFu;
229 uint32_t fourcc = 0;
230 int64_t tc = 0;
231 if (item.shared_pkt->size >= 32) {
232 memcpy(&fourcc, item.shared_pkt->data + 12, sizeof(fourcc));
233 memcpy(&tc, item.shared_pkt->data + 24, sizeof(tc));
234 }
235 if (avx_udp_rudp_send_frame(slot->rudp_sender, &client->udp_dest_addr,
236 seq, fourcc, tc,
237 item.shared_pkt->data, item.shared_pkt->size) != 0) {
238 send_ok = false;
239 }
240 } else if (client->transport == OAVX_TRANSPORT_UDP && slot->udp_sock != AVX_INVALID_SOCKET && client->has_udp_dest) {
241 uint32_t seq = ((uint32_t)client->video_packets_sent) & 0x7FFFFFFFu;
242 uint32_t fourcc = 0;
243 int64_t tc = 0;
244 if (item.shared_pkt->size >= 32) {
245 memcpy(&fourcc, item.shared_pkt->data + 12, sizeof(fourcc));
246 memcpy(&tc, item.shared_pkt->data + 24, sizeof(tc));
247 }
248 if (avx_udp_send_frame(slot->udp_sock, &client->udp_dest_addr,
249 seq, fourcc, tc,
250 item.shared_pkt->data, item.shared_pkt->size) != 0) {
251 send_ok = false;
252 }
253 } else {
254 if (!avx_socket_send_all(fd, item.shared_pkt->data, item.shared_pkt->size)) {
255 send_ok = false;
256 } else {
257 tcp_sent_bytes += (uint64_t)item.shared_pkt->size;
258 }
259 }
260 } else {
261 int p_idx = item.video_pool_idx;
262 if (p_idx >= 0 && p_idx < AVX_TX_VIDEO_POOL_SIZE) {
263 avx_tx_video_slot_t *vslot = &slot->video_pool[p_idx];
264 if (client->transport == OAVX_TRANSPORT_RUDP && slot->rudp_sender && client->has_udp_dest) {
265 send_ok = avx_send_video_datagram(slot, client, vslot, true);
266 } else if (client->transport == OAVX_TRANSPORT_UDP && slot->udp_sock != AVX_INVALID_SOCKET && client->has_udp_dest) {
267 send_ok = avx_send_video_datagram(slot, client, vslot, false);
268 } else {
269 if (vslot->metadata_buf && vslot->metadata_len > 0) {
270 if (!avx_socket_send_all(fd, vslot->metadata_hdr, vslot->metadata_hdr_len) ||
271 !avx_socket_send_all(fd, vslot->metadata_buf, vslot->metadata_len)) {
272 send_ok = false;
273 } else {
274 tcp_sent_bytes += (uint64_t)vslot->metadata_hdr_len + (uint64_t)vslot->metadata_len;
275 }
276 }
277 if (send_ok) {
278 if (!avx_socket_send_all(fd, vslot->header, vslot->header_len) ||
279 !avx_socket_send_all(fd, vslot->payload, vslot->payload_size)) {
280 send_ok = false;
281 } else {
282 tcp_sent_bytes += (uint64_t)vslot->header_len + (uint64_t)vslot->payload_size;
283 }
284 }
285 }
286 }
287 }
288 } else if (item.type == AVX_QUEUE_ITEM_AUDIO || item.type == AVX_QUEUE_ITEM_METADATA) {
289 if (item.shared_pkt && item.shared_pkt->data && item.shared_pkt->size > 0) {
290 if (item.type == AVX_QUEUE_ITEM_AUDIO && client->transport == OAVX_TRANSPORT_RUDP && slot->rudp_sender && client->has_udp_dest) {
291 uint32_t seq = 0x80000000u | (((uint32_t)client->audio_packets_sent) & 0x7FFFFFFFu);
292 uint32_t udp_fourcc = OAVX_FOURCC_AUDIO_TYPE_FLTP;
293 if (item.shared_pkt->size >= 8) {
294 uint32_t pkt_magic = 0;
295 memcpy(&pkt_magic, item.shared_pkt->data, 4);
296 if (pkt_magic == OAVX_WIRE_MAGIC_AUDIO_COMP) {
297 memcpy(&udp_fourcc, item.shared_pkt->data + 4, 4);
298 }
299 }
300 if (avx_udp_rudp_send_frame(slot->rudp_sender, &client->udp_dest_addr,
301 seq, udp_fourcc, 0,
302 item.shared_pkt->data, item.shared_pkt->size) != 0) {
303 send_ok = false;
304 }
305 } else if (item.type == AVX_QUEUE_ITEM_AUDIO && client->transport == OAVX_TRANSPORT_UDP && slot->udp_sock != AVX_INVALID_SOCKET && client->has_udp_dest) {
306 uint32_t seq = 0x80000000u | (((uint32_t)client->audio_packets_sent) & 0x7FFFFFFFu);
307 uint32_t udp_fourcc = OAVX_FOURCC_AUDIO_TYPE_FLTP;
308 if (item.shared_pkt->size >= 8) {
309 uint32_t pkt_magic = 0;
310 memcpy(&pkt_magic, item.shared_pkt->data, 4);
311 if (pkt_magic == OAVX_WIRE_MAGIC_AUDIO_COMP) {
312 memcpy(&udp_fourcc, item.shared_pkt->data + 4, 4);
313 }
314 }
315 if (avx_udp_send_frame(slot->udp_sock, &client->udp_dest_addr,
316 seq, udp_fourcc, 0,
317 item.shared_pkt->data, item.shared_pkt->size) != 0) {
318 send_ok = false;
319 }
320 } else {
321 if (!avx_socket_send_all(fd, item.shared_pkt->data, item.shared_pkt->size)) {
322 send_ok = false;
323 } else {
324 tcp_sent_bytes += (uint64_t)item.shared_pkt->size;
325 }
326 }
327 }
328 }
329 } else {
330 send_ok = false;
331 }
332  
333 /* Post-send: release refcounts under slot->lock */
334 avx_mutex_lock(&slot->lock);
335  
336 if (item.type == AVX_QUEUE_ITEM_VIDEO) {
337 if (item.shared_pkt) {
338 item.shared_pkt->refcount--;
339 if (item.shared_pkt->refcount <= 0) {
340 if (item.shared_pkt->data) free(item.shared_pkt->data);
341 free(item.shared_pkt);
342 }
343 } else {
344 int p_idx = item.video_pool_idx;
345 if (p_idx >= 0 && p_idx < AVX_TX_VIDEO_POOL_SIZE) {
346 if (slot->video_pool[p_idx].refcount > 0) {
347 slot->video_pool[p_idx].refcount--;
348 }
349 }
350 }
351 } else if (item.type == AVX_QUEUE_ITEM_AUDIO || item.type == AVX_QUEUE_ITEM_METADATA) {
352 if (item.shared_pkt) {
353 item.shared_pkt->refcount--;
354 if (item.shared_pkt->refcount <= 0) {
355 if (item.shared_pkt->data) free(item.shared_pkt->data);
356 free(item.shared_pkt);
357 }
358 }
359 }
360  
361 if (!send_ok) {
362 if (slot->clients[c_idx].fd == fd) {
363 avx_send_remove_client_locked(slot, c_idx);
364 }
365 avx_mutex_unlock(&slot->lock);
366 break;
367 }
368  
369 avx_mutex_unlock(&slot->lock);
370  
371 if (tcp_sent_bytes > 0) {
372 avx_mutex_lock(&client->tx_lock);
373 client->tcp_bytes_submitted += tcp_sent_bytes;
374 avx_mutex_unlock(&client->tx_lock);
375 }
376 }
377  
378 /* Drain any remaining queue items upon thread exit */
379 avx_client_queue_drain(slot, client);
380 return NULL;
381 }
382  
383 /* Background worker polling client sockets and parsing incoming wire commands (PTZ, tally, ping). */
384 void* avx_send_client_rx_worker(void* arg) {
385 avx_send_ctx_t* slot = (avx_send_ctx_t*)arg;
386  
387 while (slot->running && slot->client_rx_running) {
388 avx_pollfd_t pfds[AVX_MAX_CLIENTS];
389 int client_indices[AVX_MAX_CLIENTS];
390 int nfds = 0;
391  
392 avx_mutex_lock(&slot->lock);
393 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
394 if (slot->clients[i].fd != AVX_INVALID_SOCKET) {
395 pfds[nfds].fd = slot->clients[i].fd;
396 pfds[nfds].events = POLLIN;
397 pfds[nfds].revents = 0;
398 client_indices[nfds] = i;
399 nfds++;
400 }
401 }
402 avx_mutex_unlock(&slot->lock);
403  
404 if (nfds == 0) {
405 avx_sleep_ms(20);
406 continue;
407 }
408  
409 int pr = avx_poll(pfds, nfds, 100);
410 if (pr <= 0) continue;
411  
412 for (int p = 0; p < nfds; ++p) {
413 if (pfds[p].revents == 0) continue;
414  
415 int c_idx = client_indices[p];
416 avx_socket_t fd = pfds[p].fd;
417  
418 if (pfds[p].revents & (POLLHUP | POLLERR)) {
419 avx_mutex_lock(&slot->lock);
420 if (slot->clients[c_idx].fd == fd) {
421 avx_send_remove_client_locked(slot, c_idx);
422 }
423 avx_mutex_unlock(&slot->lock);
424 continue;
425 }
426  
427 if (pfds[p].revents & POLLIN) {
428 uint32_t magic = 0;
429 ssize_t n = recv(fd, (char*)&magic, sizeof(magic), MSG_WAITALL);
430 if (n <= 0) {
431 avx_mutex_lock(&slot->lock);
432 if (slot->clients[c_idx].fd == fd) {
433 avx_send_remove_client_locked(slot, c_idx);
434 }
435 avx_mutex_unlock(&slot->lock);
436 continue;
437 }
438  
439 if (magic == slot->wire_profile.magic_metadata ||
440 (slot->wire_profile.compat_magic_metadata && magic == slot->wire_profile.compat_magic_metadata)) {
441 AVX_PACKED_START
442 struct {
443 int64_t timecode;
444 uint32_t payload_len;
445 } AVX_PACKED mhdr;
446 AVX_PACKED_END
447  
448 if (recv(fd, (char*)&mhdr, sizeof(mhdr), MSG_WAITALL) != (ssize_t)sizeof(mhdr)) {
449 avx_mutex_lock(&slot->lock);
450 if (slot->clients[c_idx].fd == fd) {
451 avx_send_remove_client_locked(slot, c_idx);
452 }
453 avx_mutex_unlock(&slot->lock);
454 continue;
455 }
456  
457 if (mhdr.payload_len > 0 && mhdr.payload_len < 65536) {
458 char *mbuf = (char*)malloc(mhdr.payload_len + 1);
459 if (!mbuf) continue;
460 if (recv(fd, mbuf, mhdr.payload_len, MSG_WAITALL) != (ssize_t)mhdr.payload_len) {
461 free(mbuf);
462 avx_mutex_lock(&slot->lock);
463 if (slot->clients[c_idx].fd == fd) {
464 avx_send_remove_client_locked(slot, c_idx);
465 }
466 avx_mutex_unlock(&slot->lock);
467 continue;
468 }
469 mbuf[mhdr.payload_len] = '\0';
470  
471 avx_trace_packet("[RX]", "METADATA (REVERSE)", mbuf, mhdr.payload_len);
472  
473 avx_mutex_lock(&slot->lock);
474 if (slot->clients[c_idx].fd == fd) {
475 /* Check for Tally XML */
476 if (strstr(mbuf, slot->wire_profile.tally_tag) != NULL || strstr(mbuf, "tally") != NULL) {
477 const char *prog = strstr(mbuf, "on_program=\"");
478 const char *prev = strstr(mbuf, "on_preview=\"");
479 const char *rec = strstr(mbuf, "on_recording=\"");
480 if (!rec) rec = strstr(mbuf, "recording=\"");
481 slot->clients[c_idx].tally.flags = OAVX_TALLY_NONE;
482 if (prog && strncmp(prog + 12, "true", 4) == 0) {
483 slot->clients[c_idx].tally.flags |= OAVX_TALLY_PROGRAM;
484 }
485 if (prev && strncmp(prev + 12, "true", 4) == 0) {
486 slot->clients[c_idx].tally.flags |= OAVX_TALLY_PREVIEW;
487 }
488 if (rec) {
489 const char *val = strchr(rec, '"');
490 if (val && strncmp(val + 1, "true", 4) == 0) {
491 slot->clients[c_idx].tally.flags |= OAVX_TALLY_RECORDING;
492 }
493 }
494 avx_send_recalculate_tally_locked(slot);
495 }
496  
497 /* Check for Transport negotiation XML from client */
498 if (strstr(mbuf, "transport") != NULL) {
499 const char *m_attr = strstr(mbuf, "mode=\"");
500 if (m_attr) {
501 if (strncmp(m_attr + 6, "rudp", 4) == 0) slot->clients[c_idx].transport = OAVX_TRANSPORT_RUDP;
502 else if (strncmp(m_attr + 6, "udp", 3) == 0) slot->clients[c_idx].transport = OAVX_TRANSPORT_UDP;
503 else if (strncmp(m_attr + 6, "tcp", 3) == 0) slot->clients[c_idx].transport = OAVX_TRANSPORT_TCP;
504 }
505 const char *p_attr = strstr(mbuf, "port=\"");
506 if (p_attr) {
507 int cp = atoi(p_attr + 6);
508 if (cp > 0 && cp <= 65535) {
509 if (slot->clients[c_idx].udp_dest_addr.ss_family == AF_INET6) {
510 ((struct sockaddr_in6*)&slot->clients[c_idx].udp_dest_addr)->sin6_port = htons((uint16_t)cp);
511 slot->clients[c_idx].has_udp_dest = true;
512 } else if (slot->clients[c_idx].udp_dest_addr.ss_family == AF_INET) {
513 ((struct sockaddr_in*)&slot->clients[c_idx].udp_dest_addr)->sin_port = htons((uint16_t)cp);
514 slot->clients[c_idx].has_udp_dest = true;
515 }
516 }
517 }
518  
519 const char *c_attr = strstr(mbuf, "codecs=\"");
520 if (c_attr) {
521 char c_val[64];
522 c_val[0] = '\0';
523 const char *q_end = strchr(c_attr + 8, '"');
524 if (q_end) {
525 size_t q_len = (size_t)(q_end - (c_attr + 8));
526 if (q_len >= sizeof(c_val)) q_len = sizeof(c_val) - 1;
527 memcpy(c_val, c_attr + 8, q_len);
528 c_val[q_len] = '\0';
529 slot->clients[c_idx].negotiated_codec_fourcc = avx_negotiate_best_codec(c_val);
530 }
531 }
532  
533 const char *prof_attr = strstr(mbuf, "profile=\"");
534 bool force_wan = false;
535 bool force_lan = false;
536 if (prof_attr) {
537 if (strncmp(prof_attr + 9, "wan", 3) == 0) force_wan = true;
538 else if (strncmp(prof_attr + 9, "lan", 3) == 0) force_lan = true;
539 }
540  
541 bool is_wan = false;
542 if (force_wan) {
543 is_wan = true;
544 } else if (force_lan) {
545 is_wan = false;
546 } else {
547 is_wan = !avx_is_lan_sockaddr(&slot->clients[c_idx].addr);
548 }
549  
550 if (is_wan && !slot->clients[c_idx].is_wan_registered) {
551 slot->clients[c_idx].is_wan_client = true;
552 slot->clients[c_idx].is_wan_registered = true;
553 slot->wan_client_count++;
554 if (slot->wan_codec_fourcc == 0 || slot->clients[c_idx].negotiated_codec_fourcc != 0) {
555 slot->wan_codec_fourcc = slot->clients[c_idx].negotiated_codec_fourcc
556 ? slot->clients[c_idx].negotiated_codec_fourcc
557 : OAVX_FOURCC_VIDEO_TYPE_H264;
558 }
559 if (slot->wan_encoder) {
560 avx_video_encoder_request_keyframe(slot->wan_encoder);
561 }
562 } else if (!is_wan && slot->clients[c_idx].is_wan_registered) {
563 slot->clients[c_idx].is_wan_client = false;
564 slot->clients[c_idx].is_wan_registered = false;
565 if (slot->wan_client_count > 0) slot->wan_client_count--;
566 if (slot->wan_client_count == 0 && slot->wan_encoder) {
567 avx_video_encoder_destroy(slot->wan_encoder);
568 slot->wan_encoder = NULL;
569 slot->wan_enc_width = 0;
570 slot->wan_enc_height = 0;
571 slot->wan_enc_fourcc = 0;
572 }
573 if (slot->video_encoder) {
574 avx_video_encoder_request_keyframe(slot->video_encoder);
575 }
576 }
577 }
578  
579 /* Store last metadata */
580 snprintf(slot->last_metadata, sizeof(slot->last_metadata), "%s", mbuf);
581 slot->has_new_metadata = true;
582 }
583 avx_mutex_unlock(&slot->lock);
584  
585 free(mbuf);
586 }
587 }
588 }
589 }
590 }
591 return NULL;
592 }
593  
594 /* TCP listener thread accepting incoming connections and performing initial client handshake. */
595 void* avx_send_listen_worker(void* arg) {
596 avx_send_ctx_t* slot = (avx_send_ctx_t*)arg;
597  
598 while (slot->running) {
599 avx_socket_t listen_fd;
600 avx_mutex_lock(&slot->lock);
601 listen_fd = slot->tcp_listen_fd;
602 avx_mutex_unlock(&slot->lock);
603  
604 if (listen_fd == AVX_INVALID_SOCKET || !slot->running) {
605 break;
606 }
607  
608 /* Periodic mDNS announcement refresh (every 30 seconds) */
609 int64_t now_ns = avx_time_ns();
610 if (slot->last_mdns_broadcast_ns == 0 || (now_ns - slot->last_mdns_broadcast_ns) > 30000000000LL) {
611 slot->last_mdns_broadcast_ns = now_ns;
612 avx_mdns_broadcast_source_ex(slot->name, slot->port, slot->advertised_ip);
613 }
614  
615 avx_pollfd_t pfd;
616 pfd.fd = listen_fd;
617 pfd.events = POLLIN;
618 pfd.revents = 0;
619  
620 int pr = avx_poll(&pfd, 1, 50);
621 if (pr <= 0) {
622 continue;
623 }
624  
625 if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
626 break;
627 }
628  
629 if (!(pfd.revents & POLLIN)) {
630 continue;
631 }
632  
633 if (!slot->running) break;
634  
635 struct sockaddr_storage client_addr;
636 avx_socklen_t client_len = sizeof(client_addr);
637 avx_socket_t client_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &client_len);
638 if (client_fd == AVX_INVALID_SOCKET) {
639 if (!slot->running) break;
640 avx_sleep_ms(10);
641 continue;
642 }
643  
644 avx_socket_set_nonblocking(client_fd, false);
645 avx_socket_set_nosigpipe(client_fd);
646 avx_socket_set_keepalive(client_fd, 2, 1, 3);
647 avx_socket_set_tcp_nodelay(client_fd, true);
648 int buf_size = 16 * 1024 * 1024;
649 setsockopt(client_fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
650 setsockopt(client_fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
651  
652 struct timeval tv;
653 tv.tv_sec = 0;
654 tv.tv_usec = 250000; /* 250 ms send timeout to prevent blocking indefinitely */
655 setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
656  
657 avx_mutex_lock(&slot->lock);
658  
659 /* Check if we reached max simultaneous clients */
660 if (slot->active_clients >= slot->max_clients) {
661 avx_mutex_unlock(&slot->lock);
662 avx_socket_close(client_fd);
663 continue;
664 }
665  
666 /* Find free client slot */
667 int assigned_slot = -1;
668 avx_thread_t prev_thread = 0;
669 bool join_prev = false;
670  
671 for (int i = 0; i < slot->max_clients && i < AVX_MAX_CLIENTS; ++i) {
672 if (slot->clients[i].fd == AVX_INVALID_SOCKET) {
673 assigned_slot = i;
674 if (slot->clients[i].tx_thread_active) {
675 prev_thread = slot->clients[i].tx_thread;
676 join_prev = true;
677 slot->clients[i].tx_thread_active = false;
678 slot->clients[i].tx_thread = 0;
679 }
680 break;
681 }
682 }
683  
684 if (assigned_slot < 0) {
685 avx_mutex_unlock(&slot->lock);
686 avx_socket_close(client_fd);
687 continue;
688 }
689  
690 /* If previous thread was active on this slot, signal it to stop */
691 if (join_prev) {
692 avx_mutex_lock(&slot->clients[assigned_slot].tx_lock);
693 slot->clients[assigned_slot].tx_running = false;
694 avx_cond_broadcast(&slot->clients[assigned_slot].tx_cond);
695 avx_mutex_unlock(&slot->clients[assigned_slot].tx_lock);
696 }
697  
698 avx_mutex_unlock(&slot->lock);
699  
700 /* Join previous thread completely before reusing this slot */
701 if (join_prev) {
702 avx_thread_join(prev_thread);
703 avx_client_queue_drain(slot, &slot->clients[assigned_slot]);
704 }
705  
706 if (!slot->running) {
707 avx_socket_close(client_fd);
708 break;
709 }
710  
711 /* Now acquire lock and safely initialize the slot for the new client */
712 avx_mutex_lock(&slot->lock);
713 if (!slot->running) {
714 avx_mutex_unlock(&slot->lock);
715 avx_socket_close(client_fd);
716 break;
717 }
718  
719 slot->clients[assigned_slot].fd = client_fd;
720 slot->clients[assigned_slot].addr = client_addr;
721 slot->clients[assigned_slot].connected_time_ns = avx_time_ns();
722 slot->clients[assigned_slot].dropped_frames = 0;
723 slot->clients[assigned_slot].tally.flags = OAVX_TALLY_NONE;
724 slot->clients[assigned_slot].transport = slot->transport;
725 slot->clients[assigned_slot].has_udp_dest = false;
726 memset(&slot->clients[assigned_slot].udp_dest_addr, 0, sizeof(slot->clients[assigned_slot].udp_dest_addr));
727 slot->clients[assigned_slot].udp_dest_addr = client_addr;
728 if (client_addr.ss_family == AF_INET) {
729 ((struct sockaddr_in*)&slot->clients[assigned_slot].udp_dest_addr)->sin_port = 0;
730 } else if (client_addr.ss_family == AF_INET6) {
731 ((struct sockaddr_in6*)&slot->clients[assigned_slot].udp_dest_addr)->sin6_port = 0;
732 }
733 slot->active_clients++;
734  
735 if (slot->tcp_client_fd == AVX_INVALID_SOCKET) {
736 slot->tcp_client_fd = client_fd;
737 }
738  
739 bool is_wan = !avx_is_lan_sockaddr(&client_addr);
740 slot->clients[assigned_slot].is_wan_client = is_wan;
741 slot->clients[assigned_slot].is_wan_registered = is_wan;
742 slot->clients[assigned_slot].negotiated_codec_fourcc = OAVX_FOURCC_VIDEO_TYPE_H264;
743 if (is_wan) {
744 slot->wan_client_count++;
745 if (slot->wan_codec_fourcc == 0) slot->wan_codec_fourcc = OAVX_FOURCC_VIDEO_TYPE_H264;
746 }
747  
748 /* Reset per-client queue and enable queueing */
749 avx_mutex_lock(&slot->clients[assigned_slot].tx_lock);
750 slot->clients[assigned_slot].queue_head = 0;
751 slot->clients[assigned_slot].queue_tail = 0;
752 slot->clients[assigned_slot].queue_count = 0;
753 slot->clients[assigned_slot].video_queued = 0;
754 slot->clients[assigned_slot].congestion_level = 0;
755 slot->clients[assigned_slot].frame_seq = 0;
756 slot->clients[assigned_slot].audio_packets_sent = 0;
757 slot->clients[assigned_slot].video_packets_sent = 0;
758 slot->clients[assigned_slot].tcp_bytes_submitted = 0;
759 slot->clients[assigned_slot].last_acked_bytes = 0;
760 slot->clients[assigned_slot].rate_window_start_acked = 0;
761 slot->clients[assigned_slot].rate_window_start_sub = 0;
762 slot->clients[assigned_slot].rate_window_start_ns = 0;
763 slot->clients[assigned_slot].rate_window_throttled = false;
764 slot->clients[assigned_slot].tx_bytes_per_sec = -1.0f;
765 slot->clients[assigned_slot].last_rtt_ms = 0.0f;
766 slot->clients[assigned_slot].last_rtt_sample_ns = 0;
767 slot->clients[assigned_slot].tx_running = true;
768 avx_mutex_unlock(&slot->clients[assigned_slot].tx_lock);
769  
770 /* Start reverse reader worker if not running */
771 if (!slot->client_rx_running) {
772 slot->client_rx_running = true;
773 avx_thread_create(&slot->client_rx_thread, avx_send_client_rx_worker, slot);
774 }
775  
776 /* Request immediate keyframe from video encoders so new client receives immediate IDR */
777 if (slot->video_encoder) {
778 avx_video_encoder_request_keyframe(slot->video_encoder);
779 }
780 if (slot->wan_encoder) {
781 avx_video_encoder_request_keyframe(slot->wan_encoder);
782 }
783  
784 avx_mutex_unlock(&slot->lock);
785  
786 /* Send standard wire protocol XML handshake */
787 const char *t_str = (slot->transport == OAVX_TRANSPORT_RUDP) ? "rudp" :
788 (slot->transport == OAVX_TRANSPORT_UDP ? "udp" : "tcp");
789 char xml[512];
790 int xml_len = snprintf(xml, sizeof(xml),
791 "<%s name=\"%s\" port=\"%u\" version=\"0.2.2\">\n"
792 " <capabilities video=\"1\" audio=\"1\" metadata=\"1\" transport=\"%s\" udp_port=\"%u\"/>\n"
793 "</%s>\n",
794 slot->wire_profile.handshake_tag, slot->name, slot->port,
795 t_str, slot->udp_port, slot->wire_profile.handshake_tag);
796  
797 uint32_t payload_len = (uint32_t)xml_len;
798 uint64_t init_tcp_bytes = 0;
799 ssize_t n_hdr = send(client_fd, (const char*)&payload_len, sizeof(payload_len), MSG_NOSIGNAL);
800 if (n_hdr > 0) init_tcp_bytes += (uint64_t)n_hdr;
801 ssize_t n_xml = send(client_fd, xml, payload_len, MSG_NOSIGNAL);
802 if (n_xml > 0) init_tcp_bytes += (uint64_t)n_xml;
803  
804 avx_trace_packet("[TX]", "AVX TCP HANDSHAKE", xml, payload_len);
805 uint8_t *handshake_pkt = (uint8_t*)malloc(4 + payload_len);
806 if (handshake_pkt) {
807 memcpy(handshake_pkt, &payload_len, 4);
808 memcpy(handshake_pkt + 4, xml, payload_len);
809 avx_pcap_write_tcp(htonl(0x7F000001), slot->port, htonl(0x7F000001), 54321, 1, 1, 0x18, handshake_pkt, 4 + payload_len);
810 free(handshake_pkt);
811 }
812  
813 /* Send any queued connection metadata */
814 avx_mutex_lock(&slot->lock);
815 if (!slot->running) {
816 avx_send_remove_client_locked(slot, assigned_slot);
817 avx_mutex_unlock(&slot->lock);
818 break;
819 }
820  
821 for (size_t m = 0; m < slot->num_conn_metadata; ++m) {
822 size_t mlen = strlen(slot->conn_metadata[m]);
823 AVX_PACKED_START
824 struct {
825 uint32_t magic;
826 int64_t timecode;
827 uint32_t payload_len;
828 } AVX_PACKED mhdr;
829 AVX_PACKED_END
830 mhdr.magic = slot->wire_profile.magic_metadata;
831 mhdr.timecode = 0;
832 mhdr.payload_len = (uint32_t)mlen;
833 ssize_t nm1 = send(client_fd, (const char*)&mhdr, sizeof(mhdr), MSG_NOSIGNAL);
834 if (nm1 > 0) init_tcp_bytes += (uint64_t)nm1;
835 ssize_t nm2 = send(client_fd, slot->conn_metadata[m], mlen, MSG_NOSIGNAL);
836 if (nm2 > 0) init_tcp_bytes += (uint64_t)nm2;
837 }
838  
839 if (init_tcp_bytes > 0 && slot->clients[assigned_slot].fd == client_fd) {
840 avx_mutex_lock(&slot->clients[assigned_slot].tx_lock);
841 slot->clients[assigned_slot].tcp_bytes_submitted += init_tcp_bytes;
842 avx_mutex_unlock(&slot->clients[assigned_slot].tx_lock);
843 }
844  
845 /* Launch worker thread to pump async TX queue */
846 if (avx_thread_create(&slot->clients[assigned_slot].tx_thread,
847 avx_send_client_tx_worker,
848 &slot->clients[assigned_slot]) == 0) {
849 slot->clients[assigned_slot].tx_thread_active = true;
850 } else {
851 slot->clients[assigned_slot].tx_thread_active = false;
852 }
853  
854 avx_mutex_unlock(&slot->lock);
855 }
856 return NULL;
857 }
858  
859 bool avx_send_start_listener(avx_send_ctx_t* send_ctx) {
860 if (!send_ctx) return false;
861  
862 const char *bind_ip = (send_ctx->bind_ip[0] != '\0') ? send_ctx->bind_ip : NULL;
863 send_ctx->tcp_listen_fd = avx_socket_create_tcp_server_bind(bind_ip, send_ctx->port);
864 if (send_ctx->tcp_listen_fd == AVX_INVALID_SOCKET) {
865 /* Try dynamic port fallback */
866 uint16_t base_port = send_ctx->port ? send_ctx->port : OAVX_WIRE_DEFAULT_PORT;
867 for (uint16_t alt_port = base_port + 1; alt_port <= base_port + 10; ++alt_port) {
868 send_ctx->tcp_listen_fd = avx_socket_create_tcp_server_bind(bind_ip, alt_port);
869 if (send_ctx->tcp_listen_fd != AVX_INVALID_SOCKET) {
870 send_ctx->port = alt_port;
871 break;
872 }
873 }
874 }
875  
876 if (send_ctx->tcp_listen_fd == AVX_INVALID_SOCKET) return false;
877  
878 avx_socket_set_nonblocking(send_ctx->tcp_listen_fd, true);
879  
880 if (avx_thread_create(&send_ctx->listen_thread, avx_send_listen_worker, send_ctx) != 0) {
881 avx_socket_close(send_ctx->tcp_listen_fd);
882 send_ctx->tcp_listen_fd = AVX_INVALID_SOCKET;
883 return false;
884 }
885  
886 return true;
887 }
888  
889 OPENAVX_API void avx_send_stop_listener(avx_send_ctx_t* send_ctx) {
890 if (!send_ctx) return;
891 avx_mutex_lock(&send_ctx->lock);
892 send_ctx->running = false;
893 send_ctx->client_rx_running = false;
894 send_ctx->nack_thread_running = false;
895  
896 /* Signal and close all active clients */
897 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
898 if (send_ctx->clients[i].fd != AVX_INVALID_SOCKET) {
899 shutdown(send_ctx->clients[i].fd, AVX_SHUT_RDWR);
900 avx_socket_close(send_ctx->clients[i].fd);
901 send_ctx->clients[i].fd = AVX_INVALID_SOCKET;
902 }
903 avx_mutex_lock(&send_ctx->clients[i].tx_lock);
904 send_ctx->clients[i].tx_running = false;
905 avx_cond_broadcast(&send_ctx->clients[i].tx_cond);
906 avx_mutex_unlock(&send_ctx->clients[i].tx_lock);
907 }
908 send_ctx->active_clients = 0;
909 send_ctx->tcp_client_fd = AVX_INVALID_SOCKET;
910 if (send_ctx->tcp_listen_fd != AVX_INVALID_SOCKET) {
911 shutdown(send_ctx->tcp_listen_fd, AVX_SHUT_RDWR);
912 avx_socket_close(send_ctx->tcp_listen_fd);
913 send_ctx->tcp_listen_fd = AVX_INVALID_SOCKET;
914 }
915 avx_mutex_unlock(&send_ctx->lock);
916  
917 /* Join all active client tx worker threads */
918 for (int i = 0; i < AVX_MAX_CLIENTS; ++i) {
919 if (send_ctx->clients[i].tx_thread_active) {
920 avx_thread_join(send_ctx->clients[i].tx_thread);
921 send_ctx->clients[i].tx_thread_active = false;
922 send_ctx->clients[i].tx_thread = 0;
923 }
924 avx_client_queue_drain(send_ctx, &send_ctx->clients[i]);
925 }
926  
927 if (send_ctx->listen_thread) {
928 avx_thread_join(send_ctx->listen_thread);
929 send_ctx->listen_thread = 0;
930 }
931 if (send_ctx->client_rx_thread) {
932 avx_thread_join(send_ctx->client_rx_thread);
933 send_ctx->client_rx_thread = 0;
934 }
935 if (send_ctx->nack_thread_active) {
936 send_ctx->nack_thread_running = false;
937 avx_thread_join(send_ctx->nack_thread);
938 send_ctx->nack_thread_active = false;
939 send_ctx->nack_thread = 0;
940 }
941 }