ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
client/main.c
Go to the documentation of this file.
2#include <sodium.h>
69
72#include "session/protocol.h"
73
74#include "main.h"
75#include "../main.h" // Global exit API
76#include "server.h"
77#include "protocol_adapter.h"
78#include "crypto.h"
79#include "display.h"
80#include "capture.h"
81#include "audio.h"
85#include "session/client_like.h"
88#include <ascii-chat/tui/mdns.h>
91
92#include <libplatform/compiler.h>
93#include <libplatform/system.h>
94#include <libplatform/terminal.h>
96#include <libplatform/terminal.h>
97#include <libplatform/symbols.h>
98#include <libplatform/system.h>
99#include <ascii-chat/common.h>
101#include <ascii-chat/log/log.h>
102#include <ascii-chat/log/json.h>
103#include <options/options.h>
104#include <options/rcu.h> // For RCU-based options access
105#include <ascii-chat/util/time.h> // For time macros
106#include <ascii-chat/util/url.h> // For URL parsing and WebSocket detection
107#include <ascii-chat/buffer.h>
112#include <ascii-chat/util/ip.h>
116#include <ascii-chat/util/path.h>
118
119#ifndef NDEBUG
121#ifdef DEBUG_MEMORY
123#endif
124#endif
125
126#include <signal.h>
127#include <stdlib.h>
128#include <stdio.h>
129#include <string.h>
130#include <libplatform/atomic.h>
131#ifndef _WIN32
132#include <unistd.h>
133#endif
134#include <fcntl.h>
135
136/* ============================================================================
137 * Global State Variables
138 * ============================================================================ */
139
148
160typedef struct {
161 const char *discovered_address; // From LAN/session discovery
162 int discovered_port; // From LAN/session discovery
163 int reconnect_attempt; // Current reconnection attempt number
164 char password[PASSWORD_BUFFER_SIZE]; // Retained across attempts, wiped by session cleanup.
165 bool has_ever_connected; // Track if connection ever succeeded
167
168static client_session_state_t g_client_session = {0};
169static acip_websocket_runtime_t *g_websocket_runtime;
170
171/* Signal handling is now centralized in src/main.c via setup_signal_handlers()
172 * Signal handlers publish application exit; the owner interrupts network I/O
173 * in normal thread context. Resize detection is polled through libplatform.
174 */
175
185static void shutdown_client() {
186 // Guard against double cleanup (can be called explicitly + via atexit)
187 static bool shutdown_done = false;
188 if (shutdown_done) {
189 return;
190 }
191 shutdown_done = true;
192 log_debug("[SHUTDOWN] 1. Starting shutdown");
193
194 // Set global shutdown flag to stop all threads
195 signal_exit();
196
197 // Stop splash animation thread before any resource cleanup
199
200 sodium_memzero(g_client_session.password, sizeof(g_client_session.password));
203 acip_websocket_runtime_destroy(&g_websocket_runtime);
204
205 // Print audio analysis report if enabled
206 // Print audio analysis report if enabled
207 if (GET_OPTION(audio_analysis_enabled)) {
210 }
211
212 // Cleanup display and terminal state
213 // WORKAROUND: Skip cleanup during shutdown to avoid hanging
214 // display_cleanup();
215
216 // Cleanup core systems
217 // WORKAROUND: Skip cleanup during shutdown to avoid hanging
218 // buffer_system_cleanup();
219
220 // Disable keepawake mode (re-allow OS to sleep)
222
223 log_debug("Client shutdown complete");
224 log_destroy();
225}
226
236static int initialize_client_systems(void) {
237 // All shared subsystem initialization (timer, logging, platform, buffer domain)
238 // is now done by asciichat_shared_init() in src/main.c BEFORE options_init()
239
240 // Ensure logging output is available for connection attempts (unless it was disabled with --quiet)
241 if (!GET_OPTION(quiet)) {
243 }
245
246 // Display subsystem is now initialized by session_client_like_run()
247 // No need to call display_init() here
248
249 // Initialize capture subsystems
250 int capture_result = capture_init();
251 if (capture_result != 0) {
252 log_fatal("Failed to initialize capture subsystem");
253 return capture_result;
254 }
255
256 // Timed recordings capture call audio; immediate snapshots need only one frame.
257 if (GET_OPTION(audio_enabled) && (!GET_OPTION(snapshot_mode) || GET_OPTION(snapshot_delay) > 0)) {
258 if (audio_client_init() != 0) {
259 NOTICE(WARNING, "AUDIO UNAVAILABLE", "Failed to initialize audio system");
260 // Continue without audio instead of crashing (e.g., ARM systems with audio device incompatibility)
261 }
262
263 // Initialize audio analysis if requested
264 if (GET_OPTION(audio_analysis_enabled)) {
265 if (audio_analysis_init() != 0) {
266 log_warn("Failed to initialize audio analysis");
267 }
268 }
269 }
270
271 return 0;
272}
273
274/* ============================================================================
275 * Client Connection/Reconnection Loop (run_fn for session_client_like)
276 * ============================================================================
277 *
278 * This callback is executed after shared initialization (media/audio/display)
279 * is complete. It manages the entire client connection lifecycle:
280 * 1. Connect to server (with fallback stages: TCP, WebRTC+STUN, WebRTC+TURN)
281 * 2. Exchange media/audio with server
282 * 3. On disconnection, attempt reconnection based on policy
283 * 4. Exit on user request or max reconnection limit
284 */
285
297static bool client_should_reconnect(asciichat_error_t last_error, int attempt_number, void *user_data) {
298 if (last_error == ERROR_CRYPTO_AUTH || last_error == ERROR_CRYPTO_KEY || last_error == ERROR_CRYPTO_VERIFICATION || last_error == ERROR_CONFIG || last_error == ERROR_INVALID_PASSWORD ||
299 last_error == ERROR_INVALID_SIGNATURE || last_error == ERROR_NETWORK_PROTOCOL || last_error == ERROR_INTERNAL)
300 return false;
301 (void)attempt_number;
302 (void)user_data;
303
304 // In snapshot mode, don't reconnect - exit after first failure
305 if (GET_OPTION(snapshot_mode)) {
306 log_error("Connection lost in snapshot mode - not retrying");
307 return false;
308 }
309
310 // Otherwise, allow reconnection (framework handles max_reconnect_attempts limit)
311 return true;
312}
313
330static asciichat_error_t client_send_settings(const options_t *values, uint32_t request, void *context) {
331 return acip_settings_send(server_connection_get_transport((client_connection_t *)context), values, request, UINT32_MAX);
332}
333
334static asciichat_error_t client_run_attempt(session_capture_ctx_t *capture, session_display_ctx_t *display, void *user_data) {
335 (void)capture; // Provided by session_client_like, used by protocol threads
336 client_connection_t *connection = user_data;
337
338 // Make the framework-created display context available to protocol threads
339 display_set_context(display);
340 connection->capture_context = capture_get_context();
341 connection->display_context = display;
342 connection->audio_context = audio_get_context();
343
344 // Get the render loop's should_exit callback for monitoring
345 bool (*render_should_exit)(void *) = session_client_like_get_render_should_exit();
346 if (!render_should_exit) {
347 return SET_ERRNO(ERROR_INVALID_STATE, "Render should_exit callback not initialized");
348 }
349
350 asciichat_error_t connection_result =
351 client_connection_start(connection, g_client_session.discovered_address ? g_client_session.discovered_address : "",
352 (uint16_t)(g_client_session.discovered_port > 0 ? g_client_session.discovered_port : 27224), g_client_session.password, sizeof(g_client_session.password));
353 if (connection_result != ASCIICHAT_OK) {
354 // Password prompt failures request shutdown but must retain their error.
355 if (should_exit() && connection_result != ERROR_CRYPTO_AUTH)
356 return ERROR_NETWORK;
357 LOG_ERRNO_IF_SET("Connection attempt failed");
358 return connection_result;
359 }
360
363
364 // Log connection status
365 if (!g_client_session.has_ever_connected) {
366 log_info("Connected");
367 g_client_session.has_ever_connected = true;
368 } else {
369 log_info("Reconnected");
370 }
371
372 // Monitor connection until it breaks or shutdown is requested
373 bool snapshot_check_logged_once = false;
374 uint64_t last_progress_log_ns = 0;
375 uint64_t advertised_revision = OPTIONS_REVISION_ANY;
376 asciichat_error_t settings_error = ASCIICHAT_OK;
377 while (!should_exit() && server_connection_is_active(connection)) {
378 display_poll_keyboard(connection);
379 terminal_size_t previous = connection->advertised_dimensions;
380 settings_error = session_protocol_update_settings(&connection->advertised_dimensions, &advertised_revision, client_send_settings, connection);
381 if (settings_error != ASCIICHAT_OK)
382 break;
383 if (previous.cols != connection->advertised_dimensions.cols || previous.rows != connection->advertised_dimensions.rows) {
386 }
387 if (client_protocol_connection_lost(connection)) {
388 log_debug("Connection lost detected");
389 break;
390 }
391
392 // Check if snapshot_delay timer has fired (in case frames stopped arriving)
393 // This is a safety check for when frame reception is sparse or stops entirely
394
395 bool snapshot_mode_enabled = GET_OPTION(snapshot_mode);
396
397 if (!snapshot_check_logged_once) {
398 log_info("CLIENT_MAIN_LOOP: snapshot_mode=%d first_frame_time=%llu snapshot_delay=%.1f", snapshot_mode_enabled, (unsigned long long)atomic_load_u64(&connection->snapshot_first_frame_time_ns),
399 GET_OPTION(snapshot_delay));
400 snapshot_check_logged_once = true;
401 }
402
403 if (snapshot_mode_enabled && atomic_load_u64(&connection->snapshot_first_frame_time_ns) > 0) {
404 uint64_t current_time_ns = time_get_ns();
405 double elapsed = time_ns_to_s(time_elapsed_ns(atomic_load_u64(&connection->snapshot_first_frame_time_ns), current_time_ns));
406 double snapshot_delay = GET_OPTION(snapshot_delay);
407
408 // Log progress every 500ms
409 if (current_time_ns - last_progress_log_ns > 500 * 1000 * 1000) {
410 log_debug("[MAIN_LOOP_SNAPSHOT_CHECK] elapsed=%.3f target=%.3f first_frame_ns=%llu current_ns=%llu", elapsed, snapshot_delay,
411 (unsigned long long)atomic_load_u64(&connection->snapshot_first_frame_time_ns), (unsigned long long)current_time_ns);
412 last_progress_log_ns = current_time_ns;
413 }
414
415 if (elapsed >= snapshot_delay) {
416 char duration_str[TIME_DURATION_BUFFER_SIZE];
417 time_pretty((uint64_t)(elapsed * 1e9), -1, duration_str, sizeof(duration_str));
418 log_info("🎬 SNAPSHOT TIMEOUT FIRED (IN_MAIN_LOOP): Snapshot captured after %s! (target=%.3f)", duration_str, snapshot_delay);
419 signal_exit();
420 break; // Exit loop, proper shutdown will follow
421 }
422 }
423
424 platform_sleep_us(100 * US_PER_MS_INT);
425 }
426
427 if (should_exit()) {
428 log_debug("Shutdown requested, cleaning up connection");
429 } else {
430 log_info("[ELSE_BRANCH] Connection lost path (should_exit=0, connection_active=0)");
431 // Connection lost - check if snapshot_delay timer has fired before exiting
432
433 if (GET_OPTION(snapshot_mode) && atomic_load_u64(&connection->snapshot_first_frame_time_ns) > 0) {
434 uint64_t current_time_ns = time_get_ns();
435 double elapsed = time_ns_to_s(time_elapsed_ns(atomic_load_u64(&connection->snapshot_first_frame_time_ns), current_time_ns));
436 double snapshot_delay = GET_OPTION(snapshot_delay);
437
438 log_info("[CONNECTION_LOSS_SNAPSHOT_CHECK] elapsed=%.3f target=%.3f (checking if timer fired)", elapsed, snapshot_delay);
439
440 if (elapsed >= snapshot_delay) {
441 char duration_str[TIME_DURATION_BUFFER_SIZE];
442 time_pretty((uint64_t)(elapsed * 1e9), -1, duration_str, sizeof(duration_str));
443 log_info("🎬 SNAPSHOT TIMEOUT FIRED (ON_CONNECTION_LOSS): Snapshot captured after %s! (target=%.3f)", duration_str, snapshot_delay);
444 signal_exit();
445 // Don't return yet, allow normal cleanup to proceed below
446 }
447 }
448
449 if (!should_exit()) {
450 splash_intro_start(display);
451 log_debug("Connection lost, preparing for reconnection attempt");
452 }
453 }
454
455 // A snapshot is complete once its first frame has been rendered. The peer
456 // may close the connection while the snapshot shutdown is propagating, but
457 // that is a successful snapshot rather than a reconnectable network error.
458
459 // The receive worker publishes the rejection before marking the connection lost.
460 asciichat_error_t remote_error = server_connection_get_remote_error(connection);
461 if (remote_error != ASCIICHAT_OK) {
462 // The receive worker already queued the peer notification. Keep the owner
463 // thread's failure context without presenting the same rejection twice.
464 bool previous = errno_notifications_suppress(true);
465 asciichat_error_t result = SET_ERRNO(remote_error, "Server rejected connection: %s", asciichat_error_string(remote_error));
467 return result;
468 }
469 if (settings_error != ASCIICHAT_OK)
470 return settings_error;
471 if (should_exit())
472 return ASCIICHAT_OK;
473 return ERROR_NETWORK;
474}
475
476/* Every attempt, including dialing/startup failure, leaves through this owner. */
477static asciichat_error_t client_run(session_capture_ctx_t *capture, session_display_ctx_t *display, void *user_data) {
478 (void)user_data;
479 const char *address = g_client_session.discovered_address;
480 if (!g_websocket_runtime && address && (strncmp(address, "ws://", 5) == 0 || strncmp(address, "wss://", 6) == 0)) {
481 asciichat_error_t runtime_result = acip_websocket_runtime_create(&g_websocket_runtime);
482 if (runtime_result != ASCIICHAT_OK)
483 return runtime_result;
484 }
485 client_connection_t *connection = NULL;
486 asciichat_error_t result = client_connection_create(&connection);
487 if (result != ASCIICHAT_OK) {
488 return result;
489 }
490 asciichat_errno_scope_t attempt_errors = errno_checkpoint();
491 result = client_run_attempt(capture, display, connection);
492 asciichat_error_t cleanup = client_connection_destroy(&connection);
493 while (cleanup != ASCIICHAT_OK) {
494 // Keep borrowed application devices and display alive until all users stop.
495 LOG_ERRNO_IF_SET("Waiting for connection workers before application cleanup");
496 platform_sleep_ms(100);
497 cleanup = client_connection_destroy(&connection);
498 }
499 if (should_exit() && result == ERROR_NETWORK) {
500 // Local cancellation can arrive while a remote disconnect is being cleaned up.
502 return ASCIICHAT_OK;
503 }
504 return result;
505}
506
507/* Runs once after splash startup, before capture/audio and the retry loop. */
508static asciichat_error_t client_select_destination(void *user_data) {
509 (void)user_data;
510 const options_t *opts = options_get();
511 if (!opts)
512 return SET_ERRNO(ERROR_INVALID_STATE, "Client options are unavailable during LAN discovery");
513 if (!opts->lan_discovery)
514 return ASCIICHAT_OK;
515 bool default_destination = strcmp(opts->address, OPT_ADDRESS_DEFAULT) == 0 && opts->port == OPT_PORT_INT_DEFAULT;
516 if (!default_destination)
517 return ASCIICHAT_OK;
518
519 ui_mdns_config_t config = {.timeout_ms = 2000, .max_servers = 20, .quiet = true};
520 int count = 0;
521 ui_mdns_server_t *servers = ui_mdns_query(&config, &count);
522 uint64_t deadline = ui_input_deadline(30);
523 ui_mdns_server_t selected;
524 int selection = ui_mdns_select_live(servers, count, deadline, &selected);
525 ui_mdns_free_results(servers);
526 if (selection < 0) {
527 return SET_ERRNO(ERROR_NETWORK, "LAN server selection cancelled");
528 }
529 static char selected_address[OPTIONS_BUFF_SIZE];
530 SAFE_STRNCPY(selected_address, ui_mdns_get_best_address(&selected), sizeof(selected_address));
531 asciichat_error_t result = options_set_string("address", selected_address);
532 if (result == ASCIICHAT_OK)
533 result = options_set_int("port", selected.port);
534 if (result != ASCIICHAT_OK) {
535 return result;
536 }
537 g_client_session.discovered_address = selected_address;
538 g_client_session.discovered_port = selected.port;
539 log_debug("LAN discovery: Selected server '%s' at %s:%d", selected.name, selected_address, g_client_session.discovered_port);
540 return ASCIICHAT_OK;
541}
542
543static int client_initialize_devices(void) {
544
545 // Initialize client-specific systems (NOT shared with session_client_like)
546 // This includes application devices and the application client context.
548 int init_result = initialize_client_systems();
549 if (init_result != 0) {
550#ifndef NDEBUG
551 // Debug builds: automatically fall back to test pattern if webcam is in use
552 if (init_result == ERROR_WEBCAM_IN_USE && !GET_OPTION(test_pattern)) {
553 log_warn("Webcam is in use - automatically falling back to test pattern mode (debug build only)");
554
555 // Enable test pattern mode via RCU update
556 asciichat_error_t update_result = options_set_bool("test_pattern", true);
557 if (update_result != ASCIICHAT_OK) {
558 log_error("Failed to update options for test pattern fallback");
559 FATAL(init_result, "%s", asciichat_error_string(init_result));
560 }
561
562 // Retry initialization with test pattern enabled
563 init_result = initialize_client_systems();
564 if (init_result != 0) {
565 log_error("Failed to initialize even with test pattern fallback");
566 webcam_print_init_error_help(init_result);
567 FATAL(init_result, "%s", asciichat_error_string(init_result));
568 }
569 log_debug("Successfully initialized with test pattern fallback");
570
571 // Clear the error state since we successfully recovered
573 ASSERT_NO_ERRNO_SINCE(init_scope);
574 } else
575#endif
576 {
577 // Release builds or other errors: print help and exit
578 if (init_result == ERROR_WEBCAM || init_result == ERROR_WEBCAM_IN_USE || init_result == ERROR_WEBCAM_PERMISSION) {
579 webcam_print_init_error_help(init_result);
580 FATAL(init_result, "%s", asciichat_error_string(init_result));
581 }
582 // For other errors, just exit with the error code
583 return init_result;
584 }
585 } else {
586 ASSERT_NO_ERRNO_SINCE(init_scope);
588 }
589
590 return 0;
591}
592
593static asciichat_error_t client_prepare_destination(void *user_data) {
594 asciichat_error_t result = client_select_destination(user_data);
595 if (result != ASCIICHAT_OK)
596 return result;
597 return (asciichat_error_t)client_initialize_devices();
598}
599
600int client_main(void) {
601 // Register cleanup function for graceful shutdown
602 (void)atexit(shutdown_client);
603
604 // Register client interrupt callback (socket shutdown on SIGTERM/Ctrl+C)
605 // Global signal handlers (SIGTERM, SIGPIPE, Ctrl+C) are set up in setup_signal_handlers() in src/main.c
606 set_interrupt_callback(NULL); // Signal handlers publish application exit only.
607
608 /* ========================================================================
609 * Client-Specific: LAN/Session Discovery
610 * ========================================================================
611 * This phase discovers the server to connect to via:
612 * - LAN discovery (mDNS)
613 * - Session string lookup (ACDS)
614 * - Direct address/port
615 */
616
617 // =========================================================================
618 // Client-Specific: Server Address Resolution
619 // =========================================================================
620 // Client mode supports:
621 // 1. Direct positional address/port - handled by options
622 // 2. Interactive default LAN discovery or --scan - prepared after splash startup
623 // 3. WebSocket URL (direct ws:// or wss:// connection string)
624 //
625 // Note: Session string discovery via ACDS is handled by discovery mode only.
626 // Client mode does NOT use ACDS or session strings.
627
628 const char *discovered_address = NULL;
629 int discovered_port = 0;
630
631 // Check if user provided a WebSocket URL as the server address
632 const options_t *opts_websocket = options_get();
633 const char *provided_address = opts_websocket && opts_websocket->address[0] != '\0' ? opts_websocket->address : NULL;
634
635 if (provided_address && url_looks_like_websocket(provided_address) && url_is_websocket(provided_address)) {
636 // Direct WebSocket connection
637 log_debug("Client: Direct WebSocket URL: %s", provided_address);
638 discovered_address = provided_address;
639 discovered_port = 0; // Port is embedded in the URL
640 }
641
642 if (discovered_port > 0) {
643 log_debug("Client: discovered_address=%s, discovered_port=%d", discovered_address ? discovered_address : "NULL", discovered_port);
644 } else {
645 log_debug("Client: discovered_address=%s", discovered_address ? discovered_address : "NULL");
646 }
647
648 // Store discovered address/port in session state for client_run() callback
649 static char address_storage[BUFFER_SIZE_SMALL];
650 if (discovered_address) {
651 SAFE_STRNCPY(address_storage, discovered_address, sizeof(address_storage));
652 g_client_session.discovered_address = address_storage;
653 g_client_session.discovered_port = discovered_port;
654 } else {
655 const options_t *opts_fallback = options_get();
656 if (opts_fallback && opts_fallback->address[0] != '\0') {
657 SAFE_STRNCPY(address_storage, opts_fallback->address, sizeof(address_storage));
658 g_client_session.discovered_address = address_storage;
659 g_client_session.discovered_port = opts_fallback->port;
660 } else {
661 g_client_session.discovered_address = "localhost";
662 g_client_session.discovered_port = 27224;
663 }
664 }
665
666 /* ========================================================================
667 * Configure and Run Shared Client-Like Session Framework
668 * ========================================================================
669 * session_client_like_run() handles all shared initialization:
670 * - Terminal output management (force stderr if piped)
671 * - Keepawake system (platform sleep prevention)
672 * - Splash screen lifecycle
673 * - Media source selection (webcam, file, URL, test pattern)
674 * - FPS probing for media files
675 * - Audio initialization and lifecycle
676 * - Display context creation
677 * - Proper cleanup ordering (critical for PortAudio)
678 *
679 * Client mode provides:
680 * - client_run() callback: connection loop, protocol startup, monitoring
681 * - client_should_reconnect() callback: reconnection policy
682 * - Reconnection configuration: attempts, delay, callbacks
683 */
684
685 // Get reconnect attempts setting (-1 = unlimited, 0 = no retry, >0 = retry N times)
686 int reconnect_attempts = GET_OPTION(reconnect_attempts);
687
688 // Configure session_client_like with client-specific settings
690 .run_fn = client_run,
691 .prepare_fn = client_prepare_destination,
692 .run_user_data = NULL,
694 .discovery = NULL,
695 .custom_should_exit = NULL,
696 .exit_user_data = NULL,
697 .keyboard_handler = NULL, // Client mode: server drives display
698 .max_reconnect_attempts = reconnect_attempts,
699 .should_reconnect_callback = client_should_reconnect,
700 .reconnect_user_data = NULL,
701 .reconnect_delay_ms = 1000, // 1 second delay between reconnection attempts
702 .print_newline_on_tty_exit = false, // Server/client manages cursor
703 };
704
705 log_debug("About to call session_client_like_run() with %d attempts", reconnect_attempts);
706 asciichat_error_t session_result = session_client_like_run(&config);
707 log_debug("session_client_like_run() returned %d", session_result);
708
709 // Cleanup session log buffer (used by splash screen in session_client_like)
710 // NOTE: session_log_buffer_destroy() is already called in session_client_like_run()
711 // during its cleanup phase, so we don't call it here to avoid double-destroy of mutex
712
713 log_debug("ascii-chat client shutting down");
714
715 // IMPORTANT: Stop worker threads and join them BEFORE memory report
716 // atexit(shutdown_client) won't run if interrupted by SIGTERM, so call explicitly
717 log_debug("About to call shutdown_client()");
718 fflush(stderr);
719 shutdown_client();
720 log_debug("shutdown_client() returned");
721 fflush(stderr);
722
723 // Cleanup remaining shared subsystems (buffer domain, platform, etc.)
724 log_debug("About to call asciichat_shared_destroy()");
726
727 // Log final session statistics before exit
728 // Note: Frame count is logged in client_connection_stop() if connection was established
729 // This is a fallback in case the connection never started
730 return session_result;
731}
ascii-chat Discovery Service (ACDS) Protocol Message Formats
ACIP client-side protocol library and ACDS client connection API.
int audio_analysis_init(void)
Measurements used to diagnose sent or received audio quality.
Definition analysis.c:113
void audio_analysis_print_report(void)
Print audio analysis report.
Definition analysis.c:522
void audio_analysis_destroy(void)
Cleanup audio analysis.
Definition analysis.c:839
Audio Analysis and Debugging Interface.
Application-level callbacks for library code.
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_checkpoint(void)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
Common buffer size definitions.
int capture_init()
Initialize capture subsystem.
void capture_cleanup()
Cleanup capture subsystem.
session_capture_ctx_t * capture_get_context(void)
ascii-chat Client Media Capture Management Interface
int client_main(void)
Client mode entry point for unified binary.
struct webrtc_peer_manager * g_peer_manager
Client connection session state for session_client_like integration.
ascii-chat Client Mode Entry Point Header
asciichat_error_t session_client_like_run(const session_client_like_config_t *config)
bool(*)(void *) session_client_like_get_render_should_exit(void)
Definition client_like.c:98
Shared initialization and teardown for client-like modes (mirror, client, discovery).
struct session_client_like_config session_client_like_config_t
@ SESSION_CLIENT_LIKE_KIND_CLIENT
Definition client_like.h:65
asciichat_error_t session_protocol_update_settings(terminal_size_t *advertised, uint64_t *advertised_revision, session_protocol_send_settings_fn send, void *context)
Platform initialization and static synchronization helpers.
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
void display_set_context(session_display_ctx_t *display_ctx)
Set the display context created by session_client_like framework.
void display_full_reset()
Perform full display reset.
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
void asciichat_shared_destroy(void)
Clean up all shared library subsystems.
Definition common.c:219
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ERROR_INVALID_PASSWORD
Definition error_codes.h:87
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_WEBCAM_IN_USE
Definition error_codes.h:64
@ ERROR_CRYPTO_VERIFICATION
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_SIGNATURE
Definition error_codes.h:88
@ ERROR_CRYPTO_AUTH
Definition error_codes.h:99
@ ERROR_WEBCAM_PERMISSION
Definition error_codes.h:65
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INTERNAL
Definition error_codes.h:91
@ ERROR_WEBCAM
Definition error_codes.h:63
void log_truncate_if_large(void)
Manually truncate large log files.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
void log_destroy(void)
Destroy the logging system and close log file.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_fatal(...)
Log a FATAL message.
Definition log/log.h:640
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
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
#define GET_OPTION(field)
Definition options.h:1333
asciichat_error_t options_set_int(const char *name, int value)
Check if an option was explicitly set via command-line.
Definition rcu.c:887
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
asciichat_error_t options_set_string(const char *name, const char *value)
Definition rcu.c:901
asciichat_error_t options_set_bool(const char *name, bool value)
Definition rcu.c:895
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
#define OPT_ADDRESS_DEFAULT
Default server address for client connections.
Definition options.h:536
struct session_display_ctx session_display_ctx_t
session display config is intentionally a small, concrete record. Fields such as snapshot_mode,...
int splash_intro_done(void)
Signal that intro splash should end (first frame ready to render).
Definition splash.c:421
int splash_intro_start(session_display_ctx_t *ctx)
Start animated intro screen with rainbow ASCII art (non-blocking).
Definition splash.c:370
struct session_capture_ctx session_capture_ctx_t
session capture config keeps the values that move through the subsystem: type, path,...
bool url_is_websocket(const char *url)
Check if a URL string is a valid WebSocket URL.
Definition url.c:325
bool url_looks_like_websocket(const char *url)
Quick check if a string is a WebSocket URL.
Definition url.c:340
void webcam_print_init_error_help(asciichat_error_t error_code)
Print helpful error diagnostics for webcam initialization failures.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 JSON structured logging output
ACIP client-side protocol API.
struct acip_websocket_runtime acip_websocket_runtime_t
🌍 IP Address Parsing and Formatting Utilities
asciichat_error_t acip_settings_send(acip_transport_t *transport, const options_t *values, uint32_t request, uint32_t expected_revision)
📝 Logging API with multiple log levels and terminal output control
void signal_exit(void)
Definition main.c:252
bool should_exit(void)
Definition main.c:248
void set_interrupt_callback(void(*cb)(void))
Definition main.c:272
Global application exit and signal handling API.
🌐 Core network I/O operations with timeout support
#define NOTICE(severity, title,...)
Definition notice.h:56
#define OPTIONS_REVISION_ANY
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
ASCII Palette Management for Video-to-ASCII Conversion.
Password prompting utilities with secure input and formatting.
📂 Path Manipulation Utilities
bool client_protocol_connection_lost(client_connection_t *connection)
Interactive search filtering for terminal screens.
Thread-safe circular log buffer for session screens (status, splash).
#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.
void audio_cleanup()
Cleanup audio subsystem.
int audio_client_init()
Initialize audio subsystem.
audio_context_t * audio_get_context(void)
Get the global audio context for use by other subsystems.
ascii-chat Client Audio Processing Management Interface
asciichat_error_t client_connection_destroy(client_connection_t **owner)
asciichat_error_t client_connection_start(client_connection_t *connection, const char *address, uint16_t port, char *password, size_t password_capacity)
asciichat_error_t client_connection_create(client_connection_t **out)
struct client_connection client_connection_t
void display_poll_keyboard(client_connection_t *connection)
ascii-chat Client Display Management Interface
bool server_connection_is_active(client_connection_t *connection)
Establish connection to ascii-chat server.
asciichat_error_t server_connection_get_remote_error(client_connection_t *connection)
acip_transport_t * server_connection_get_transport(client_connection_t *connection)
Get ACIP transport instance.
ascii-chat Client Server Connection Management Interface
void platform_disable_keepawake(void)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
atomic_t snapshot_first_frame_time_ns
session_capture_ctx_t * capture_context
session_display_ctx_t * display_context
terminal_size_t advertised_dimensions
audio_context_t * audio_context
Client connection session state for session_client_like integration.
char password[PASSWORD_BUFFER_SIZE]
const char * discovered_address
bool lan_discovery
Enable LAN service discovery via mDNS (client only).
Definition options.h:1044
int port
Server port number.
Definition options.h:1004
char address[256]
Server address (client) or bind address (server).
Definition options.h:1002
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...
Configuration for TUI discovery.
Definition tui/mdns.h:79
Discovered server information from mDNS.
Definition tui/mdns.h:66
char name[256]
Service instance name (e.g., "swift-river-canyon").
Definition tui/mdns.h:67
uint16_t port
Server port number.
Definition tui/mdns.h:70
For pending ice candidate, this is the live record that ties candidate, mid, next together....
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_title_activity(ui_title_activity_t activity)
void ui_controller_title_ready(void)
@ UI_TITLE_ACTIVITY_IDLE
uint64_t ui_input_deadline(unsigned seconds)
Definition tui/input.c:48
ui_mdns_server_t * ui_mdns_query(const ui_mdns_config_t *config, int *out_count)
TUI-based server selection with formatted display.
Definition tui/mdns.c:80
int ui_mdns_select_live(const ui_mdns_server_t *servers, int count, uint64_t deadline, ui_mdns_server_t *chosen)
Definition tui/mdns.c:409
void ui_mdns_free_results(ui_mdns_server_t *servers)
Free results from mDNS discovery.
Definition tui/mdns.c:100
const char * ui_mdns_get_best_address(const ui_mdns_server_t *server)
This is the handoff point for mdns refresh. Callers fill mutex, stop, thread, running before passing ...
Definition tui/mdns.c:429
mDNS service discovery UI with terminal_screen rendering
🌐 Production-Grade URL Validation and Parsing
asciichat_error_t acip_websocket_runtime_create(acip_websocket_runtime_t **out)
void acip_websocket_runtime_destroy(acip_websocket_runtime_t **runtime)