ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
main.h File Reference

ascii-chat Client Mode Entry Point Header More...

Go to the source code of this file.

Functions

int client_main (void)
 Client mode entry point for unified binary.

Variables

struct webrtc_peer_manager * g_peer_manager
 Global WebRTC peer manager for P2P connections.

Detailed Description

ascii-chat Client Mode Entry Point Header

This header exposes the client mode entry point for the unified binary architecture. The unified binary dispatches to client_main() when invoked as ascii-chat client.

Unified Binary Architecture

The ascii-chat application uses a single binary with multiple operating modes:

  • ascii-chat server - Run as server (multi-client connection manager)
  • ascii-chat client - Run as client (connects to server, streams video/audio)

This design provides several benefits:

  • Simplified distribution (single binary to install)
  • Reduced disk space (shared library code)
  • Easier testing (one binary to build and deploy)
  • Consistent versioning across modes

Mode Entry Point Contract

Each mode entry point (server_main, client_main) must:

  • Accept no arguments: int mode_main(void)
  • Options are already parsed by main dispatcher (available via global opt_* variables)
  • Return 0 on success, non-zero error code on failure
  • Perform mode-specific initialization and main loop
  • Perform complete cleanup before returning

Implementation Notes

The client_main() function is the original main() from src/client/main.c, adapted to the new dispatcher pattern. Common initialization (options parsing, logging setup, lock debugging, –show-capabilities) now happens in src/main.c before dispatch.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
2025
Version
2.0

Definition in file client/main.h.

Function Documentation

◆ client_main()

int client_main ( void )

Client mode entry point for unified binary.

This function implements the complete client lifecycle including:

  • Client-specific subsystem initialization (display, capture, audio)
  • Server connection establishment with exponential backoff reconnection
  • Main event loop coordinating connection state and thread lifecycle
  • Media streaming (webcam frames and optional audio)
  • Frame display to terminal
  • Graceful shutdown and resource cleanup

Lifecycle Overview

The client follows this high-level state flow:

  1. Initialize: Set up display, capture, audio subsystems
  2. Connect Loop:
    • Establish TCP connection to server
    • Perform cryptographic handshake
    • Spawn worker threads (data reception, capture, keepalive, audio)
    • Monitor connection health
    • Detect connection loss via thread exit or socket errors
  3. Cleanup: Stop threads, close socket, reset terminal
  4. Reconnect: Exponential backoff, retry (unless fatal auth error)
  5. Exit: On user signal (SIGINT) or fatal error

Connection Failure Handling

Transient Errors (retryable):

  • Connection refused, timeout, DNS failure → exponential backoff retry
  • Network temporarily unavailable → wait and retry

Fatal Errors (no retry):

Thread Management

The client spawns several worker threads coordinated by the main thread:

  • Data Reception Thread: Receives and processes server packets
  • Webcam Capture Thread: Captures frames, transmits to server
  • Ping/Keepalive Thread: Sends periodic pings, detects timeouts
  • Audio Threads (optional): Captures/plays audio with Opus encoding

All threads check the global g_should_exit flag and exit cleanly on shutdown. Main thread waits for all threads to exit before reconnection or final cleanup.

Options

Options are already parsed by the main dispatcher (src/main.c) before this function is called. They are available via the global options API (GET_OPTION, etc.).

Key options affecting behavior:

  • opt_address: Server address or session string
  • opt_port: Server port (default 27224)
  • opt_audio_enabled: Enable audio capture/playback
  • opt_snapshot: Capture single frame and exit
  • opt_client_key, opt_server_key: SSH keys for authentication
Returns
Exit code:
  • 0: Success (clean exit or snapshot completed)
  • 1: Initialization/configuration error
  • 2: Connection fatal error (auth failed)
  • 130: Signal interrupt (SIGINT/Ctrl+C)
Example
# Invoked by dispatcher after options are parsed:
ascii-chat client --address localhost --audio
# Dispatcher (src/main.c) handles:
# - Option parsing
# - Log initialization
# - Signal handler setup
# Then calls client_main() which handles:
# - Subsystem init (display, capture, audio)
# - Connection loop with reconnection logic
# - Thread coordination
# - Graceful shutdown
See also
topic_client "Client Architecture Overview"
topic_client_main "Client Lifecycle Details"
topic_client_connection "Connection Management"
topic_client_protocol "Packet Processing"

Definition at line 600 of file client/main.c.

600 {
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}
asciichat_error_t session_client_like_run(const session_client_like_config_t *config)
struct session_client_like_config session_client_like_config_t
@ SESSION_CLIENT_LIKE_KIND_CLIENT
Definition client_like.h:65
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_STRNCPY(dst, src, size)
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
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define GET_OPTION(field)
Definition options.h:1333
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
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 set_interrupt_callback(void(*cb)(void))
Definition main.c:272
int port
Server port number.
Definition options.h:1004
char address[256]
Server address (client) or bind address (server).
Definition options.h:1002

References options_state::address, asciichat_shared_destroy(), BUFFER_SIZE_SMALL, GET_OPTION, log_debug, options_get(), options_state::port, SAFE_STRNCPY, SESSION_CLIENT_LIKE_KIND_CLIENT, session_client_like_run(), set_interrupt_callback(), url_is_websocket(), and url_looks_like_websocket().

Variable Documentation

◆ g_peer_manager

struct webrtc_peer_manager* g_peer_manager
extern

Global WebRTC peer manager for P2P connections.

Manages WebRTC peer connections for ACDS session participants. Handles SDP/ICE exchange and DataChannel lifecycle for P2P ACIP transport.

NULL if WebRTC not initialized (TCP-only mode). Initialized when joining/creating ACDS sessions with WebRTC transport.

Global WebRTC peer manager for P2P connections.

Global WebRTC peer manager (legacy compatibility)

Client mode no longer uses WebRTC, but protocol.c still references this. Always NULL in client mode.

Definition at line 147 of file client/main.c.