ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
backpressure.c
Go to the documentation of this file.
2#include <ascii-chat/otel.h>
6#include <libplatform/cond.h>
7#include <libplatform/thread.h>
8#include <ascii-chat/buffer.h>
9#include <ascii-chat/common.h>
12#include <string.h>
13
14#define OUTBOUND_MAX_PACKETS 512
15#define OUTBOUND_MAX_STREAMS 64
16#define WIRE_OVERHEAD (sizeof(packet_header_t) + 32 + CRYPTO_NONCE_SIZE + CRYPTO_MAC_SIZE)
17
32
49
68
69static size_t backend_bytes(acip_outbound_t *out) {
70 return out->transport->methods->queued_bytes ? out->transport->methods->queued_bytes(out->transport) : 0;
71}
72
73static outbound_stream_t *stream_state(acip_outbound_t *out, uint16_t type, uint32_t id) {
74 size_t stream_count = (size_t)atomic_load_u64(&out->stream_count);
75 for (size_t i = 0; i < stream_count; ++i)
76 if (out->streams[i].type == type && out->streams[i].stream == id) {
77 out->streams[i].last_used_ns = time_get_ns();
78 return &out->streams[i];
79 }
80 if (stream_count == OUTBOUND_MAX_STREAMS) {
81 size_t victim = OUTBOUND_MAX_STREAMS;
82 for (size_t i = 0; i < stream_count; ++i) {
83 bool pending = false;
84 for (outbound_packet_t *p = out->head; p; p = p->next)
85 if (p->encoded && p->type == out->streams[i].type && p->stream == out->streams[i].stream) {
86 pending = true;
87 break;
88 }
89 if (!pending && (victim == OUTBOUND_MAX_STREAMS || out->streams[i].last_used_ns < out->streams[victim].last_used_ns))
90 victim = i;
91 }
92 if (victim == OUTBOUND_MAX_STREAMS) {
93 log_warn("Outbound stream state limit reached (%u); all stream slots are active", OUTBOUND_MAX_STREAMS);
94 return NULL;
95 }
96 log_warn("Evicting inactive outbound stream state for type %u stream %u", out->streams[victim].type, out->streams[victim].stream);
97 outbound_stream_t *stream = &out->streams[victim];
98 *stream = (outbound_stream_t){.type = type, .stream = id, .last_used_ns = time_get_ns()};
99 atomic_store_bool(&stream->needs_keyframe, true);
100 return stream;
101 }
102 size_t index = stream_count;
103 outbound_stream_t *stream = &out->streams[index];
104 *stream = (outbound_stream_t){.type = type, .stream = id, .last_used_ns = time_get_ns()};
105 atomic_store_bool(&stream->needs_keyframe, true);
106 // Publish immutable identity only after initialization. The keyframe bit is
107 // atomic because it is updated independently of the stream identity.
108 atomic_store_u64(&out->stream_count, index + 1);
109 return stream;
110}
111
112// Keep a small connection-owned working set instead of visiting the global
113// allocator and buffer domain for every media packet. All access holds mutex.
114static void packet_free(acip_outbound_t *out, outbound_packet_t *packet) {
115 if (!out->stopping && !out->failed && out->recycled_count < 8 && buffer_capacity(packet->data) <= 256 * 1024) {
116 packet->next = out->recycled;
117 out->recycled = packet;
118 ++out->recycled_count;
119 return;
120 }
121 buffer_release(packet->data);
122 SAFE_FREE(packet);
123}
124
125static bool same_stream(const outbound_packet_t *a, const outbound_packet_t *b) {
126 return a->type == b->type && a->stream == b->stream;
127}
128
129static bool outbound_insert_packet(acip_outbound_t *out, outbound_packet_t *packet, bool priority) {
130 outbound_packet_t **link = &out->head;
131 if (priority) {
132 for (outbound_packet_t **scan = &out->head; *scan; scan = &(*scan)->next)
133 if (!(*scan)->video && !(*scan)->audio && (*scan)->type != PACKET_TYPE_PING && (*scan)->type != PACKET_TYPE_PONG)
134 link = &(*scan)->next;
135 }
136 while (*link && (!priority || !(*link)->video))
137 link = &(*link)->next;
138 bool was_empty = out->head == NULL;
139 packet->next = *link;
140 *link = packet;
141 return was_empty;
142}
143
144/* Conservatively invalidate all unsent encoded output for this stream. The
145 * producer requests an IDR with parameter sets before resuming its chain. */
146static void discard_stream(acip_outbound_t *out, const outbound_packet_t *video) {
147 if (video->encoded) {
148 outbound_stream_t *stream = stream_state(out, video->type, video->stream);
149 if (stream)
150 atomic_store_bool(&stream->needs_keyframe, true);
151 }
152 outbound_packet_t **link = &out->head;
153 while (*link) {
154 outbound_packet_t *packet = *link;
155 if (packet->video && same_stream(packet, video)) {
156 *link = packet->next;
157 out->bytes -= packet->cost;
158 --out->count;
159 atomic_fetch_add_u64(&out->dropped, 1);
160 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_DROP, 1);
161 packet_free(out, packet);
162 } else {
163 link = &packet->next;
164 }
165 }
166}
167
168static void expire_video(acip_outbound_t *out, uint64_t now) {
169 for (;;) {
170 outbound_packet_t *expired = NULL;
171 for (outbound_packet_t *p = out->head; p; p = p->next)
172 if (p->video && now - p->created > ACIP_OUTBOUND_VIDEO_AGE_NS) {
173 expired = p;
174 break;
175 }
176 if (!expired)
177 break;
178 outbound_packet_t identity = *expired;
179 discard_stream(out, &identity);
180 }
181}
182
183static void expire_datagrams(acip_outbound_t *out, uint64_t now) {
184 outbound_packet_t **link = &out->head;
185 while (*link) {
186 outbound_packet_t *packet = *link;
187 if (packet->options.delivery != ACIP_DELIVERY_DATAGRAM || !packet->options.deadline_ns || packet->options.deadline_ns > now) {
188 link = &packet->next;
189 continue;
190 }
191 if (packet->encoded) {
192 outbound_packet_t identity = *packet;
193 discard_stream(out, &identity);
194 link = &out->head;
195 continue;
196 }
197 *link = packet->next;
198 out->bytes -= packet->cost;
199 --out->count;
200 atomic_fetch_add_u64(&out->dropped, 1);
201 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_DROP, 1);
202 packet_free(out, packet);
203 }
204}
205
206// Keep the terminal wrapper plus its relevant nested cause. Follow causal IDs,
207// not merely older registry entries, and never cross this send's checkpoint.
208static asciichat_error_context_t backend_failure_detail(asciichat_errno_scope_t scope, const asciichat_error_context_t *cause) {
210 size_t count = errno_snapshot(scope.thread_id, frames, ASCIICHAT_ERRNO_MAX_DEPTH).copied;
211 asciichat_error_context_t detail = {0};
212 uint64_t next = cause->cause_id;
213 for (size_t i = 0; i < count && next; ++i) {
214 if (frames[i].generation != scope.generation || frames[i].error_id <= scope.after_id)
215 continue;
216 if (frames[i].error_id != next)
217 continue;
218 if (!detail.has_system_error && !detail.has_wsa_error)
219 detail = frames[i];
220 else if (frames[i].has_system_error || frames[i].has_wsa_error)
221 detail = frames[i];
222 next = frames[i].cause_id;
223 }
224 return detail;
225}
226
227static asciichat_error_t import_failure(const asciichat_error_context_t *cause, const asciichat_error_context_t *detail) {
228 if (detail->code != ASCIICHAT_OK && !cause->has_system_error && !cause->has_wsa_error) {
229 errno_import(detail);
230 // Recreate the wrapper at its original source location. Normal recording
231 // links it to the newly imported cause in this producer's registry; simply
232 // importing both would leave the wrapper pointing at the handled worker ID.
233 return errno_set_with_message(cause->code, cause->file, cause->line, cause->function, "%s", cause->context_message);
234 }
235 return errno_import(cause);
236}
237
238// The caller holds mutex. Retain the first terminal cause, reject later
239// admissions, and wake queued producers with that failure. Backend close is
240// performed by the worker after releasing mutex.
241static void outbound_record_failure_and_fail_pending(acip_outbound_t *out, asciichat_error_t code, const asciichat_error_context_t *cause, const asciichat_error_context_t *detail) {
242 if (!out->failed) {
243 out->failure_code = code;
244 if (cause)
245 out->failure = *cause;
246 if (detail)
247 out->failure_detail = *detail;
248 }
249 out->failed = true;
250 while (out->head) {
251 outbound_packet_t *p = out->head;
252 out->head = p->next;
253 out->bytes -= p->cost;
254 --out->count;
255 if (p->wait) {
256 p->result = out->failure_code;
257 p->done = true;
258 } else {
259 packet_free(out, p);
260 }
261 }
262 cond_broadcast(&out->changed);
263}
264
265static asciichat_error_t outbound_send(acip_outbound_t *out, const outbound_packet_t *packet) {
266 ASCII_OTEL_SCOPE_PARENT(ACIP_OUTBOUND_SEND, &packet->telemetry_context);
267 ASCII_OTEL_PACKET(packet->type, packet->size >= sizeof(packet_header_t) ? packet->size - sizeof(packet_header_t) : 0, "send", acip_transport_get_type(out->transport));
268 uint64_t wait_ns = time_get_ns() - packet->created;
269 ASCII_OTEL_ATTR_INT("network.queue.wait_ns", wait_ns);
270 ASCII_OTEL_ATTR_STRING("network.packet.category", packet->video ? "video" : packet->audio ? "audio" : "control");
271 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_WAIT, (double)wait_ns / 1e9);
272 if (out->transport->methods->sendv_ex) {
273 socket_buffer_t buffer = {packet->data, packet->size};
274 return out->transport->methods->sendv_ex(out->transport, &buffer, 1, &packet->options);
275 }
276 return out->transport->methods->send(out->transport, packet->data, packet->size);
277}
278
279static void *outbound_worker(void *arg) {
280 acip_outbound_t *out = arg;
281 mutex_lock(&out->mutex);
282 while (!out->stopping && !out->failed) {
283 uint64_t now = time_get_ns();
284 expire_video(out, now);
285 expire_datagrams(out, now);
286 outbound_packet_t *p = out->head;
287 if (!p) {
288 cond_timedwait(&out->changed, &out->mutex, 100 * NS_PER_MS_INT);
289 continue;
290 }
291 // Rotation uses this same serialized writer for every transport. Flush
292 // only when work is queued; idle polling must not reacquire the queue lock.
293 mutex_unlock(&out->mutex);
294 asciichat_error_t security_result = acip_security_flush(out->transport);
295 mutex_lock(&out->mutex);
296 if (security_result != ASCIICHAT_OK) {
297 outbound_record_failure_and_fail_pending(out, security_result, NULL, NULL);
298 break;
299 }
300 now = time_get_ns();
301 p = out->head;
302 if (!p)
303 continue;
304 /* Admitted reliable traffic expires by closing the connection, never by
305 * silently removing an audio or control packet. */
306 uint64_t deadline = p->audio ? 5 * NS_PER_SEC_INT : 10 * NS_PER_SEC_INT;
307 /* Reliable expiry is terminal for control traffic only. Video and audio
308 * are media queues and are governed by their media admission/expiry
309 * policy; they must not tear down the peer merely because a slow backend
310 * delayed submission. */
311 if (!p->video && !p->audio && p->options.delivery == ACIP_DELIVERY_RELIABLE && now - p->created > deadline) {
314 SET_ERRNO(ERROR_NETWORK_TIMEOUT, "Outbound reliable packet expired before submission");
315 bool has_cause = errno_peek_since(scope, &cause);
316 outbound_record_failure_and_fail_pending(out, ERROR_NETWORK_TIMEOUT, has_cause ? &cause : NULL, NULL);
318 break;
319 }
320 // Include backend-owned bytes before reserving room for audio and control.
321 size_t backend = backend_bytes(out);
322 // Keep scheduling decisions in the plaintext queue. Even tiny reliable
323 // packets must not accumulate behind video in a backend's opaque FIFO.
324 acip_transport_capabilities_t capabilities = {0};
325 asciichat_error_t capability_result = acip_transport_get_capabilities(out->transport, &capabilities);
326 if (capability_result != ASCIICHAT_OK) {
327 outbound_record_failure_and_fail_pending(out, capability_result, NULL, NULL);
328 break;
329 }
330 /* Media must wait for opaque backends without independent streams so it
331 * cannot build an unbounded FIFO behind an already-buffered frame. A
332 * reliable control packet is different: withholding it here can make it
333 * expire while waiting behind the media backlog it is meant to control.
334 * The backend preserves ordering, so submit control traffic and let it
335 * drain normally. */
336 if (backend != 0 && !capabilities.independent_streams && (p->video || p->audio)) {
337 if (out->transport->methods->wait_writable) {
338 mutex_unlock(&out->mutex);
339 asciichat_error_t writable = out->transport->methods->wait_writable(out->transport, 10 * NS_PER_MS_INT);
340 mutex_lock(&out->mutex);
341 if (writable != ASCIICHAT_OK && writable != ERROR_NETWORK_TIMEOUT) {
342 outbound_record_failure_and_fail_pending(out, writable, NULL, NULL);
343 break;
344 }
345 } else {
346 cond_timedwait(&out->changed, &out->mutex, 2 * NS_PER_MS_INT);
347 }
348 continue;
349 }
350 out->head = p->next;
351 out->bytes -= p->cost;
352 // Admission reserves plaintext plus two wire owners. During handoff one
353 // wire owner moves into the backend's counter, so do not count it twice.
354 out->active_bytes = p->cost - (p->size + WIRE_OVERHEAD);
355 mutex_unlock(&out->mutex);
356 /* One worker fixes wire/encryption order. Backends receive only complete
357 * packets and must finish a partially submitted packet or fail the stream. */
359 asciichat_error_t result = outbound_send(out, p);
360 asciichat_error_context_t cause = {0};
361 asciichat_error_context_t detail = {0};
362 if (result != ASCIICHAT_OK) {
363 // Only this send's matching failure belongs to the submission. A backend
364 // may return a status without context, or leave an unrelated nested error.
365 if (!errno_peek_since(scope, &cause) || cause.code != result) {
366 SET_ERRNO(result, "Outbound backend submission failed");
367 errno_peek_since(scope, &cause);
368 } else {
369 detail = backend_failure_detail(scope, &cause);
370 }
371 }
373 bool datagram_drop = p->options.delivery == ACIP_DELIVERY_DATAGRAM && (result == ERROR_NETWORK_TIMEOUT || result == ERROR_BUFFER_FULL || result == ERROR_NOT_SUPPORTED);
374 if (!p->wait) {
375 mutex_lock(&out->mutex);
376 out->active_bytes = 0;
377 --out->count;
378 if (datagram_drop) {
379 if (p->encoded)
380 discard_stream(out, p);
381 atomic_fetch_add_u64(&out->dropped, 1);
382 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_DROP, 1);
383 }
384 if (result == ASCIICHAT_OK) {
385 atomic_fetch_add_u64(&out->submitted, 1);
386 if (p->encoded && p->keyframe)
387 atomic_fetch_add_u64(&out->recovery_frames, 1);
388 }
389 if (result != ASCIICHAT_OK && !datagram_drop)
390 outbound_record_failure_and_fail_pending(out, result, &cause, &detail);
391 cond_broadcast(&out->changed);
392 packet_free(out, p);
393 mutex_unlock(&out->mutex);
394 if (result != ASCIICHAT_OK && !datagram_drop)
395 break;
396 continue;
397 }
398 mutex_lock(&out->mutex);
399 out->active_bytes = 0;
400 --out->count;
401 if (datagram_drop) {
402 if (p->encoded)
403 discard_stream(out, p);
404 atomic_fetch_add_u64(&out->dropped, 1);
405 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_DROP, 1);
406 }
407 if (result == ASCIICHAT_OK) {
408 atomic_fetch_add_u64(&out->submitted, 1);
409 if (p->encoded && p->keyframe)
410 atomic_fetch_add_u64(&out->recovery_frames, 1);
411 }
412 if (p->wait) {
413 p->result = result;
414 p->done = true;
415 cond_broadcast(&out->changed);
416 }
417 if (result != ASCIICHAT_OK && !datagram_drop) {
418 outbound_record_failure_and_fail_pending(out, result, &cause, &detail);
419 break;
420 }
421 }
422 bool failed = out->failed && !out->stopped_by_caller;
423 mutex_unlock(&out->mutex);
424 if (failed)
425 out->transport->methods->close(out->transport);
426 return NULL;
427}
428
430 ASCII_OTEL_SCOPE(ACIP_OUTBOUND_CREATE);
431 if (!transport || !transport->methods || (!transport->methods->send && !transport->methods->sendv_ex))
432 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing outbound backend");
433 if (transport->outbound)
434 return ASCIICHAT_OK;
436 if (mutex_init(&out->mutex, "connection_outgoing_packet_queue") != ASCIICHAT_OK) {
437 SAFE_FREE(out);
438 return GET_ERRNO();
439 }
440 if (cond_init(&out->changed, "outgoing_packet_ready_or_done") != ASCIICHAT_OK) {
441 mutex_destroy(&out->mutex);
442 SAFE_FREE(out);
443 return GET_ERRNO();
444 }
445 out->transport = transport;
446 asciichat_error_t result = platform_thread_create(&out->worker, "outbound", outbound_worker, out);
447 if (result != ASCIICHAT_OK) {
448 cond_destroy(&out->changed);
449 mutex_destroy(&out->mutex);
450 SAFE_FREE(out);
451 return result;
452 }
453 transport->outbound = out;
454 return ASCIICHAT_OK;
455}
456
458 acip_outbound_t *out = transport ? transport->outbound : NULL;
459 if (!out)
460 return;
461 mutex_lock(&out->mutex);
462 out->stopping = true;
463 out->stopped_by_caller = true;
464 outbound_record_failure_and_fail_pending(out, ERROR_NETWORK, NULL, NULL);
465 mutex_unlock(&out->mutex);
466}
467
469 ASCII_OTEL_SCOPE(ACIP_OUTBOUND_DESTROY);
470 acip_outbound_t *out = transport->outbound;
471 if (!out)
472 return;
473 mutex_lock(&out->mutex);
474 out->stopping = true;
475 cond_broadcast(&out->changed);
476 mutex_unlock(&out->mutex);
477 /* Wake a blocked send while every backend resource is still alive. The
478 * failed-send worker also closes its backend, so wait for that worker before
479 * closing here: two concurrent closes can join the same service thread. */
480 if (transport->methods->interrupt)
481 transport->methods->interrupt(transport);
482 else
483 transport->methods->close(transport);
484 thread_join(&out->worker, NULL);
485 if (transport->methods->interrupt)
486 transport->methods->close(transport);
487 mutex_lock(&out->mutex);
488 outbound_record_failure_and_fail_pending(out, ERROR_NETWORK, NULL, NULL);
489 while (out->recycled) {
490 outbound_packet_t *p = out->recycled;
491 out->recycled = p->next;
492 packet_free(out, p);
493 }
494 mutex_unlock(&out->mutex);
495 cond_destroy(&out->changed);
496 mutex_destroy(&out->mutex);
497 SAFE_FREE(transport->outbound);
498}
499
500static asciichat_error_t outbound_submitv(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options, acip_admission_t *admission) {
501 ASCII_OTEL_SCOPE(ACIP_OUTBOUND_SUBMITV);
502 if (!transport || !transport->outbound || !buffers || !count || count > SOCKET_IOV_MAX || !admission)
503 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid outbound submission");
504 *admission = ACIP_ADMISSION_CONGESTED;
505 size_t size = 0;
506 for (size_t i = 0; i < count; ++i) {
507 if ((buffers[i].len && !buffers[i].data) || buffers[i].len > ACIP_OUTBOUND_BUDGET - WIRE_OVERHEAD - size)
508 return SET_ERRNO(ERROR_NETWORK_SIZE, "Outbound packet exceeds byte budget");
509 size += buffers[i].len;
510 }
511 packet_header_t header;
512 if (buffers[0].len < sizeof(header))
513 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing outbound ACIP header");
514 memcpy(&header, buffers[0].data, sizeof(header));
515 outbound_packet_t info = {.size = size, .cost = 3 * (size + WIRE_OVERHEAD) + sizeof(outbound_packet_t) + 128, .type = NET_TO_HOST_U16(header.type), .stream = NET_TO_HOST_U32(header.client_id)};
516 info.options = options ? *options : (acip_send_options_t){.traffic_class = acip_packet_traffic_class(info.type), .delivery = ACIP_DELIVERY_RELIABLE};
518 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid outbound send options");
520 if (!transport->methods->sendv_ex || !transport->methods->validate_send_options)
521 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Datagrams and deadlines are not supported by this transport");
523 return SET_ERRNO(ERROR_INVALID_PARAM, "Datagram flow does not match packet type");
524 asciichat_error_t result = transport->methods->validate_send_options(transport, &info.options);
525 if (result != ASCIICHAT_OK)
526 return result;
527 if (info.options.deadline_ns && info.options.deadline_ns <= time_get_ns())
528 return SET_ERRNO(ERROR_NETWORK_TIMEOUT, "Outbound datagram deadline expired");
529 }
531 info.video = info.encoded || info.type == PACKET_TYPE_IMAGE_FRAME || info.type == PACKET_TYPE_ASCII_FRAME;
533 ASCII_OTEL_ATTR_STRING("network.packet.category", info.video ? "video" : info.audio ? "audio" : "control");
534 info.wait = !info.video && !info.audio && info.type != PACKET_TYPE_PING && info.type != PACKET_TYPE_PONG;
535 if (info.encoded) {
536 const uint8_t *flags = NULL;
537 if (buffers[0].len > sizeof(header))
538 flags = (const uint8_t *)buffers[0].data + sizeof(header);
539 else if (count > 1 && buffers[1].len)
540 flags = buffers[1].data;
541 if (!flags)
542 return SET_ERRNO(ERROR_INVALID_FRAME, "Missing encoded frame flags");
543 info.keyframe = (*flags & 1) != 0;
544 }
545 acip_outbound_t *out = transport->outbound;
546 mutex_lock(&out->mutex);
547 info.created = time_get_ns();
549 if (out->stopping || out->failed) {
550 asciichat_error_t code = out->failed ? out->failure_code : ERROR_NETWORK;
551 asciichat_error_context_t cause = out->failure;
552 asciichat_error_context_t detail = out->failure_detail;
553 mutex_unlock(&out->mutex);
554 return cause.code == code ? import_failure(&cause, &detail) : SET_ERRNO(code, "Outbound connection closed");
555 }
556 // Admission first retires stale plaintext and restores codec recovery state;
557 // dependent predictive frames stay rejected until a fresh keyframe arrives.
558 expire_video(out, info.created);
559 expire_datagrams(out, info.created);
560 outbound_stream_t *stream = info.encoded ? stream_state(out, info.type, info.stream) : NULL;
561 if (info.encoded && (!stream || (atomic_load_bool(&stream->needs_keyframe) && !info.keyframe))) {
562 atomic_fetch_add_u64(&out->dropped, 1);
563 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_DROP, 1);
565 ASCII_OTEL_ATTR_STRING("network.queue.admission", "needs_keyframe");
566 mutex_unlock(&out->mutex);
567 return ASCIICHAT_OK;
568 }
569 if (info.video && !info.encoded)
570 discard_stream(out, &info);
571 // Include backend-owned bytes before reserving room for audio and control.
572 size_t backend = backend_bytes(out);
574 size_t limit = ACIP_OUTBOUND_BUDGET - reserved;
575 size_t pending = out->bytes + out->active_bytes + backend + transport->methods->reserved_bytes;
576 ASCII_OTEL_ATTR_INT("network.queue.pending_bytes", (int64_t)pending);
577 ASCII_OTEL_ATTR_INT("network.queue.budget_bytes", (int64_t)limit);
578 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_PENDING, (double)pending);
579 if (out->head)
580 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_AGE, (double)(info.created - out->head->created) / 1e9);
581 if (out->count >= OUTBOUND_MAX_PACKETS - (info.video ? 64 : info.audio ? 32 : 0) || pending > limit || info.cost > limit - pending) {
582 if (info.encoded)
583 discard_stream(out, &info);
584 atomic_fetch_add_u64(&out->congestion, 1);
585 ASCII_OTEL_ATTR_STRING("network.queue.admission", "congested");
586 ascii_otel_metric(ASCII_OTEL_METRIC_OUTBOUND_CONGESTION, 1);
587 mutex_unlock(&out->mutex);
588 return ASCIICHAT_OK;
589 }
590 // Reuse storage only when ownership and synchronous-wait semantics match.
591 outbound_packet_t **cached = &out->recycled;
592 while (*cached && ((*cached)->wait != info.wait || buffer_capacity((*cached)->data) < size))
593 cached = &(*cached)->next;
594 outbound_packet_t *p = *cached;
595 uint8_t *storage = NULL;
596 if (p) {
597 *cached = p->next;
598 --out->recycled_count;
599 storage = p->data;
600 } else {
601 p = SAFE_MALLOC(sizeof(*p), outbound_packet_t *);
602 }
603 if (!p) {
604 mutex_unlock(&out->mutex);
605 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate outbound packet");
606 }
607 *p = info;
608 p->data = storage ? storage : buffer_alloc(info.wait ? buffer_control_domain() : NULL, size);
609 if (!p->data) {
610 SAFE_FREE(p);
611 mutex_unlock(&out->mutex);
612 return SET_ERRNO(ERROR_MEMORY, "Cannot own outbound plaintext");
613 }
614 size_t offset = 0;
615 for (size_t i = 0; i < count; ++i) {
616 if (buffers[i].len)
617 memcpy(p->data + offset, buffers[i].data, buffers[i].len);
618 offset += buffers[i].len;
619 }
620 /* All non-video traffic is inserted ahead of pending media while preserving
621 * protocol barriers and FIFO order within each traffic class. */
622 bool was_empty = outbound_insert_packet(out, p, !info.video);
623 out->bytes += info.cost;
624 ++out->count;
625 atomic_fetch_add_u64(&out->accepted, 1);
626 pending += info.cost;
627 uint64_t peak = atomic_load_u64(&out->peak_bytes);
628 while (pending > peak && !atomic_cas_u64(&out->peak_bytes, &peak, pending))
629 ;
630 if (stream && info.keyframe)
631 atomic_store_bool(&stream->needs_keyframe, false);
632 *admission = ACIP_ADMISSION_ACCEPTED;
633 ASCII_OTEL_ATTR_STRING("network.queue.admission", "accepted");
634 if (was_empty)
635 cond_broadcast(&out->changed);
637 asciichat_error_context_t cause = {0};
638 asciichat_error_context_t detail = {0};
639 if (info.wait) {
640 while (!p->done)
641 cond_wait(&out->changed, &out->mutex);
642 result = p->result;
643 if (result != ASCIICHAT_OK) {
644 cause = out->failure;
645 detail = out->failure_detail;
646 }
647 packet_free(out, p);
648 }
649 mutex_unlock(&out->mutex);
650 if (result == ASCIICHAT_OK)
651 return result;
652 return cause.code == result ? import_failure(&cause, &detail) : SET_ERRNO(result, "Outbound submission failed");
653}
654
655asciichat_error_t acip_outbound_submitv(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, acip_admission_t *admission) {
656 return outbound_submitv(transport, buffers, count, NULL, admission);
657}
658
659asciichat_error_t acip_outbound_submitv_ex(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options, acip_admission_t *admission) {
660 if (!options)
661 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing outbound send options");
662 return outbound_submitv(transport, buffers, count, options, admission);
663}
664
666 if (!transport || !transport->outbound || !stats)
667 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing outbound statistics");
668 acip_outbound_t *out = transport->outbound;
669 mutex_lock(&out->mutex);
670 stats->accepted = atomic_load_u64(&out->accepted);
671 stats->submitted = atomic_load_u64(&out->submitted);
672 stats->dropped = atomic_load_u64(&out->dropped);
673 stats->congestion = atomic_load_u64(&out->congestion);
674 stats->recovery_frames = atomic_load_u64(&out->recovery_frames);
675 stats->peak_bytes = (size_t)atomic_load_u64(&out->peak_bytes);
676 stats->application_bytes = out->bytes + out->active_bytes;
677 stats->backend_bytes = backend_bytes(out);
678 stats->backend_reserved_bytes = transport->methods->reserved_bytes;
679 uint64_t now = time_get_ns();
680 for (outbound_packet_t *p = out->head; p; p = p->next)
681 if (p->video && now - p->created > stats->oldest_frame_age_ns)
682 stats->oldest_frame_age_ns = now - p->created;
683 mutex_unlock(&out->mutex);
684 return ASCIICHAT_OK;
685}
686
688 if (!transport || !transport->outbound)
689 return false;
690 acip_outbound_t *out = transport->outbound;
691 if (transport->methods->consume_keyframe_request && transport->methods->consume_keyframe_request(transport, type, id)) {
692 outbound_packet_t stream = {.type = type, .stream = id, .video = true, .encoded = true};
693 mutex_lock(&out->mutex);
694 discard_stream(out, &stream);
695 mutex_unlock(&out->mutex);
696 return true;
697 }
698 mutex_lock(&out->mutex);
699 size_t count = (size_t)atomic_load_u64(&out->stream_count);
700 for (size_t i = 0; i < count; ++i)
701 if (out->streams[i].type == type && out->streams[i].stream == id) {
702 bool needs_keyframe = atomic_load_bool(&out->streams[i].needs_keyframe);
703 mutex_unlock(&out->mutex);
704 return needs_keyframe;
705 }
706 mutex_unlock(&out->mutex);
707 return true;
708}
asciichat_error_t errno_set_with_message(asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_snapshot_t errno_snapshot(uint64_t id, asciichat_error_context_t *out, size_t capacity)
asciichat_errno_scope_t errno_scope_begin(void)
asciichat_error_t errno_import(const asciichat_error_context_t *cause)
#define SET_ERRNO(code,...)
#define GET_ERRNO()
@ ASCIICHAT_ERRNO_HANDLED
#define ASCIICHAT_ERRNO_MAX_DEPTH
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
void acip_outbound_destroy(acip_transport_t *transport)
asciichat_error_t acip_outbound_submitv_ex(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options, acip_admission_t *admission)
asciichat_error_t acip_outbound_snapshot(acip_transport_t *transport, acip_outbound_stats_t *stats)
asciichat_error_t acip_outbound_create(acip_transport_t *transport)
struct outbound_packet outbound_packet_t
asciichat_error_t acip_outbound_submitv(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, acip_admission_t *admission)
#define OUTBOUND_MAX_STREAMS
#define OUTBOUND_MAX_PACKETS
bool acip_outbound_needs_keyframe(acip_transport_t *transport, uint16_t type, uint32_t id)
#define WIRE_OVERHEAD
void acip_outbound_stop(acip_transport_t *transport)
#define ACIP_OUTBOUND_VIDEO_AGE_NS
#define ACIP_OUTBOUND_BUDGET
struct acip_outbound acip_outbound_t
#define ACIP_OUTBOUND_AUDIO_RESERVE
acip_admission_t
@ ACIP_ADMISSION_ACCEPTED
@ ACIP_ADMISSION_CONGESTED
@ ACIP_ADMISSION_NEEDS_KEYFRAME
#define ACIP_OUTBOUND_CONTROL_RESERVE
size_t buffer_capacity(const void *data)
Definition buffer.c:300
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
buffer_domain_t * buffer_control_domain(void)
Definition buffer.c:465
#define buffer_release(data)
Definition buffer.h:108
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:77
@ ERROR_BUFFER_FULL
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
@ ERROR_INVALID_FRAME
@ ERROR_INVALID_PARAM
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:80
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:74
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Transport abstraction layer for ACIP protocol.
asciichat_error_t acip_security_flush(acip_transport_t *transport)
gotel_context_t ascii_otel_context(void)
Definition otel.c:870
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_SCOPE_PARENT(id, parent)
Definition otel.h:98
#define ASCII_OTEL_PACKET(type, size, action, transport)
Definition otel.h:96
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
static bool size_t index
Definition queries.h:10
static bool size_t gotel_query_t * out
Definition queries.h:10
asciichat_error_t acip_transport_get_capabilities(acip_transport_t *transport, acip_transport_capabilities_t *out)
Definition send.c:101
🔤 String Manipulation and Shell Escaping Utilities
This is the handoff point for acip outbound stats. Callers fill application_bytes,...
atomic_t recovery_frames
atomic_t submitted
size_t recycled_count
atomic_t stream_count
outbound_packet_t * recycled
platform_thread_t worker
outbound_packet_t * head
size_t active_bytes
bool stopped_by_caller
acip_transport_t * transport
atomic_t dropped
atomic_t accepted
outbound_stream_t streams[64]
asciichat_error_context_t failure
atomic_t peak_bytes
asciichat_error_t failure_code
asciichat_error_context_t failure_detail
atomic_t congestion
uint64_t deadline_ns
Definition traffic.h:23
acip_delivery_t delivery
Definition traffic.h:22
acip_traffic_class_t traffic_class
Definition traffic.h:21
The useful part of acip transport capabilities is in independent_streams, datagrams,...
asciichat_error_t(* validate_send_options)(acip_transport_t *transport, const acip_send_options_t *options)
void(* interrupt)(acip_transport_t *transport)
asciichat_error_t(* send)(acip_transport_t *transport, const void *data, size_t len)
Send data through this transport.
asciichat_error_t(* close)(acip_transport_t *transport)
Close this transport.
bool(* consume_keyframe_request)(acip_transport_t *transport, uint16_t type, uint32_t stream_id)
size_t reserved_bytes
Bound for backend-owned pending data not exposed by queued_bytes.
asciichat_error_t(* sendv_ex)(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options)
struct acip_outbound * outbound
Per-connection plaintext admission and scheduling.
const acip_transport_methods_t * methods
Method table (virtual functions).
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
gotel_context_t telemetry_context
struct outbound_packet * next
asciichat_error_t result
acip_send_options_t options
uint64_t last_used_ns
atomic_t needs_keyframe
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
⏱️ High-precision timing utilities using sokol_time.h and uthash
acip_traffic_class_t acip_packet_traffic_class(uint16_t type)
Definition traffic.c:4
@ ACIP_TRAFFIC_CONTROL
Definition traffic.h:10
@ ACIP_TRAFFIC_VISUAL
Definition traffic.h:12
@ ACIP_TRAFFIC_AUDIO
Definition traffic.h:11
@ ACIP_DELIVERY_RELIABLE
Definition traffic.h:16
@ ACIP_DELIVERY_DATAGRAM
Definition traffic.h:17