ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
host.c
Go to the documentation of this file.
2
3/* Storage capacities in elements; text buffers include the terminating NUL. */
4#define SESSION_HOST_KEY_PATH_BUFFER_SIZE 512
5#define HOST_AUDIO_BUFFER_FRAMES 10
11#include <ascii-chat/common.h>
13#include <ascii-chat/otel.h>
26
27#include "session/host.h"
28#ifndef __EMSCRIPTEN__
29#include "quic_listeners.h"
30#endif
33#include "session/host_timing.h"
34#include "session/display.h"
36#include <ascii-chat/common.h>
37#include <options/options.h>
40#include <libplatform/mutex.h>
41#include <libplatform/thread.h>
42#include <ascii-chat/log/log.h>
52#include "session/audio.h"
58
59#include <string.h>
60#include <time.h>
61#include <stdio.h>
62
63/* ============================================================================
64 * Session Host Constants
65 * ============================================================================ */
66
68#define SESSION_HOST_DEFAULT_MAX_CLIENTS MAX_SESSION_PARTICIPANTS
69
70/* ============================================================================
71 * Session Host Internal Types
72 * ============================================================================ */
73
118
119static void host_client_release_transport(session_host_client_t *client) {
120 if (client->opus_decoder) {
122 client->opus_decoder = NULL;
123 }
124 if (client->opus_encoder) {
126 client->opus_encoder = NULL;
127 }
128 if (client->rain) {
129 digital_rain_destroy(client->rain);
130 client->rain = NULL;
131 }
134 client->transport = NULL;
136}
137
138/* ============================================================================
139 * Session Host Context Structure
140 * ============================================================================ */
141
154
227
228static void host_forget_render_history(session_host_t *host, uint32_t client_id);
229
230/* ============================================================================
231 * Session Host Lifecycle Functions
232 * ============================================================================ */
233
235 if (!config) {
236 SET_ERRNO(ERROR_INVALID_PARAM, "NULL config");
237 return NULL;
238 }
239
240 // Allocate host
242
243 // Copy configuration
244 host->port = config->port > 0 ? config->port : OPT_PORT_INT_DEFAULT;
245 host->max_clients = config->max_clients > 0 ? config->max_clients : SESSION_HOST_DEFAULT_MAX_CLIENTS;
246 host->encryption_enabled = config->encryption_enabled;
247 host->configured_quic_listeners = config->configured_quic_listeners;
248
249 if (config->ipv4_address) {
250 SAFE_STRNCPY(host->ipv4_address, config->ipv4_address, sizeof(host->ipv4_address));
251 }
252
253 if (config->ipv6_address) {
254 SAFE_STRNCPY(host->ipv6_address, config->ipv6_address, sizeof(host->ipv6_address));
255 }
256
257 if (config->key_path) {
258 SAFE_STRNCPY(host->key_path, config->key_path, sizeof(host->key_path));
259 }
260
261 if (config->password) {
262 SAFE_STRNCPY(host->password, config->password, sizeof(host->password));
263 }
264
265 host->callbacks = config->callbacks;
266 host->user_data = config->user_data;
267
268 host->running = false;
269
270 // Allocate client array
271 host->clients = SAFE_CALLOC((size_t)host->max_clients, sizeof(session_host_client_t), session_host_client_t *);
272
273 host->client_count = 0;
274 host->next_client_id = 1;
275
276 // Initialize mutex
277 if (mutex_init(&host->clients_mutex, "host_clients") != 0) {
278 SET_ERRNO(ERROR_THREAD, "Failed to initialize clients mutex");
279 SAFE_FREE(host->clients);
280 acip_frame_workspace_destroy(&host->frame_workspace);
281 SAFE_FREE(host);
282 return NULL;
283 }
284
285 host->initialized = true;
286 return host;
287}
288
290 if (!host)
291 return ASCIICHAT_OK;
293 if (result != ASCIICHAT_OK)
294 return result;
295
296 // Clean up audio resources
297 if (host->audio_ctx) {
298#ifndef __EMSCRIPTEN__
299 session_audio_destroy(host->audio_ctx);
300#endif
301 host->audio_ctx = NULL;
302 }
303
304 while (host->render_histories) {
305 host_render_history_t *history = host->render_histories;
306 host->render_histories = history->next;
307 ascii_stabilizer_reset(&history->stabilizer);
308 SAFE_FREE(history);
309 }
310
311 // Free client array and per-client resources
312 if (host->clients) {
313 for (int i = 0; i < host->max_clients; i++) {
314 host_client_release_transport(&host->clients[i]);
315 if (host->clients[i].incoming_video) {
316 image_destroy(host->clients[i].incoming_video);
317 host->clients[i].incoming_video = NULL;
318 }
319 if (host->clients[i].incoming_audio) {
320 ringbuffer_destroy(host->clients[i].incoming_audio);
321 host->clients[i].incoming_audio = NULL;
322 }
323 }
324 SAFE_FREE(host->clients);
325 }
326
327 // Destroy mutex
328 mutex_destroy(&host->clients_mutex);
329
330 // Clear sensitive data
331 memset(host->password, 0, sizeof(host->password));
332
333 host->initialized = false;
334 acip_frame_workspace_destroy(&host->frame_workspace);
335 SAFE_FREE(host);
336 return ASCIICHAT_OK;
337}
338
339/* ============================================================================
340 * Session Host Server Control Functions
341 * ============================================================================ */
342
343asciichat_error_t session_host_receive_packet(session_host_t *host, uint32_t client_id, packet_type_t ptype, const void *data, size_t len) {
344 if (!host || !host->initialized || (!data && len))
345 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid host packet");
346 acip_transport_t *client_transport = session_host_get_client_transport(host, client_id);
347 switch (ptype) {
349 // Client sent a video frame - parse and store in incoming buffer
350 if (data && len >= sizeof(image_frame_packet_t)) {
351 const image_frame_packet_t *frame_hdr = (const image_frame_packet_t *)data;
352 const uint8_t *pixel_data = (const uint8_t *)data + sizeof(image_frame_packet_t);
353 size_t pixel_data_size = len - sizeof(image_frame_packet_t);
354 uint32_t width = NET_TO_HOST_U32(frame_hdr->width);
356 uint32_t pixel_format = NET_TO_HOST_U32(frame_hdr->pixel_format);
357 size_t bytes_per_pixel = (pixel_format == PIXEL_FORMAT_RGBA || pixel_format == PIXEL_FORMAT_BGRA) ? 4 : 3;
358 size_t expected_size = 0;
359 size_t pixel_count = 0;
360
361 if (pixel_format < PIXEL_FORMAT_RGB || pixel_format > PIXEL_FORMAT_BGRA || width == 0 || height == 0 || width > INT_MAX || height > INT_MAX ||
362 checked_size_mul((size_t)width, (size_t)height, &pixel_count) != ASCIICHAT_OK || checked_size_mul(pixel_count, bytes_per_pixel, &expected_size) != ASCIICHAT_OK ||
363 expected_size != pixel_data_size) {
364 log_warn("Discarding malformed video frame from client %u (%ux%u, format %u, payload %zu)", client_id, width, height, pixel_format, pixel_data_size);
365 } else {
366 // Frame dimensions and pixel format are network-order fields. Resize
367 // this participant's image when its capture dimensions change.
368 mutex_lock(&host->clients_mutex);
369 for (int j = 0; j < host->max_clients; j++) {
370 if (host->clients[j].active && host->clients[j].client_id == client_id && host->clients[j].incoming_video) {
371 image_t *img = host->clients[j].incoming_video;
372 if (img->w != (int)width || img->h != (int)height) {
373 image_t *resized = image_new(width, height);
374 if (!resized) {
375 log_warn("Could not allocate %ux%u video frame for client %u", width, height, client_id);
376 break;
377 }
378 image_destroy(img);
379 host->clients[j].incoming_video = img = resized;
380 }
381
382 uint8_t *dst = (uint8_t *)img->pixels;
383 if (pixel_format == PIXEL_FORMAT_RGB) {
384 memcpy(dst, pixel_data, pixel_count * 3);
385 } else if (pixel_format == PIXEL_FORMAT_BGR) {
386 for (size_t p = 0; p < pixel_count; p++) {
387 dst[p * 3] = pixel_data[p * 3 + 2];
388 dst[p * 3 + 1] = pixel_data[p * 3 + 1];
389 dst[p * 3 + 2] = pixel_data[p * 3];
390 }
391 } else {
392 const bool bgra = pixel_format == PIXEL_FORMAT_BGRA;
393 for (size_t p = 0; p < pixel_count; p++) {
394 const uint8_t *src = pixel_data + p * 4;
395 dst[p * 3] = src[bgra ? 2 : 0];
396 dst[p * 3 + 1] = src[1];
397 dst[p * 3 + 2] = src[bgra ? 0 : 2];
398 }
399 }
400 log_debug_every(500 * US_PER_MS_INT, "Frame received from client %u (%ux%u, format %u)", client_id, width, height, pixel_format);
401 break;
402 }
403 }
404 mutex_unlock(&host->clients_mutex);
405 }
406 }
407 break;
408
410 // Client sent Opus-encoded audio batch
411 if (data && len > 16) { // Must have at least header
412 const uint8_t *batch_data = (const uint8_t *)data;
413 // Parse header: sample_rate (4), frame_duration (4), frame_count (4), reserved (4)
414 (void)batch_data[0]; // Avoid unused variable warning if we don't use sample_rate/frame_duration
415 uint32_t batch_frame_count_net = 0;
416 memcpy(&batch_frame_count_net, batch_data + 8, sizeof(batch_frame_count_net));
417 uint32_t batch_frame_count = NET_TO_HOST_U32(batch_frame_count_net);
418
419 size_t frame_sizes_len = (size_t)batch_frame_count * sizeof(uint16_t);
420 if (batch_frame_count > 0 && batch_frame_count <= 1000 && 16 + frame_sizes_len <= len) {
421 const uint8_t *frame_sizes = batch_data + 16;
422 const uint8_t *opus_frames = batch_data + 16 + (batch_frame_count * sizeof(uint16_t));
423 const uint8_t *batch_end = batch_data + len;
424
425 // Find client and decode audio
426 mutex_lock(&host->clients_mutex);
427 for (int j = 0; j < host->max_clients; j++) {
428 if (host->clients[j].client_id == client_id && host->clients[j].active && host->clients[j].incoming_audio) {
429 if (!host->clients[j].opus_decoder)
431 if (!host->clients[j].opus_decoder) {
432 mutex_unlock(&host->clients_mutex);
433 return SET_ERRNO(ERROR_AUDIO, "Failed to initialize participant decoder");
434 }
435 // Each participant owns an independent predictive Opus stream.
436 const uint8_t *current_frame = opus_frames;
437 for (uint32_t k = 0; k < batch_frame_count; k++) {
438 uint16_t frame_size_net = 0;
439 memcpy(&frame_size_net, frame_sizes + k * sizeof(frame_size_net), sizeof(frame_size_net));
440 uint16_t frame_size = NET_TO_HOST_U16(frame_size_net);
441 if ((size_t)(batch_end - current_frame) < frame_size) {
442 break;
443 }
444 if (frame_size > 0) {
445 // Allocate buffer for decoded samples
446 float decoded_samples[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)]; // Max 20ms @ 48kHz
447 int decoded_count = opus_codec_decode(host->clients[j].opus_decoder, current_frame, (int)frame_size, decoded_samples, (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS));
448 if (decoded_count > 0) {
449 host->clients[j].audio_active = true;
450 // Write samples to ringbuffer one at a time
451 for (int s = 0; s < decoded_count; s++) {
452 ringbuffer_write(host->clients[j].incoming_audio, &decoded_samples[s]);
453 }
454 }
455 }
456 current_frame += frame_size;
457 }
458 log_debug_every(NS_PER_MS_INT, "Audio batch received from client %u (%u frames)", client_id, batch_frame_count);
459 break;
460 }
461 }
462 mutex_unlock(&host->clients_mutex);
463 }
464 }
465 break;
466
468 log_info("Client %u started streaming", client_id);
469 mutex_lock(&host->clients_mutex);
470 for (int j = 0; j < host->max_clients; j++) {
471 if (host->clients[j].client_id == client_id) {
472 host->clients[j].video_active = true;
473 break;
474 }
475 }
476 mutex_unlock(&host->clients_mutex);
477 break;
478
482 size_t reply_length = 0;
484 session_host_client_t *target = NULL;
485 mutex_lock(&host->clients_mutex);
486 for (int j = 0; j < host->max_clients; ++j) {
487 if (host->clients[j].active && host->clients[j].client_id == client_id) {
488 target = &host->clients[j];
489 break;
490 }
491 }
492 if (!target)
493 result = SET_ERRNO(ERROR_INVALID_STATE, "Unknown settings participant");
494 else if (ptype == PACKET_TYPE_CLIENT_CAPABILITIES) {
495 if (!data || len != sizeof(terminal_capabilities_packet_t))
496 result = SET_ERRNO(ERROR_INVALID_PARAM, "Invalid capabilities");
497 else {
499 memcpy(&packet, data, sizeof(packet));
500 if (target->rendering.width) {
501 // Codec advertisements cannot change an established viewer's settings.
502 mutex_unlock(&host->clients_mutex);
503 return ASCIICHAT_OK;
504 }
505 result = acip_render_settings_capabilities(&target->rendering, &packet);
506 if (result == ASCIICHAT_OK) {
508 size_t query_length;
509 acip_settings_header_t header = {.schema = 1, .expected_revision = UINT32_MAX};
510 result = acip_settings_encode(&header, "", query, sizeof(query), &query_length);
511 if (result == ASCIICHAT_OK)
512 result = acip_settings_request(&target->rendering, query, query_length, reply, sizeof(reply), &reply_length);
513 }
514 }
515 } else if (!target->rendering.revision)
516 result = SET_ERRNO(ERROR_INVALID_STATE, "Settings received before capabilities");
517 else
518 result = acip_settings_request(&target->rendering, data, len, reply, sizeof(reply), &reply_length);
519 if (target && result == ASCIICHAT_OK) {
520 target->render_width = target->rendering.width;
521 target->render_height = target->rendering.height;
522 if (reply_length)
523 result = packet_send_via_transport(target->transport, PACKET_TYPE_ACIP_SETTINGS_ACK, reply, reply_length, 0);
524 }
525 mutex_unlock(&host->clients_mutex);
526 return result;
527 }
528
530 log_info("Client %u stopped streaming", client_id);
531 mutex_lock(&host->clients_mutex);
532 for (int j = 0; j < host->max_clients; j++) {
533 if (host->clients[j].client_id == client_id) {
534 host_forget_render_history(host, client_id);
535 host->clients[j].video_active = false;
536 host->clients[j].audio_active = false;
537 break;
538 }
539 }
540 mutex_unlock(&host->clients_mutex);
541 break;
542
543 case PACKET_TYPE_PING:
544 // Respond with PONG
545 log_debug_every(NS_PER_MS_INT, "PING from client %u", client_id);
546 acip_send_pong(client_transport);
547 break;
548
550 log_info("Client %u requested disconnect", client_id);
551 // Mark for removal (will be handled separately to avoid deadlock)
552 break;
553
554 default:
555 log_warn("Unknown packet type %u from client %u", ptype, client_id);
556 break;
557 }
558
559 return ASCIICHAT_OK;
560}
561
562static ascii_stabilizer_t *host_render_history(session_host_t *host, uint32_t viewer_id, uint32_t source_id) {
563 for (host_render_history_t *item = host->render_histories; item; item = item->next)
564 if (item->viewer_id == viewer_id && item->source_id == source_id)
565 return &item->stabilizer;
566 host_render_history_t *item = SAFE_CALLOC(1, sizeof(*item), host_render_history_t *);
567 if (!item)
568 return NULL;
569 item->viewer_id = viewer_id;
570 item->source_id = source_id;
571 item->next = host->render_histories;
572 host->render_histories = item;
573 return &item->stabilizer;
574}
575
576static void host_forget_render_history(session_host_t *host, uint32_t client_id) {
577 host_render_history_t **link = &host->render_histories;
578 while (*link) {
579 host_render_history_t *item = *link;
580 if (item->viewer_id == client_id || item->source_id == client_id) {
581 *link = item->next;
583 SAFE_FREE(item);
584 } else {
585 link = &item->next;
586 }
587 }
588}
589
590static void host_forget_viewer_history(session_host_t *host, uint32_t viewer_id) {
591 host_render_history_t **link = &host->render_histories;
592 while (*link) {
593 host_render_history_t *item = *link;
594 if (item->viewer_id == viewer_id) {
595 *link = item->next;
597 SAFE_FREE(item);
598 } else {
599 link = &item->next;
600 }
601 }
602}
603
604static char *host_create_video_grid(session_host_t *host, int count, int width, int height, const terminal_capabilities_t *caps, const char *palette, uint32_t viewer_id, size_t *size) {
605 int columns, rows;
606 if (ascii_grid_layout(count, width, height, &columns, &rows) != ASCIICHAT_OK)
607 return NULL;
608 int cell_width = (width - columns + 1) / columns;
609 int cell_height = (height - rows + 1) / rows;
610 // Match ascii_create_grid's first-source fallback for very small viewports.
611 bool fallback = count > 1 && (cell_width < 10 || cell_height < 3);
612 if (fallback) {
613 cell_width = width;
614 cell_height = height;
615 }
616 ascii_frame_source_t *sources = SAFE_CALLOC((size_t)count, sizeof(*sources), ascii_frame_source_t *);
617 int index = 0;
618 for (int i = 0; i < host->max_clients; ++i) {
619 if (!host->clients[i].active || !host->clients[i].video_active || !host->clients[i].incoming_video)
620 continue;
621 uint64_t start = time_get_ns();
622 ascii_stabilizer_t *history = caps->stabilize ? host_render_history(host, viewer_id, host->clients[i].client_id) : NULL;
623 sources[index].frame_data = ascii_convert_with_buffers_stabilized(host->clients[i].incoming_video, cell_width, cell_height, caps, false, false, palette, false, NULL, NULL, history);
626 sources[index].frame_size = sources[index].frame_data ? strlen(sources[index].frame_data) : 0;
627 ++index;
628 if (fallback)
629 break;
630 }
631 char *grid = ascii_create_grid(sources, count, width, height, size);
632 for (int i = 0; i < count; ++i)
633 SAFE_FREE(sources[i].frame_data);
634 SAFE_FREE(sources);
635 return grid;
636}
637
638static void host_render_video(session_host_t *host, bool waiting_for_peer) {
639 mutex_lock(&host->clients_mutex);
640 int count = 0;
641 for (int i = 0; i < host->max_clients; ++i)
642 if (host->clients[i].active && host->clients[i].video_active && host->clients[i].incoming_video)
643 ++count;
644
645 if (count > 0) {
646 ASCII_OTEL_SCOPE(SERVER_VIDEO);
647 typedef struct {
648 int width, height;
649 uint32_t viewer_id;
650 terminal_capabilities_t caps;
651 const char *palette;
652 char *frame;
653 size_t size;
654 } host_grid_t;
655 // Cache each viewport and rendering configuration for this frame.
656 host_grid_t *grids = SAFE_CALLOC((size_t)host->max_clients + 1, sizeof(*grids), host_grid_t *);
657 int grid_count = 0;
658 for (int i = 0; i <= host->max_clients; ++i) {
659 bool local_display = i == host->max_clients;
660 int width = 80, height = 24;
661 terminal_capabilities_t caps = {0};
662 const char *palette = NULL;
663 session_host_client_t *recipient = local_display ? NULL : &host->clients[i];
664 if (local_display) {
665 if (waiting_for_peer)
666 continue;
667 if (host->render_target.client_id) {
668 for (int j = 0; j < host->max_clients; ++j) {
669 if (host->clients[j].active && host->clients[j].client_id == host->render_target.client_id) {
670 recipient = &host->clients[j];
671 break;
672 }
673 }
674 if (!recipient)
675 continue;
676 } else {
677 session_host_render_config_t config = {0};
678 if (!host->render_target.get_config || host->render_target.get_config(host->render_target.context, &config) != ASCIICHAT_OK || !config.palette || config.width <= 0 || config.height <= 0)
679 continue;
680 caps = config.caps;
681 palette = config.palette;
682 width = config.width;
683 height = config.height;
684 }
685 } else {
686 if (recipient->client_id == host->render_target.client_id)
687 continue;
688 }
689 if (recipient) {
690 if (!recipient->active || !recipient->transport)
691 continue;
692 if (!recipient->rendering.revision)
693 continue;
694 caps = recipient->rendering.caps;
695 palette = recipient->rendering.palette;
696 if (recipient->render_width > 0 && recipient->render_height > 0) {
697 width = recipient->render_width;
698 height = recipient->render_height;
699 }
700 }
701 if (!palette)
702 continue;
703 if (!caps.utf8_support) {
704 if (caps.render_mode == RENDER_MODE_HALF_BLOCK)
705 caps.render_mode = RENDER_MODE_FOREGROUND;
706 if (palette_requires_utf8_encoding(palette, strlen(palette)))
708 }
709 uint64_t now = time_get_ns();
710 if (recipient && caps.desired_fps > 0) {
711 uint64_t interval = NS_PER_SEC_INT / caps.desired_fps;
712 if (recipient->next_video_deadline && now < recipient->next_video_deadline)
713 continue;
714 if (!recipient->next_video_deadline || now - recipient->next_video_deadline > interval * 2)
715 recipient->next_video_deadline = now;
716 recipient->next_video_deadline += interval;
717 }
718 uint32_t viewer_id = recipient ? recipient->client_id : 0;
719 if (!caps.stabilize)
720 host_forget_viewer_history(host, viewer_id);
721 int cached = 0;
722 while (cached < grid_count && (grids[cached].caps.stabilize != caps.stabilize || (caps.stabilize && grids[cached].viewer_id != viewer_id) || grids[cached].width != width ||
723 grids[cached].height != height || grids[cached].caps.render_mode != caps.render_mode || grids[cached].caps.text_renderer != caps.text_renderer ||
724 grids[cached].caps.palette_explicit != caps.palette_explicit || grids[cached].caps.color_level != caps.color_level ||
725 grids[cached].caps.utf8_support != caps.utf8_support || grids[cached].caps.color_filter != caps.color_filter || strcmp(grids[cached].palette, palette) != 0))
726 ++cached;
727 if (cached == grid_count) {
728 grids[cached].viewer_id = viewer_id;
729 grids[cached].width = width;
730 grids[cached].height = height;
731 grids[cached].caps = caps;
732 grids[cached].palette = palette;
733 grids[cached].frame = host_create_video_grid(host, count, width, height, &caps, palette, viewer_id, &grids[cached].size);
734 ++grid_count;
735 }
736 host_grid_t *grid = &grids[cached];
737 if (!grid->frame)
738 continue;
739 char *rain_frame = NULL;
740 const char *output = grid->frame;
741 size_t output_size = grid->size;
742 if (recipient) {
743 if (caps.capabilities & TERM_CAP_MATRIX_RAIN) {
744 if (recipient->rain && (recipient->rain->num_columns != width || recipient->rain->num_rows != height)) {
745 digital_rain_destroy(recipient->rain);
746 recipient->rain = NULL;
747 }
748 if (!recipient->rain) {
749 recipient->rain = digital_rain_init(width, height);
750 recipient->rain_time = (double)now / NS_PER_SEC_INT;
751 }
752 if (recipient->rain) {
753 double seconds = (double)now / NS_PER_SEC_INT;
754 digital_rain_set_color_from_filter(recipient->rain, caps.color_filter);
755 rain_frame = digital_rain_apply(recipient->rain, grid->frame, (float)(seconds - recipient->rain_time));
756 recipient->rain_time = seconds;
757 if (rain_frame) {
758 output = rain_frame;
759 output_size = strlen(rain_frame);
760 }
761 }
762 } else if (recipient->rain) {
763 digital_rain_destroy(recipient->rain);
764 recipient->rain = NULL;
765 }
766 }
767 if (!recipient) {
768 host->render_target.render_frame(host->render_target.context, output, output_size, width, height);
769 } else {
770 acip_render_settings_t rendering = recipient->rendering;
771 rendering.caps = caps;
772 SAFE_STRNCPY(rendering.palette, palette, sizeof(rendering.palette));
773 uint32_t effects = (caps.capabilities & TERM_CAP_MATRIX_RAIN) ? FRAME_RENDER_CONTRACT_RAIN : 0;
774 if (count > 1)
776 acip_send_ascii_frame_contract(recipient->transport, &host->frame_workspace, output, output_size, width, height, &rendering, effects, "session-host");
777 }
778 SAFE_FREE(rain_frame);
779 }
780 for (int i = 0; i < grid_count; ++i)
781 SAFE_FREE(grids[i].frame);
782 SAFE_FREE(grids);
783 }
784 mutex_unlock(&host->clients_mutex);
785}
786
788 if (!host || !host->initialized)
789 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session host");
790 host_render_video(host, false);
791 return ASCIICHAT_OK;
792}
793
795 if (!host || !host->initialized)
796 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
797 uint64_t mix_start = time_get_ns();
798 double total[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)] = {0};
800 mutex_lock(&host->clients_mutex);
801 // Drain each source once. Keep unclipped samples so mix-minus can subtract
802 // the recipient before clipping without leaking its voice into the output.
803 for (int i = 0; i < host->max_clients; i++) {
804 session_host_client_t *client = &host->clients[i];
805 memset(client->audio_frame, 0, sizeof(client->audio_frame));
806 if (!client->active || !client->audio_active || !client->incoming_audio)
807 continue;
808 for (int j = 0; j < (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS); j++) {
809 if (ringbuffer_read(client->incoming_audio, &client->audio_frame[j]))
810 total[j] += client->audio_frame[j];
811 }
812 }
813 for (int i = 0; i < host->max_clients; i++) {
814 session_host_client_t *client = &host->clients[i];
815 if (!client->active || !client->transport)
816 continue;
817 ASCII_OTEL_SCOPE(SERVER_AUDIO);
818 if (!client->opus_encoder)
820 if (!client->opus_encoder) {
821 result = SET_ERRNO(ERROR_AUDIO, "Failed to initialize participant encoder");
822 continue;
823 }
824 float mixed[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)];
825 for (int j = 0; j < (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS); j++) {
826 float sample = (float)(total[j] - client->audio_frame[j]);
827 mixed[j] = sample > 1.0f ? 1.0f : sample < -1.0f ? -1.0f : sample;
828 }
830 size_t opus_len = opus_codec_encode(client->opus_encoder, mixed, OPUS_FRAME_SAMPLES * AUDIO_CHANNELS, opus_buffer, sizeof(opus_buffer));
831 if (opus_len > 0) {
832 uint16_t frame_sizes[1] = {(uint16_t)opus_len};
833 asciichat_error_t sent = acip_send_audio_opus_batch(client->transport, opus_buffer, opus_len, frame_sizes, 1, AUDIO_SAMPLE_RATE, CLIENT_AUDIO_PIPELINE_FRAME_MS);
834 if (sent != ASCIICHAT_OK)
835 log_warn("Failed to send mixed audio to client %u", client->client_id);
836 }
837 }
838 mutex_unlock(&host->clients_mutex);
840#ifndef __EMSCRIPTEN__
841 float recorded[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)];
842 for (int j = 0; j < (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS); j++)
843 recorded[j] = total[j] > 1.0 ? 1.0f : total[j] < -1.0 ? -1.0f : (float)total[j];
845#endif
846 return result;
847}
848
849static void *host_render_thread(void *arg) {
850 session_host_t *host = (session_host_t *)arg;
851 if (!host) {
852 SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
853 return NULL;
854 }
855
856 log_info("Host render thread started");
857
858 bool waiting_for_peer = GET_OPTION(detected_mode) == MODE_DISCOVERY && !GET_OPTION(snapshot_mode) && GET_OPTION(splash_screen) && terminal_is_interactive() && terminal_is_stdout_tty();
859 host->snapshot_first_frame_ns = 0;
860 uint64_t last_video_render_ns = 0;
861 uint64_t audio_deadline_ns = 0;
862
863 while (host->render_thread_running && host->running) {
864 uint64_t now_ns = time_get_ns();
865 if (waiting_for_peer) {
866 bool peer_ready = false;
867 mutex_lock(&host->clients_mutex);
868 for (int i = 0; i < host->max_clients; ++i) {
869 session_host_client_t *client = &host->clients[i];
870 // Capabilities establish protocol readiness without requiring camera frames.
871 if (client->active && client->participant_type == PARTICIPANT_TYPE_NETWORK && client->render_width > 0 && client->render_height > 0) {
872 peer_ready = true;
873 break;
874 }
875 }
876 mutex_unlock(&host->clients_mutex);
877 if (peer_ready) {
880 waiting_for_peer = false;
881 }
882 }
883
884 // VIDEO RENDERING (60 FPS = 16.7ms)
885 if (time_elapsed_ns(last_video_render_ns, now_ns) >= NS_PER_MS_INT * 16) {
886 host_render_video(host, waiting_for_peer);
887 last_video_render_ns = now_ns;
888 }
889
890 // Complete snapshots only after a local frame, outside the client lock.
891 if (host->snapshot_first_frame_ns > 0 && (double)(time_get_ns() - host->snapshot_first_frame_ns) / NS_PER_SEC_INT >= GET_OPTION(snapshot_delay)) {
893 break;
894 }
895
896 // Audio consumes one 20 ms Opus frame per tick.
897 while (session_host_audio_due(&audio_deadline_ns, now_ns)) {
898 // Mix audio from all participants
899 // 1. Read samples from each participant's incoming_audio ringbuffer
900 // 2. Mix into output buffer (simple addition with clipping)
901 // 3. Encode with Opus
902 // 4. Broadcast mixed audio via av_send_audio_opus_batch()
903
905 log_warn("Host audio rendering failed");
906
907 log_debug_every(NS_PER_MS_INT, "Audio render cycle");
908 }
909
910 // Small sleep to prevent busy-loop
911 APP_CALLBACK_VOID(platform_pump_events);
912 platform_sleep_ms(1);
913 }
914
915 log_info("Host render thread stopped");
916 return NULL;
917}
918
919#ifndef __EMSCRIPTEN__
930static asciichat_error_t host_connection_open(network_connection_t *connection, void *arg) {
931 session_host_t *host = arg;
932 host_connection_t *client = SAFE_CALLOC(1, sizeof(*client), host_connection_t *);
933 if (!client)
934 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate host connection");
935 network_connection_set_context(connection, client);
937 if (!client->client_id)
938 return SET_ERRNO(ERROR_SESSION_FULL, "Host has no participant capacity");
939 mutex_lock(&host->clients_mutex);
940 for (int i = 0; i < host->max_clients; ++i)
941 if (host->clients[i].client_id == client->client_id)
942 host->clients[i].connection = connection;
943 mutex_unlock(&host->clients_mutex);
944 if (network_connection_state(connection) == NETWORK_READY)
946 asciichat_error_t result = network_connection_prepare_security(connection, true, host->password);
947 if (result != ASCIICHAT_OK)
948 return result;
950 client->identity = ctx->server_private_key;
952 .handshake = ctx,
953 .identity_keys = &client->identity,
954 .identity_key_count = client->identity.type == KEY_TYPE_ED25519 ? 1 : 0,
955 .whitelist = ctx->client_whitelist,
956 .whitelist_count = ctx->num_whitelisted_clients,
957 .initialized = true,
958 .password = host->password,
959 .secure = network_connection_secure(connection),
960 .require_auth = ctx->has_password || ctx->require_client_auth,
961 .require_identity = ctx->require_client_auth,
962 .require_encryption = GET_OPTION(encrypt_enabled),
963 .forbid_encryption = GET_OPTION(no_encrypt)};
964 return ASCIICHAT_OK;
965}
966static asciichat_error_t host_connection_packet(network_connection_t *connection, packet_type_t type, const void *payload, size_t length, void *arg) {
967 host_connection_t *client = network_connection_context(connection);
969 asciichat_error_t result = network_negotiation_receive(&client->negotiation, network_connection_transport(connection), type, payload, length);
970 if (result == ASCIICHAT_OK && client->negotiation.ready) {
971 network_connection_ready(connection);
972 // Admission attaches the transport before security negotiation. Publish
973 // protocol readiness only now, so browser peers can begin STREAM_START.
975 }
976 return result;
977 }
978 return session_host_receive_packet(arg, client->client_id, type, payload, length);
979}
980static asciichat_error_t host_connection_closing(network_connection_t *connection, void *arg) {
981 session_host_t *host = arg;
982 host_connection_t *client = network_connection_context(connection);
983 if (!client || !client->client_id)
984 return ASCIICHAT_OK;
985 mutex_lock(&host->clients_mutex);
986 for (int i = 0; i < host->max_clients; ++i)
987 if (host->clients[i].client_id == client->client_id)
988 host->clients[i].connection = NULL;
989 mutex_unlock(&host->clients_mutex);
990 return session_host_remove_client(host, client->client_id);
991}
992static void host_connection_closed(network_connection_t *connection, void *arg) {
993 (void)arg;
994 host_connection_t *client = network_connection_context(connection);
995 SAFE_FREE(client);
996}
997static void *host_network_run(void *arg) {
998 session_host_t *host = arg;
999 network_server_run(host->network_server);
1000 return NULL;
1001}
1002#endif
1004 if (!host || !host->initialized)
1005 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session host");
1006 if (host->running)
1007 return ASCIICHAT_OK;
1008 if (host->port > UINT16_MAX)
1009 return SET_ERRNO(ERROR_INVALID_PARAM, "Host port is outside the transport endpoint range");
1010#ifdef __EMSCRIPTEN__
1011 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Browser hosts accept browser-managed connections");
1012#else
1014 if (host->configured_quic_listeners)
1015 result = session_quic_listeners_open(host->port, &host->quic_endpoint, &host->webtransport_endpoint);
1016 if (result != ASCIICHAT_OK)
1017 return result;
1018 network_server_config_t config = {.quic_endpoint = host->quic_endpoint,
1019 .webtransport_endpoint = host->webtransport_endpoint,
1020 .port = host->port,
1021 .ipv4_address = host->ipv4_address[0] ? host->ipv4_address : "127.0.0.1",
1022 .bind_ipv4 = true,
1023 .max_connections = host->max_clients,
1024 .partial_timeout_ms = 30000,
1025 .callbacks = {host_connection_open, host_connection_packet, host_connection_closing, host_connection_closed},
1026 .user_data = host};
1027 result = network_server_create(&config, &host->network_server);
1028 if (result == ASCIICHAT_OK)
1029 result = network_server_start(host->network_server);
1030 if (result == ASCIICHAT_OK)
1031 result = platform_thread_create(&host->network_thread, "host_network", host_network_run, host);
1032 if (result != ASCIICHAT_OK) {
1033 network_server_destroy(&host->network_server);
1034 return result;
1035 }
1036 host->network_thread_started = true;
1037 host->running = true;
1038 return ASCIICHAT_OK;
1039#endif
1040}
1042 if (!host || !host->initialized)
1043 return ASCIICHAT_OK;
1044 if (host->render_thread_running) {
1045 host->render_thread_running = false;
1046 asciichat_error_t result = thread_join(&host->render_thread, NULL);
1047 if (result != ASCIICHAT_OK) {
1048 host->render_thread_running = true;
1049 return result;
1050 }
1051 }
1052#ifndef __EMSCRIPTEN__
1053 network_server_request_stop(host->network_server);
1054 if (host->network_thread_started) {
1055 asciichat_error_t result = thread_join(&host->network_thread, NULL);
1056 if (result != ASCIICHAT_OK)
1057 return result;
1058 host->network_thread_started = false;
1059 }
1060 asciichat_error_t result = network_server_stop(host->network_server);
1061 if (result != ASCIICHAT_OK)
1062 return result;
1063 network_server_destroy(&host->network_server);
1064 result = session_quic_listeners_close(&host->quic_endpoint, &host->webtransport_endpoint);
1065 if (result != ASCIICHAT_OK)
1066 return result;
1067#endif
1068 host->running = false;
1069 return ASCIICHAT_OK;
1070}
1072#ifndef __EMSCRIPTEN__
1073 if (!host || !host->network_server)
1074 return SET_ERRNO(ERROR_INVALID_STATE, "Host network is not running");
1075 return network_server_adopt(host->network_server, transport, "peer", true);
1076#else
1077 (void)host;
1078 (void)transport;
1079 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Browser peers use the browser host bridge");
1080#endif
1081}
1082
1084 if (!host || !host->initialized) {
1085 return false;
1086 }
1087 return host->running;
1088}
1089
1090/* ============================================================================
1091 * Session Host Client Management Functions
1092 * ============================================================================ */
1093
1094uint32_t session_host_add_client(session_host_t *host, acip_transport_t *transport, acip_transport_ownership_t ownership, const char *ip, int port) {
1095 if (!host || !host->initialized) {
1096 return 0;
1097 }
1098
1099 if ((ownership != ACIP_TRANSPORT_BORROWED && ownership != ACIP_TRANSPORT_OWNED) || (!transport && ownership == ACIP_TRANSPORT_OWNED)) {
1100 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport ownership");
1101 return 0;
1102 }
1103
1104 mutex_lock(&host->clients_mutex);
1105
1106 // Check if we have room
1107 if (host->client_count >= host->max_clients) {
1108 mutex_unlock(&host->clients_mutex);
1109 SET_ERRNO(ERROR_SESSION_FULL, "Maximum clients reached");
1110 return 0;
1111 }
1112
1113 // Find empty slot
1114 for (int i = 0; i < host->max_clients; i++) {
1115 if (!host->clients[i].active) {
1116 host->clients[i].participant_type = PARTICIPANT_TYPE_NETWORK;
1117 host->clients[i].client_id = host->next_client_id++;
1118 host->clients[i].connection = NULL;
1119 if (ip) {
1120 SAFE_STRNCPY(host->clients[i].ip_address, ip, sizeof(host->clients[i].ip_address));
1121 }
1122 host->clients[i].port = port;
1123 host->clients[i].active = true;
1124 host->clients[i].video_active = false;
1125 host->clients[i].audio_active = false;
1126 host->clients[i].connected_at = (uint64_t)time(NULL);
1127 host->clients[i].transport = NULL;
1128 host->clients[i].transport_ownership = ACIP_TRANSPORT_BORROWED;
1129 host->clients[i].render_width = 0;
1130 host->clients[i].render_height = 0;
1131 memset(&host->clients[i].rendering, 0, sizeof(host->clients[i].rendering));
1132 host->clients[i].rendering.fps_limit = DEFAULT_MAX_FPS;
1133 host->clients[i].next_video_deadline = 0;
1134
1135 // Allocate media buffers
1136 host->clients[i].incoming_video = image_new(480, 270); // Network-optimal size (HD preview)
1137 host->clients[i].incoming_audio = ringbuffer_create(sizeof(float), (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS) * HOST_AUDIO_BUFFER_FRAMES); // ~200ms buffer @ 48kHz
1138
1139 if (!host->clients[i].incoming_video || !host->clients[i].incoming_audio) {
1140 // Cleanup on allocation failure
1141 if (host->clients[i].incoming_video) {
1142 image_destroy(host->clients[i].incoming_video);
1143 host->clients[i].incoming_video = NULL;
1144 }
1145 if (host->clients[i].incoming_audio) {
1146 ringbuffer_destroy(host->clients[i].incoming_audio);
1147 host->clients[i].incoming_audio = NULL;
1148 }
1149 host->clients[i].active = false;
1150 mutex_unlock(&host->clients_mutex);
1151 SET_ERRNO(ERROR_MEMORY, "Failed to allocate media buffers for client");
1152 return 0;
1153 }
1154
1155 host->clients[i].transport = transport;
1156 host->clients[i].transport_ownership = ownership;
1157 uint32_t client_id = host->clients[i].client_id;
1158 host->client_count++;
1159
1160 mutex_unlock(&host->clients_mutex);
1161
1162 // Invoke callback
1163 if (host->callbacks.on_client_join) {
1164 host->callbacks.on_client_join(host, client_id, host->user_data);
1165 }
1166
1167 return client_id;
1168 }
1169 }
1170
1171 mutex_unlock(&host->clients_mutex);
1172 return 0;
1173}
1174
1176 if (!host || !host->initialized) {
1177 return 0;
1178 }
1179
1180 mutex_lock(&host->clients_mutex);
1181
1182 // Check if we have room
1183 if (host->client_count >= host->max_clients) {
1184 mutex_unlock(&host->clients_mutex);
1185 SET_ERRNO(ERROR_SESSION_FULL, "Maximum clients reached");
1186 return 0;
1187 }
1188
1189 // Check if memory participant already exists (only one allowed)
1190 for (int i = 0; i < host->max_clients; i++) {
1191 if (host->clients[i].active && host->clients[i].participant_type == PARTICIPANT_TYPE_MEMORY) {
1192 mutex_unlock(&host->clients_mutex);
1193 SET_ERRNO(ERROR_INVALID_PARAM, "Memory participant already exists");
1194 return 0;
1195 }
1196 }
1197
1198 // Find empty slot
1199 for (int i = 0; i < host->max_clients; i++) {
1200 if (!host->clients[i].active) {
1201 host->clients[i].participant_type = PARTICIPANT_TYPE_MEMORY;
1202 host->clients[i].client_id = host->next_client_id++;
1203 SAFE_STRNCPY(host->clients[i].ip_address, "memory", sizeof(host->clients[i].ip_address));
1204 host->clients[i].port = 0;
1205 host->clients[i].active = true;
1206 host->clients[i].video_active = true; // Memory participants always have active video/audio
1207 host->clients[i].audio_active = true;
1208 host->clients[i].connected_at = (uint64_t)time(NULL);
1209 host->clients[i].transport = NULL;
1210 host->clients[i].transport_ownership = ACIP_TRANSPORT_BORROWED;
1211
1212 // Allocate media buffers (same as network clients)
1213 host->clients[i].incoming_video = image_new(480, 270);
1214 host->clients[i].incoming_audio = ringbuffer_create(sizeof(float), (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS) * HOST_AUDIO_BUFFER_FRAMES);
1215
1216 if (!host->clients[i].incoming_video || !host->clients[i].incoming_audio) {
1217 if (host->clients[i].incoming_video) {
1218 image_destroy(host->clients[i].incoming_video);
1219 host->clients[i].incoming_video = NULL;
1220 }
1221 if (host->clients[i].incoming_audio) {
1222 ringbuffer_destroy(host->clients[i].incoming_audio);
1223 host->clients[i].incoming_audio = NULL;
1224 }
1225 host->clients[i].active = false;
1226 mutex_unlock(&host->clients_mutex);
1227 SET_ERRNO(ERROR_MEMORY, "Failed to allocate media buffers for memory participant");
1228 return 0;
1229 }
1230
1231 uint32_t participant_id = host->clients[i].client_id;
1232 host->client_count++;
1233
1234 mutex_unlock(&host->clients_mutex);
1235
1236 log_info("Added memory participant with ID %u", participant_id);
1237
1238 // Invoke callback
1239 if (host->callbacks.on_client_join) {
1240 host->callbacks.on_client_join(host, participant_id, host->user_data);
1241 }
1242
1243 return participant_id;
1244 }
1245 }
1246
1247 mutex_unlock(&host->clients_mutex);
1248 return 0;
1249}
1250
1252 if (!host || !host->initialized || !frame) {
1253 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
1254 }
1255
1256 if (!frame->pixels || frame->w <= 0 || frame->h <= 0 || image_validate_dimensions((size_t)frame->w, (size_t)frame->h) != ASCIICHAT_OK)
1257 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid injected image");
1258 size_t pixel_bytes;
1259 if (image_calc_rgb_size((size_t)frame->w, (size_t)frame->h, &pixel_bytes) != ASCIICHAT_OK)
1260 return SET_ERRNO(ERROR_INVALID_PARAM, "Injected image size is outside supported limits");
1261
1262 mutex_lock(&host->clients_mutex);
1263
1264 // Find memory participant
1265 for (int i = 0; i < host->max_clients; i++) {
1266 if (host->clients[i].active && host->clients[i].client_id == participant_id && host->clients[i].participant_type == PARTICIPANT_TYPE_MEMORY) {
1267
1268 if (!host->clients[i].incoming_video) {
1269 mutex_unlock(&host->clients_mutex);
1270 return SET_ERRNO(ERROR_INVALID_STATE, "Memory participant has no video buffer");
1271 }
1272
1273 // Copy frame data into buffer
1274 image_t *dest = host->clients[i].incoming_video;
1275 if (dest->w != frame->w || dest->h != frame->h) {
1276 // Reallocate if size changed
1277 image_t *replacement = image_new(frame->w, frame->h);
1278 if (!replacement) {
1279 mutex_unlock(&host->clients_mutex);
1280 return SET_ERRNO(ERROR_MEMORY, "Failed to reallocate video buffer");
1281 }
1282 image_destroy(dest);
1283 dest = replacement;
1284 host->clients[i].incoming_video = dest;
1285 }
1286
1287 // Copy pixel data
1288 memcpy(dest->pixels, frame->pixels, pixel_bytes);
1289
1290 host->clients[i].video_active = true;
1291
1292 mutex_unlock(&host->clients_mutex);
1293 return ASCIICHAT_OK;
1294 }
1295 }
1296
1297 mutex_unlock(&host->clients_mutex);
1298 return SET_ERRNO(ERROR_NOT_FOUND, "Memory participant not found");
1299}
1300
1302 if (!host || !host->initialized || !samples || count == 0 || count % AUDIO_CHANNELS) {
1303 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
1304 }
1305
1306 mutex_lock(&host->clients_mutex);
1307
1308 // Find memory participant
1309 for (int i = 0; i < host->max_clients; i++) {
1310 if (host->clients[i].active && host->clients[i].client_id == participant_id && host->clients[i].participant_type == PARTICIPANT_TYPE_MEMORY) {
1311
1312 if (!host->clients[i].incoming_audio) {
1313 mutex_unlock(&host->clients_mutex);
1314 return SET_ERRNO(ERROR_INVALID_STATE, "Memory participant has no audio buffer");
1315 }
1316
1317 // Write samples to ringbuffer (one at a time)
1318 size_t written = 0;
1319 for (size_t j = 0; j < count; j++) {
1320 if (ringbuffer_write(host->clients[i].incoming_audio, &samples[j])) {
1321 written++;
1322 } else {
1323 break; // Buffer full
1324 }
1325 }
1326
1327 if (written < count) {
1328 log_warn_every(NS_PER_MS_INT, "Audio ringbuffer full, dropped %zu samples", count - written);
1329 }
1330
1331 host->clients[i].audio_active = true;
1332
1333 mutex_unlock(&host->clients_mutex);
1334 return ASCIICHAT_OK;
1335 }
1336 }
1337
1338 mutex_unlock(&host->clients_mutex);
1339 return SET_ERRNO(ERROR_NOT_FOUND, "Memory participant not found");
1340}
1341
1343 if (!host || !host->initialized) {
1344 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
1345 }
1346
1347 mutex_lock(&host->clients_mutex);
1348
1349 for (int i = 0; i < host->max_clients; i++) {
1350 if (host->clients[i].active && host->clients[i].client_id == client_id) {
1351 // Invoke callback before removing
1352 mutex_unlock(&host->clients_mutex);
1353 if (host->callbacks.on_client_leave) {
1354 host->callbacks.on_client_leave(host, client_id, host->user_data);
1355 }
1356 mutex_lock(&host->clients_mutex);
1357
1358#ifndef __EMSCRIPTEN__
1359 if (host->clients[i].connection) {
1360 network_connection_request_stop(host->clients[i].connection);
1361 mutex_unlock(&host->clients_mutex);
1362 return ASCIICHAT_OK;
1363 }
1364#endif
1365 host_client_release_transport(&host->clients[i]);
1366
1367 // Clean up media buffers
1368 if (host->clients[i].incoming_video) {
1369 image_destroy(host->clients[i].incoming_video);
1370 host->clients[i].incoming_video = NULL;
1371 }
1372 if (host->clients[i].incoming_audio) {
1373 ringbuffer_destroy(host->clients[i].incoming_audio);
1374 host->clients[i].incoming_audio = NULL;
1375 }
1376
1377 host_forget_render_history(host, client_id);
1378 host->clients[i].active = false;
1379 host->client_count--;
1380 if (host->render_target.client_id == client_id)
1381 host->render_target = (session_host_render_target_t){0};
1382
1383 mutex_unlock(&host->clients_mutex);
1384 return ASCIICHAT_OK;
1385 }
1386 }
1387
1388 mutex_unlock(&host->clients_mutex);
1389 return SET_ERRNO(ERROR_NOT_FOUND, "Client not found: %u", client_id);
1390}
1391
1393 if (!host || !host->initialized || !info) {
1394 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
1395 }
1396
1397 mutex_lock(&host->clients_mutex);
1398
1399 for (int i = 0; i < host->max_clients; i++) {
1400 if (host->clients[i].active && host->clients[i].client_id == client_id) {
1401 info->client_id = host->clients[i].client_id;
1402 SAFE_STRNCPY(info->ip_address, host->clients[i].ip_address, sizeof(info->ip_address));
1403 info->port = host->clients[i].port;
1404 info->video_active = host->clients[i].video_active;
1405 info->audio_active = host->clients[i].audio_active;
1406 info->connected_at = host->clients[i].connected_at;
1407
1408 mutex_unlock(&host->clients_mutex);
1409 return ASCIICHAT_OK;
1410 }
1411 }
1412
1413 mutex_unlock(&host->clients_mutex);
1414 return SET_ERRNO(ERROR_NOT_FOUND, "Client not found: %u", client_id);
1415}
1416
1418 if (!host || !host->initialized) {
1419 return 0;
1420 }
1421 return host->client_count;
1422}
1423
1425 if (!host || !host->initialized || !ids || max_ids <= 0) {
1426 return 0;
1427 }
1428
1429 mutex_lock(&host->clients_mutex);
1430
1431 int count = 0;
1432 for (int i = 0; i < host->max_clients && count < max_ids; i++) {
1433 if (host->clients[i].active) {
1434 ids[count++] = host->clients[i].client_id;
1435 }
1436 }
1437
1438 mutex_unlock(&host->clients_mutex);
1439 return count;
1440}
1441
1442/* ============================================================================
1443 * Session Host Broadcast Functions
1444 * ============================================================================ */
1445
1447 if (!host || !host->initialized || !frame) {
1448 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
1449 }
1450
1451 if (!host->running) {
1452 return SET_ERRNO(ERROR_INVALID_STATE, "not running");
1453 }
1454
1455 // Broadcast ASCII frame to all connected clients
1456 size_t frame_len = strlen(frame);
1458
1459 mutex_lock(&host->clients_mutex);
1460 for (int i = 0; i < host->max_clients; i++) {
1461 if (host->clients[i].active && host->clients[i].transport) {
1462 asciichat_error_t send_result = acip_send_ascii_frame(host->clients[i].transport, &host->frame_workspace, frame, frame_len, 80, 24, "session-host");
1463 if (send_result != ASCIICHAT_OK) {
1464 log_warn("Failed to send ASCII frame to client %u", host->clients[i].client_id);
1465 result = send_result;
1466 }
1467 }
1468 }
1469 mutex_unlock(&host->clients_mutex);
1470
1471 return result;
1472}
1473
1475 if (!host || !host->initialized || !frame) {
1476 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
1477 }
1478
1479 if (!host->running) {
1480 return SET_ERRNO(ERROR_INVALID_STATE, "not running");
1481 }
1482
1483 // Send ASCII frame to specific client
1484 size_t frame_len = strlen(frame);
1485
1486 mutex_lock(&host->clients_mutex);
1487 for (int i = 0; i < host->max_clients; i++) {
1488 if (host->clients[i].client_id == client_id && host->clients[i].active) {
1489 asciichat_error_t result = host->clients[i].transport ? acip_send_ascii_frame(host->clients[i].transport, &host->frame_workspace, frame, frame_len, 80, 24, "session-host")
1490 : SET_ERRNO(ERROR_INVALID_STATE, "Client %u has no transport", client_id);
1491 mutex_unlock(&host->clients_mutex);
1492 return result;
1493 }
1494 }
1495 mutex_unlock(&host->clients_mutex);
1496
1497 return SET_ERRNO(ERROR_NOT_FOUND, "client %u not found", client_id);
1498}
1499
1500/* ============================================================================
1501 * Session Host Display Functions
1502 * ============================================================================ */
1503
1505 if (!host || !host->initialized) {
1506 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
1507 }
1508 if (target) {
1509 bool has_backend = target->get_config || target->render_frame;
1510 bool complete_backend = target->get_config && target->render_frame;
1511 bool valid_target = target->client_id ? !has_backend : complete_backend;
1512 if (!valid_target)
1513 return SET_ERRNO(ERROR_INVALID_PARAM, "Local rendering requires a client or a complete display backend");
1514 }
1515
1516 mutex_lock(&host->clients_mutex);
1517 if (target && target->client_id) {
1518 bool found = false;
1519 for (int i = 0; i < host->max_clients; ++i)
1520 if (host->clients[i].active && host->clients[i].client_id == target->client_id)
1521 found = true;
1522 if (!found) {
1523 mutex_unlock(&host->clients_mutex);
1524 return SET_ERRNO(ERROR_NOT_FOUND, "Local display client not found: %u", target->client_id);
1525 }
1526 }
1527 host->render_target = target ? *target : (session_host_render_target_t){0};
1528 mutex_unlock(&host->clients_mutex);
1529 return ASCIICHAT_OK;
1530}
1531
1532#ifndef __EMSCRIPTEN__
1533static asciichat_error_t native_display_config(void *context, session_host_render_config_t *config) {
1534 session_host_t *host = context;
1535 const terminal_capabilities_t *caps = session_display_get_caps(host->display_context);
1536 if (!caps)
1537 return SET_ERRNO(ERROR_INVALID_STATE, "Local terminal display is not initialized");
1538 config->caps = *caps;
1539 config->caps.render_mode = GET_OPTION(render_mode);
1540 config->caps.text_renderer = GET_OPTION(renderer);
1541 config->caps.stabilize = GET_OPTION(stabilize);
1542 config->caps.palette_explicit = GET_OPTION(palette_explicit);
1543 config->caps.wants_background = config->caps.render_mode == RENDER_MODE_BACKGROUND;
1544 if (GET_OPTION(color_mode) != TERM_COLOR_AUTO)
1545 config->caps.color_level = GET_OPTION(color_mode);
1546 config->caps.color_filter = GET_OPTION(color_filter);
1547 config->palette = session_display_get_palette_chars(host->display_context);
1548 config->width = GET_OPTION(width) > 0 ? GET_OPTION(width) : 80;
1549 config->height = GET_OPTION(height) > 0 ? GET_OPTION(height) : 24;
1550 return ASCIICHAT_OK;
1551}
1552
1553static void native_display_frame(void *context, const char *frame, size_t size, int width, int height) {
1554 (void)size;
1555 (void)width;
1556 (void)height;
1557 session_host_t *host = context;
1558 if (!host->display_logging_disabled) {
1560 host->display_logging_disabled = true;
1561 }
1562 session_display_render_frame(host->display_context, frame);
1563 if (GET_OPTION(snapshot_mode) && host->snapshot_first_frame_ns == 0 && session_display_has_first_frame(host->display_context))
1564 host->snapshot_first_frame_ns = time_get_ns();
1565}
1566
1568 if (!host || !host->initialized)
1569 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
1570 mutex_lock(&host->clients_mutex);
1571 host->display_context = display;
1572 host->render_target = display ? (session_host_render_target_t){.get_config = native_display_config, .render_frame = native_display_frame, .context = host} : (session_host_render_target_t){0};
1573 mutex_unlock(&host->clients_mutex);
1574 return ASCIICHAT_OK;
1575}
1576#endif
1577
1578/* ============================================================================
1579 * Session Host Render Thread Functions
1580 * ============================================================================ */
1581
1583 if (!host || !host->initialized) {
1584 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid host");
1585 }
1586
1587 // Discovery mode starts the shared host renderer without passing through
1588 // server/main.c, which normally initializes the ASCII lookup palettes.
1590
1591 if (!host->running) {
1592 return SET_ERRNO(ERROR_INVALID_STATE, "not running");
1593 }
1594
1595 if (host->render_thread_running) {
1596 return ASCIICHAT_OK; // Already running
1597 }
1598
1599 // Create audio context for mixing (host mode = true)
1600 if (!host->audio_ctx) {
1601 host->audio_ctx = session_audio_create(true);
1602 if (!host->audio_ctx) {
1603 return SET_ERRNO(ERROR_INVALID_STATE, "Failed to create audio context");
1604 }
1605 }
1606
1607 // Spawn render thread
1608 host->render_thread_running = true;
1609 if (platform_thread_create(&host->render_thread, "render", host_render_thread, host) != 0) {
1610 log_error("Failed to spawn render thread");
1611 host->render_thread_running = false;
1612 return SET_ERRNO(ERROR_THREAD, "Failed to spawn render thread");
1613 }
1614
1615 log_info("Host render thread started");
1616 return ASCIICHAT_OK;
1617}
1618
1620 if (!host || !host->initialized) {
1621 return;
1622 }
1623
1624 if (!host->render_thread_running) {
1625 return;
1626 }
1627
1628 // Signal thread to stop
1629 host->render_thread_running = false;
1630
1631 // Wait for thread to complete
1632 if (thread_join(&host->render_thread, NULL) != ASCIICHAT_OK) {
1633 host->render_thread_running = true;
1634 SET_ERRNO(ERROR_THREAD, "Render worker still owns host audio resources");
1635 return;
1636 }
1637
1638 // Clean up audio resources
1639 if (host->audio_ctx) {
1640#ifndef __EMSCRIPTEN__
1641 session_audio_destroy(host->audio_ctx);
1642#endif
1643 host->audio_ctx = NULL;
1644 }
1645
1646 log_info("Host render thread stopped");
1647}
1648
1649/* ============================================================================
1650 * Session Host Transport Functions (WebRTC Integration)
1651 * ============================================================================ */
1652
1654 if (!host || !host->initialized) {
1655 return SET_ERRNO(ERROR_INVALID_PARAM, "Host is NULL or not initialized");
1656 }
1657
1658 if ((ownership != ACIP_TRANSPORT_BORROWED && ownership != ACIP_TRANSPORT_OWNED) || (!transport && ownership == ACIP_TRANSPORT_OWNED))
1659 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport ownership");
1660
1661 mutex_lock(&host->clients_mutex);
1662
1663 // Find client with matching ID
1664 for (int i = 0; i < host->max_clients; i++) {
1665 if (host->clients[i].active && host->clients[i].client_id == client_id) {
1666 log_info("Setting transport=%p for client %u (was=%p)", transport, client_id, host->clients[i].transport);
1667
1668 if (host->clients[i].transport == transport && host->clients[i].transport_ownership != ownership) {
1669 mutex_unlock(&host->clients_mutex);
1670 return SET_ERRNO(ERROR_INVALID_STATE, "Cannot change ownership of a registered transport");
1671 }
1672 server_state_packet_t state = {0};
1673 if (transport) {
1674 uint32_t active_count = 0;
1675 for (int j = 0; j < host->max_clients; j++) {
1676 if (host->clients[j].active) {
1677 active_count++;
1678 }
1679 }
1680 state.connected_client_count = HOST_TO_NET_U32(active_count);
1681 state.active_client_count = HOST_TO_NET_U32(active_count);
1682 }
1683 if (transport) {
1684 asciichat_error_t result = acip_send_server_state(transport, &state);
1685 if (result != ASCIICHAT_OK) {
1686 mutex_unlock(&host->clients_mutex);
1687 return result;
1688 }
1689 }
1690 if (host->clients[i].transport != transport)
1691 host_client_release_transport(&host->clients[i]);
1692 host->clients[i].transport = transport;
1693 host->clients[i].transport_ownership = transport ? ownership : ACIP_TRANSPORT_BORROWED;
1694 mutex_unlock(&host->clients_mutex);
1695 return ASCIICHAT_OK;
1696 }
1697 }
1698
1699 mutex_unlock(&host->clients_mutex);
1700 log_warn("Client %u not found", client_id);
1701 return SET_ERRNO(ERROR_NOT_FOUND, "Client not found");
1702}
1703
1705 if (!host || !host->initialized) {
1706 return NULL;
1707 }
1708
1709 mutex_lock(&host->clients_mutex);
1710
1711 // Find client with matching ID
1712 for (int i = 0; i < host->max_clients; i++) {
1713 if (host->clients[i].active && host->clients[i].client_id == client_id) {
1714 acip_transport_t *transport = host->clients[i].transport;
1715 mutex_unlock(&host->clients_mutex);
1716 return transport;
1717 }
1718 }
1719
1720 mutex_unlock(&host->clients_mutex);
1721 return NULL;
1722}
1723
1725 if (!host || !host->initialized) {
1726 return false;
1727 }
1728
1729 mutex_lock(&host->clients_mutex);
1730
1731 // Find client with matching ID
1732 for (int i = 0; i < host->max_clients; i++) {
1733 if (host->clients[i].active && host->clients[i].client_id == client_id) {
1734 bool has_transport = host->clients[i].transport != NULL;
1735 mutex_unlock(&host->clients_mutex);
1736 return has_transport;
1737 }
1738 }
1739
1740 mutex_unlock(&host->clients_mutex);
1741 return false;
1742}
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
asciichat_error_t ascii_grid_layout(int source_count, int width, int height, int *grid_cols, int *grid_rows)
Definition ascii.c:625
char * ascii_convert_with_buffers_stabilized(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch, const char *palette_chars, const bool contain, image_t **workspace, outbuf_t *output, ascii_stabilizer_t *stabilizer)
Definition ascii.c:282
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define OPUS_FRAME_SAMPLES
#define CLIENT_AUDIO_PIPELINE_FRAME_MS
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:8
#define AUDIO_CHANNELS
Definition audio/limits.h:9
#define AUDIO_OPUS_SESSION_PACKET_CAPACITY
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
Application limits and constraints.
Matrix-style digital rain effect for ASCII frames.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
int color_mode
Definition fft.c:26
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
int opus_codec_decode(opus_codec_t *codec, const uint8_t *data, size_t data_len, float *out_samples, int out_num_samples)
Decode Opus audio frame.
Definition opus.c:171
void opus_codec_destroy(opus_codec_t *codec)
Destroy an Opus codec instance.
Definition opus.c:271
size_t opus_codec_encode(opus_codec_t *codec, const float *samples, int num_samples, uint8_t *out_data, size_t out_size)
Encode audio frame with Opus.
Definition opus.c:132
opus_codec_t * opus_codec_create_decoder_channels(int sample_rate, int channels)
Definition opus.c:91
opus_codec_t * opus_codec_create_encoder_channels(opus_application_t application, int sample_rate, int bitrate, int channels)
Definition opus.c:39
@ OPUS_APPLICATION_AUDIO
General audio (optimized for music).
Definition opus.h:86
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#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_INVALID_STATE
@ ERROR_NOT_FOUND
@ ERROR_AUDIO
Definition error_codes.h:66
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_SESSION_FULL
Definition error_codes.h:86
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73
key_type_t type
Definition key_types.h:102
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second).
#define IP_ADDRESS_BUFFER_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
#define US_PER_MS_INT
Definition time.h:176
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
@ PACKET_TYPE_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ PACKET_TYPE_CLIENT_LEAVE
Clean disconnect notification.
Definition packet.h:427
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429
@ PACKET_TYPE_ACIP_SETTINGS_SYNC
Settings sync (Initiator -> Host -> All Participants).
Definition packet.h:499
@ PACKET_TYPE_ACIP_SETTINGS_ACK
Settings acknowledgment (Participant -> Initiator).
Definition packet.h:501
@ PACKET_TYPE_CLIENT_CAPABILITIES
Client reports terminal capabilities.
Definition packet.h:419
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_STREAM_STOP
Client stops sending media.
Definition packet.h:431
#define GET_OPTION(field)
Definition options.h:1333
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921
bool palette_requires_utf8_encoding(const char *chars, size_t len)
Check if palette requires UTF-8 encoding.
Definition palette.c:53
const palette_def_t * get_builtin_palette(palette_type_t type)
Get built-in palette definition.
Definition palette.c:45
const char * chars
Character sequence (ordered from dark to light).
Definition palette.h:134
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:100
#define PIXEL_FORMAT_BGRA
BGRA pixel format.
#define PIXEL_FORMAT_RGB
Packed RGB24 pixel format used by ACIP image-frame senders.
#define PIXEL_FORMAT_BGR
BGR pixel format.
#define PIXEL_FORMAT_RGBA
Packed RGBA32 pixel format.
ringbuffer_t * ringbuffer_create(size_t element_size, size_t capacity)
Create a new ring buffer.
Definition ringbuffer.c:34
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:60
bool ringbuffer_read(ringbuffer_t *rb, void *data)
Try to read an element from the ring buffer (non-blocking).
Definition ringbuffer.c:92
bool ringbuffer_write(ringbuffer_t *rb, const void *data)
Try to write an element to the ring buffer (non-blocking).
Definition ringbuffer.c:70
void session_host_stop_render(session_host_t *host)
Stop media rendering thread.
Definition host.c:1619
struct session_audio_ctx session_audio_ctx_t
Opaque session audio context handle.
asciichat_error_t session_host_inject_audio(session_host_t *host, uint32_t participant_id, const float *samples, size_t count)
Inject audio samples from memory participant.
Definition host.c:1301
asciichat_error_t session_host_destroy(session_host_t *host)
Destroy session host and free resources.
Definition host.c:289
bool session_host_client_has_transport(session_host_t *host, uint32_t client_id)
Check if a specific client has an active ACIP transport.
Definition host.c:1724
int splash_intro_done(void)
Signal that intro splash should end (first frame ready to render).
Definition splash.c:421
bool session_host_is_running(session_host_t *host)
Check if host is running.
Definition host.c:1083
asciichat_error_t session_host_stop(session_host_t *host)
Stop accepting connections and disconnect all clients.
Definition host.c:1041
void session_audio_destroy(session_audio_ctx_t *ctx)
Destroy session audio context and free resources.
asciichat_error_t session_host_set_client_transport(session_host_t *host, uint32_t client_id, acip_transport_t *transport, acip_transport_ownership_t ownership)
Select a transport for a specific client in the host.
Definition host.c:1653
struct session_host session_host_t
Opaque session host handle.
asciichat_error_t session_host_inject_frame(session_host_t *host, uint32_t participant_id, const image_t *frame)
Inject a video frame from memory participant.
Definition host.c:1251
uint32_t session_host_add_memory_participant(session_host_t *host)
Add a memory participant (host's own media).
Definition host.c:1175
asciichat_error_t session_host_set_display(session_host_t *host, struct session_display_ctx *display)
Set a native terminal display context for local frame rendering.
Definition host.c:1567
void session_display_render_frame(session_display_ctx_t *ctx, const char *frame_data)
Render an ASCII frame to the terminal.
bool session_display_has_first_frame(session_display_ctx_t *ctx)
Check if the display has rendered its first frame.
acip_transport_t * session_host_get_client_transport(session_host_t *host, uint32_t client_id)
Get the current transport for a specific client in the host.
Definition host.c:1704
asciichat_error_t session_host_send_frame(session_host_t *host, uint32_t client_id, const char *frame)
Send ASCII frame to a specific client.
Definition host.c:1474
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
session_audio_ctx_t * session_audio_create(bool is_host)
Create a new session audio context.
const char * session_display_get_palette_chars(session_display_ctx_t *ctx)
Get the palette characters string.
void splash_wait_for_animation(void)
Wait for splash animation thread to fully exit.
Definition splash.c:446
const terminal_capabilities_t * session_display_get_caps(session_display_ctx_t *ctx)
Get detected terminal capabilities.
int session_host_get_client_count(session_host_t *host)
Get number of connected clients.
Definition host.c:1417
asciichat_error_t session_host_remove_client(session_host_t *host, uint32_t client_id)
Remove a client by ID.
Definition host.c:1342
asciichat_error_t session_host_find_client(session_host_t *host, uint32_t client_id, session_host_client_info_t *info)
Find a client by ID.
Definition host.c:1392
asciichat_error_t session_host_start(session_host_t *host)
Start accepting client connections.
Definition host.c:1003
int session_host_get_client_ids(session_host_t *host, uint32_t *ids, int max_ids)
Get list of all connected client IDs.
Definition host.c:1424
asciichat_error_t session_host_broadcast_frame(session_host_t *host, const char *frame)
Broadcast ASCII frame to all clients.
Definition host.c:1446
session_host_t * session_host_create(const session_host_config_t *config)
Create a new session host.
Definition host.c:234
asciichat_error_t session_host_start_render(session_host_t *host)
Start media rendering thread (video mixing and audio distribution).
Definition host.c:1582
void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter)
Set digital rain color from color filter.
void digital_rain_destroy(digital_rain_t *rain)
Destroy digital rain effect context.
char * digital_rain_apply(digital_rain_t *rain, const char *frame, float delta_time)
Apply digital rain effect to ASCII frame.
struct digital_rain digital_rain_t
Digital rain effect context.
void ascii_simd_init(void)
Initialize SIMD subsystem.
digital_rain_t * digital_rain_init(int num_columns, int num_rows)
Initialize digital rain effect context.
char * ascii_create_grid(ascii_frame_source_t *sources, int source_count, int width, int height, size_t *out_size)
Create a grid layout from multiple ASCII frames.
Definition ascii.c:708
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
#define SESSION_HOST_KEY_PATH_BUFFER_SIZE
Definition host.c:4
asciichat_error_t session_host_render_audio(session_host_t *host)
Definition host.c:794
asciichat_error_t session_host_render_video(session_host_t *host)
Definition host.c:787
uint32_t session_host_add_client(session_host_t *host, acip_transport_t *transport, acip_transport_ownership_t ownership, const char *ip, int port)
Definition host.c:1094
struct host_render_history host_render_history_t
Owns the server-side session state, including connected participants, host callbacks,...
asciichat_error_t session_host_set_render_target(session_host_t *host, const session_host_render_target_t *target)
Definition host.c:1504
#define SESSION_HOST_DEFAULT_MAX_CLIENTS
Default maximum clients.
Definition host.c:68
asciichat_error_t session_host_accept_peer(session_host_t *host, acip_transport_t *transport)
Definition host.c:1071
#define HOST_AUDIO_BUFFER_FRAMES
Definition host.c:5
asciichat_error_t session_host_receive_packet(session_host_t *host, uint32_t client_id, packet_type_t ptype, const void *data, size_t len)
Definition host.c:343
🏠 Server-side session hosting abstraction
⚙️ Common definitions, error codes, macros, and types shared throughout the application
ACIP server-side protocol API.
Transport abstraction layer for ACIP protocol.
participant_type_t
For client info, this is the live record that ties participant_type, network_connection,...
struct quic_endpoint quic_endpoint_t
struct network_server network_server_t
struct network_connection network_connection_t
SIMD-optimized ASCII conversion interface.
asciichat_error_t acip_send_server_state(acip_transport_t *transport, const server_state_packet_t *state)
Send server state update to client (server → client).
asciichat_error_t acip_send_ascii_frame_contract(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *frame_data, size_t frame_size, uint32_t width, uint32_t height, const acip_render_settings_t *settings, uint32_t effects, const char *client_id)
asciichat_error_t acip_send_ascii_frame(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *text, size_t length, uint32_t width, uint32_t height, const char *client_id)
void acip_frame_workspace_destroy(acip_frame_workspace_t *workspace)
asciichat_error_t acip_render_settings_capabilities(acip_render_settings_t *state, const terminal_capabilities_packet_t *packet)
asciichat_error_t acip_settings_encode(const acip_settings_header_t *header, const char *json, uint8_t *buffer, size_t capacity, size_t *length)
asciichat_error_t acip_settings_request(acip_render_settings_t *state, const void *payload, size_t length, uint8_t *reply, size_t capacity, size_t *reply_length)
void network_connection_ready(network_connection_t *c)
asciichat_error_t network_server_create(const network_server_config_t *config, network_server_t **out)
network_connection_state_t network_connection_state(network_connection_t *c)
void network_connection_request_stop(network_connection_t *c)
const char * network_connection_peer(network_connection_t *c)
void network_connection_set_context(network_connection_t *c, void *context)
asciichat_error_t network_connection_prepare_security(network_connection_t *c, bool server, const char *password)
asciichat_error_t network_server_start(network_server_t *s)
void * network_connection_context(network_connection_t *c)
crypto_handshake_context_t * network_connection_handshake(network_connection_t *c)
bool network_connection_secure(network_connection_t *c)
acip_transport_t * network_connection_transport(network_connection_t *c)
void network_server_destroy(network_server_t **owner)
asciichat_error_t network_server_adopt(network_server_t *s, acip_transport_t *transport, const char *peer, bool secure)
void network_server_request_stop(network_server_t *s)
asciichat_error_t network_server_stop(network_server_t *s)
asciichat_error_t network_server_run(network_server_t *s)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
#define ascii_stabilizer_reset
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
void signal_exit(void)
Definition main.c:252
asciichat_error_t network_negotiation_receive(network_negotiation_t *n, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length)
@ NETWORK_PROTOCOL_MEDIA
Definition negotiation.h:9
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
Opus audio codec wrapper for real-time encoding/decoding.
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
✅ Safe Integer Arithmetic and Overflow Detection
ASCII Palette Management for Video-to-ASCII Conversion.
Protocol version, features, compression, and frame flag constants.
static bool size_t index
Definition queries.h:8
asciichat_error_t session_quic_listeners_close(quic_endpoint_t **native, quic_endpoint_t **webtransport)
asciichat_error_t session_quic_listeners_open(int port, quic_endpoint_t **native, quic_endpoint_t **webtransport)
void audio_recording_submit(audio_recording_source_t source, const float *samples, size_t count, uint64_t start_ns)
Definition recording.c:79
@ AUDIO_RECORDING_REMOTE
Definition recording.h:13
#define FRAME_RENDER_CONTRACT_RAIN
#define FRAME_RENDER_CONTRACT_GRID
Lock-Free Ring Buffer and Frame Buffer Management.
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78
asciichat_error_t acip_send_pong(acip_transport_t *transport)
Send pong packet.
Definition send.c:382
asciichat_error_t acip_send_audio_opus_batch(acip_transport_t *transport, const void *opus_data, size_t opus_len, const uint16_t *frame_sizes, uint32_t frame_count, uint32_t sample_rate, uint32_t frame_duration)
Send batched Opus-encoded audio frames.
Definition send.c:338
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
#define PASSWORD_BUFFER_SIZE
Password input buffer size (256 bytes).
Definition sizes.h:162
Intro and status screen display for ascii-chat with animated rainbow effects.
uint8_t participant_id[SESSION_ID_SIZE]
🔊 Session-level audio coordination wrapper
🖥️ Unified terminal display abstraction for session-based rendering
bool terminal_is_interactive(void)
bool terminal_is_stdout_tty(void)
🔤 String Manipulation and Shell Escaping Utilities
Send ASCII frame to client (server → client).
acip render settings keeps the values that move through the subsystem: caps, width,...
acip settings header keeps the values that move through the subsystem: schema, request,...
Frame source structure for grid layout.
Definition ascii.h:350
size_t frame_size
Frame data size in bytes (length of frame string).
Definition ascii.h:352
const char * frame_data
Frame data pointer (ASCII frame string, not owned).
Definition ascii.h:351
Cryptographic handshake context structure.
int num_rows
Number of rows in grid.
int num_columns
Number of columns in grid.
private_key_t identity
Definition host.c:923
network_negotiation_t negotiation
Definition host.c:922
uint32_t client_id
Definition host.c:921
Owns the server-side session state, including connected participants, host callbacks,...
Definition host.c:149
uint32_t viewer_id
Definition host.c:150
uint32_t source_id
Definition host.c:150
ascii_stabilizer_t stabilizer
Definition host.c:151
struct host_render_history * next
Definition host.c:152
Describes one compressed image sent through ACIP. width, height, and pixel_format tell the decoder ho...
Definition packet.h:948
uint32_t pixel_format
Pixel format enum (1=RGB24, 2=RGBA32, 3=BGR24, 4=BGRA32).
Definition packet.h:954
uint32_t height
Image height in pixels.
Definition packet.h:952
uint32_t width
Image width in pixels.
Definition packet.h:950
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
When code needs to work with network negotiation, it keeps protocol, handshake, identity_keys,...
Definition negotiation.h:18
State for one Opus encoding or decoding direction.
Definition opus.h:105
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
Audio ring buffer for real-time audio streaming.
Definition ringbuffer.h:94
Server state packet structure.
Definition packet.h:757
uint32_t active_client_count
Number of clients actively sending video/audio streams.
Definition packet.h:761
uint32_t connected_client_count
Total number of currently connected clients.
Definition packet.h:759
Runtime terminal state and reusable workspaces for ASCII rendering.
terminal_capabilities_t caps
Detected terminal capabilities.
Snapshot of the address, identity, activity, and connection time for one host client.
Definition host.h:112
Snapshot of the address, identity, activity, and connection time for one host client.
Definition host.h:87
uint64_t connected_at
Connection timestamp (Unix time).
Definition host.h:104
int port
Client port.
Definition host.h:95
bool audio_active
Client is currently streaming audio.
Definition host.h:101
char ip_address[IP_ADDRESS_BUFFER_SIZE]
Client IP address.
Definition host.h:92
uint32_t client_id
Unique client identifier.
Definition host.h:89
bool video_active
Client is currently streaming video.
Definition host.h:98
Keeps the host-side rendering history used to compare successive frames and stabilize output for conn...
Definition host.c:88
ringbuffer_t * incoming_audio
Incoming audio ringbuffer (written by receive loop, read by render thread).
Definition host.c:113
acip_transport_ownership_t transport_ownership
Definition host.c:107
char ip_address[IP_ADDRESS_BUFFER_SIZE]
Definition host.c:92
digital_rain_t * rain
Definition host.c:101
acip_render_settings_t rendering
Definition host.c:100
float audio_frame[(OPUS_FRAME_SAMPLES *AUDIO_CHANNELS)]
Definition host.c:116
uint16_t render_height
Definition host.c:99
opus_codec_t * opus_encoder
Definition host.c:115
uint32_t client_id
Definition host.c:90
participant_type_t participant_type
Definition host.c:89
network_connection_t * connection
Definition host.c:91
uint64_t connected_at
Definition host.c:97
image_t * incoming_video
Incoming video frame buffer (for host render thread).
Definition host.c:110
uint16_t render_width
Definition host.c:98
struct acip_transport * transport
Transport borrowed from the connection owner or browser bridge.
Definition host.c:106
uint64_t next_video_deadline
Definition host.c:102
opus_codec_t * opus_decoder
Definition host.c:114
Host-side event hooks for joins, departures, media, and errors.
Definition host.h:163
void * user_data
User-provided context pointer passed to callbacks.
Definition host.h:192
const char * ipv6_address
IPv6 address to bind to (NULL for any).
Definition host.h:171
session_host_callbacks_t callbacks
Event callbacks.
Definition host.h:189
bool encryption_enabled
Enable encryption (default: true).
Definition host.h:177
bool configured_quic_listeners
Definition host.h:180
const char * key_path
Path to server identity key.
Definition host.h:183
int port
Port to listen on (default: 27224).
Definition host.h:165
const char * password
Password for client authentication (optional).
Definition host.h:186
const char * ipv4_address
IPv4 address to bind to (NULL for any).
Definition host.h:168
int max_clients
Maximum number of clients.
Definition host.h:174
When code needs to work with session host render config, it keeps caps, palette, width,...
Definition host.h:440
terminal_capabilities_t caps
Definition host.h:441
session host render target is intentionally a small, concrete record. Fields such as client_id,...
Definition host.h:452
void(* render_frame)(void *context, const char *frame, size_t size, int width, int height)
Definition host.h:455
asciichat_error_t(* get_config)(void *context, session_host_render_config_t *config)
Definition host.h:454
char password[PASSWORD_BUFFER_SIZE]
Password.
Definition host.c:177
bool running
Server is running.
Definition host.c:201
mutex_t clients_mutex
Client list mutex.
Definition host.c:213
bool initialized
Context is initialized.
Definition host.c:225
acip_frame_workspace_t frame_workspace
Definition host.c:156
platform_thread_t network_thread
IPv6 listen socket.
Definition host.c:197
quic_endpoint_t * webtransport_endpoint
Definition host.c:194
bool network_thread_started
Definition host.c:198
struct session_display_ctx * display_context
Display context for local frame rendering (optional, can be NULL).
Definition host.c:186
int client_count
Current client count.
Definition host.c:207
session_host_render_target_t render_target
Definition host.c:187
session_host_client_t * clients
Client array.
Definition host.c:204
network_server_t * network_server
IPv4 listen socket.
Definition host.c:192
bool display_logging_disabled
Definition host.c:188
char ipv4_address[IP_ADDRESS_BUFFER_SIZE]
IPv4 bind address.
Definition host.c:162
void * user_data
User data for callbacks.
Definition host.c:183
char key_path[512]
Key path.
Definition host.c:174
session_host_callbacks_t callbacks
Event callbacks.
Definition host.c:180
session_audio_ctx_t * audio_ctx
Audio context for mixing (host only).
Definition host.c:222
char ipv6_address[IP_ADDRESS_BUFFER_SIZE]
IPv6 bind address.
Definition host.c:165
bool configured_quic_listeners
Definition host.c:193
int max_clients
Maximum clients.
Definition host.c:168
int port
Port to listen on.
Definition host.c:159
uint64_t snapshot_first_frame_ns
Definition host.c:189
host_render_history_t * render_histories
Definition host.c:157
bool render_thread_running
Render thread is running.
Definition host.c:219
uint32_t next_client_id
Next client ID counter.
Definition host.c:210
platform_thread_t render_thread
Render thread handle (for video mixing and audio distribution).
Definition host.c:216
bool encryption_enabled
Encryption enabled.
Definition host.c:171
quic_endpoint_t * quic_endpoint
Definition host.c:194
Terminal capabilities packet structure (Packet Type 5).
Definition packet.h:1093
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t image_validate_dimensions(size_t width, size_t height)
Validate image dimensions (non-zero, within limits).
Definition util/image.c:97
asciichat_error_t image_calc_rgb_size(size_t width, size_t height, size_t *out_size)
Calculate total RGB buffer size from dimensions.
Definition util/image.c:53
🖼️ Safe overflow-checked buffer size calculations for images and video frames