ascii-chat 0.6.0
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
Options Module

⚙️ The command-line flags available More...

Files

file  acds.c
 ACDS mode option parsing and help text.
 
file  acds.h
 ACDS (Discovery Service) mode option parsing.
 
file  actions.c
 Action option callbacks for ascii-chat.
 
file  actions.h
 Action option callbacks for ascii-chat.
 
file  builder.c
 Implementation of options builder API.
 
file  builder.h
 Options builder API for flexible command-line option configuration.
 
file  client.c
 Client mode option parsing and help text.
 
file  client.h
 Client mode option parsing.
 
file  common.c
 Common utilities and helpers for option parsing.
 
file  common.h
 Common utilities and helpers for option parsing.
 
file  levenshtein.h
 Levenshtein distance algorithm for fuzzy string matching.
 
file  mirror.c
 Mirror mode option parsing and help text.
 
file  mirror.h
 Mirror mode option parsing.
 
file  options.c
 ⚙️ Unified command-line argument parser with built-in mode detection
 
file  options.h
 ⚙️ Command-line options parsing and configuration management for ascii-chat
 
file  parsers.c
 Custom option parsers implementation.
 
file  parsers.h
 Custom option parsers for enum types.
 
file  presets.c
 Preset option configurations for ascii-chat modes.
 
file  server.c
 Server mode option parsing and help text.
 
file  server.h
 Server mode option parsing.
 
file  validation.h
 Validation functions for options parsing.
 

Data Structures

struct  options_state
 Consolidated options structure. More...
 

Macros

#define LEVENSHTEIN_SUGGESTION_THRESHOLD   3
 Maximum edit distance to suggest an option.
 
#define COLOR_MODE_AUTO   TERM_COLOR_AUTO
 Backward compatibility aliases for color mode enum values.
 
#define COLOR_MODE_NONE   TERM_COLOR_NONE
 Monochrome mode.
 
#define COLOR_MODE_16   TERM_COLOR_16
 16-color mode (alias)
 
#define COLOR_MODE_16_COLOR   TERM_COLOR_16
 16-color mode (full name)
 
#define COLOR_MODE_256   TERM_COLOR_256
 256-color mode (alias)
 
#define COLOR_MODE_256_COLOR   TERM_COLOR_256
 256-color mode (full name)
 
#define COLOR_MODE_TRUECOLOR   TERM_COLOR_TRUECOLOR
 24-bit truecolor mode
 
#define ASCIICHAT_BINARY_OPTIONS_STRUCT
 Binary-level options (parsed before mode selection)
 
#define ASCIICHAT_COMMON_OPTIONS_STRUCT
 Common options (all modes after binary parsing)
 
#define ASCIICHAT_SERVER_OPTIONS_STRUCT
 Server mode options.
 
#define ASCIICHAT_CLIENT_OPTIONS_STRUCT
 Client mode options.
 
#define ASCIICHAT_MIRROR_OPTIONS_STRUCT
 Mirror mode options.
 
#define ASCIICHAT_ACDS_OPTIONS_STRUCT
 ACDS mode options.
 
#define GET_OPTION(field)
 Safely get a specific option field (lock-free read)
 

Typedefs

typedef struct options_state options_t
 Consolidated options structure.
 

Enumerations

enum  asciichat_mode_t { MODE_SERVER , MODE_CLIENT , MODE_MIRROR , MODE_ACDS }
 Mode type for options parsing. More...
 

Functions

ASCIICHAT_API size_t levenshtein (const char *a, const char *b)
 Calculate Levenshtein distance between two strings.
 
ASCIICHAT_API size_t levenshtein_n (const char *a, const size_t length, const char *b, const size_t bLength)
 Calculate Levenshtein distance with explicit string lengths.
 
ASCIICHAT_API const char * levenshtein_find_similar (const char *unknown, const char *const *candidates)
 Find the most similar string from a NULL-terminated array.
 
const options_toptions_get (void)
 Get current options (lock-free read)
 
asciichat_error_t options_update (void(*updater)(options_t *, void *), void *context)
 Update options using copy-on-write (thread-safe)
 
asciichat_error_t options_set_dimensions (unsigned short int width, unsigned short int height)
 Update terminal dimensions.
 
asciichat_error_t options_set_color_mode (terminal_color_mode_t mode)
 Update color mode.
 
asciichat_error_t options_set_render_mode (render_mode_t mode)
 Update render mode.
 
asciichat_error_t options_set_log_level (log_level_t level)
 Update log level.
 

Variables

ASCIICHAT_API int opt_acds_port
 TCP listen port (ACDS mode only)
 
ASCIICHAT_API char opt_acds_database_path [OPTIONS_BUFF_SIZE]
 SQLite database path (ACDS mode only)
 
ASCIICHAT_API char opt_acds_key_path [OPTIONS_BUFF_SIZE]
 Ed25519 identity key path (ACDS mode only)
 
const float weight_red
 
const float weight_green
 Green weight for luminance calculation.
 
const float weight_blue
 Blue weight for luminance calculation.
 
unsigned short int RED []
 Red channel lookup table.
 
unsigned short int GREEN []
 Green channel lookup table.
 
unsigned short int BLUE []
 Blue channel lookup table.
 
unsigned short int GRAY []
 Grayscale lookup table.
 

Utility Functions

int strtoint_safe (const char *str)
 Safely parse string to integer with validation.
 

Option Parsing Functions

asciichat_error_t options_init (int argc, char **argv)
 Initialize options by parsing command-line arguments.
 
void usage (FILE *desc, asciichat_mode_t mode)
 Print usage information for client, server, or mirror mode.
 
void usage_client (FILE *desc)
 Print client usage information.
 
void usage_server (FILE *desc)
 Print server usage information.
 
void usage_mirror (FILE *desc)
 Print mirror usage information.
 
void usage_acds (FILE *desc)
 Print ACDS usage information.
 

Dimension Update Functions

void update_dimensions_for_full_height (options_t *opts)
 Update dimensions for full height display.
 
void update_dimensions_to_terminal_size (options_t *opts)
 Update dimensions to match terminal size.
 

Validation Functions

ASCIICHAT_API int validate_opt_port (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate port number (1-65535)
 
ASCIICHAT_API int validate_opt_positive_int (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate positive integer.
 
ASCIICHAT_API int validate_opt_non_negative_int (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate non-negative integer.
 
ASCIICHAT_API int validate_opt_color_mode (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate color mode string.
 
ASCIICHAT_API int validate_opt_render_mode (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate render mode string.
 
ASCIICHAT_API int validate_opt_palette (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate palette type string.
 
ASCIICHAT_API int validate_opt_log_level (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate log level string.
 
ASCIICHAT_API int validate_opt_ip_address (const char *value_str, char *parsed_address, size_t address_size, bool is_client, char *error_msg, size_t error_msg_size)
 Validate IP address or hostname.
 
ASCIICHAT_API float validate_opt_float_non_negative (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate non-negative float value.
 
ASCIICHAT_API int validate_opt_fps (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate FPS value (1-144)
 
ASCIICHAT_API int validate_opt_max_clients (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate max clients value (1-32)
 
ASCIICHAT_API int validate_opt_compression_level (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate compression level (1-9)
 
ASCIICHAT_API int validate_opt_reconnect (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate reconnect value.
 
ASCIICHAT_API int validate_opt_device_index (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate device index (-1 for default, 0+ for specific device)
 
ASCIICHAT_API int validate_opt_password (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate password (8-256 characters)
 

Configuration Constants

#define OPTIONS_BUFF_SIZE   256
 Buffer size for option string values.
 
#define OPT_WIDTH_DEFAULT   110
 Default terminal width in characters.
 
#define OPT_HEIGHT_DEFAULT   70
 Default terminal height in characters.
 
#define SNAPSHOT_DELAY_DEFAULT   3.0f
 Default snapshot delay in seconds.
 
#define OPT_PORT_DEFAULT   "27224"
 Default TCP port for client/server communication.
 
#define OPT_ADDRESS_DEFAULT   "localhost"
 Default server address for client connections.
 
#define OPT_ADDRESS6_DEFAULT   "::1"
 Default IPv6 server address.
 
#define OPT_MAX_CLIENTS_DEFAULT   9
 Default maximum concurrent clients (server only)
 
#define OPT_COMPRESSION_LEVEL_DEFAULT   1
 Default compression level (1-9)
 
#define OPT_FPS_DEFAULT   60
 Default FPS (frames per second)
 
#define OPT_WEBCAM_INDEX_DEFAULT   0
 Default webcam device index.
 
#define OPT_MICROPHONE_INDEX_DEFAULT   (-1)
 Default microphone device index (-1 means system default)
 
#define OPT_SPEAKERS_INDEX_DEFAULT   (-1)
 Default speakers device index (-1 means system default)
 
#define OPT_RECONNECT_ATTEMPTS_DEFAULT   (-1)
 Default reconnect attempts (-1 means auto/infinite)
 
#define OPT_WEBCAM_FLIP_DEFAULT   true
 Default webcam flip state (true = horizontally flipped)
 
#define OPT_COLOR_MODE_DEFAULT   COLOR_MODE_AUTO
 Default color mode (auto-detect terminal capabilities)
 
#define OPT_RENDER_MODE_DEFAULT   RENDER_MODE_FOREGROUND
 Default render mode (foreground characters only)
 
#define OPT_ENCODE_AUDIO_DEFAULT   true
 Default audio encoding state (true = Opus encoding enabled)
 

Detailed Description

⚙️ The command-line flags available

MIT licensed. Copyright (c) 2015 Titus Wormer titus.nosp@m.worm.nosp@m.er@gm.nosp@m.ail..nosp@m.com From: https://github.com/wooorm/levenshtein.c

This header provides comprehensive functionality for parsing command-line arguments and managing configuration settings for both client and server modes of ascii-chat. It serves as the central configuration system, parsing user preferences and providing defaults for all application settings.

Design Philosophy:

The options system follows a global configuration pattern where all options are stored in global variables that can be accessed throughout the application. This design:

Option Categories:

Options are organized into logical categories:

Option Parsing:

Options are parsed using the standard POSIX getopt() interface (with Windows compatibility via platform/windows/getopt.h). The parser:

Default Values:

All options have sensible defaults that work out-of-the-box:

Option Lifecycle:

  1. Initialization: Call options_init() at program startup
  2. Parsing: options_init() parses command-line arguments
  3. Validation: Options are validated and defaults applied
  4. Usage: Access option values via global variables throughout the application
  5. Updates: Some options can be updated dynamically (e.g., terminal dimensions)

Usage Example:

#include "options.h"
int main(int argc, char **argv) {
// Parse command-line options
asciichat_error_t err = options_init(argc, argv, true); // is_client = true
if (err != ASCIICHAT_OK) {
if (err == ERROR_USAGE) {
usage(stderr, true); // Print usage and exit
}
return 1;
}
// Access parsed options
printf("Connecting to %s:%s\n", opt_address, opt_port);
printf("Terminal size: %dx%d\n", opt_width, opt_height);
printf("Encryption enabled\n");
}
// Use options throughout application
// ...
return 0;
}
int main(int argc, char **argv)
Definition acds/main.c:55
asciichat_error_t
Error and exit codes - unified status values (0-255)
Definition error_codes.h:46
@ ASCIICHAT_OK
Definition error_codes.h:48
@ ERROR_USAGE
Definition error_codes.h:50
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments.
Definition options.c:144
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for client, server, or mirror mode.
ASCIICHAT_API char opt_address[OPTIONS_BUFF_SIZE]
ASCIICHAT_API unsigned short int opt_encrypt_enabled
ASCIICHAT_API unsigned short int opt_height
ASCIICHAT_API char opt_port[OPTIONS_BUFF_SIZE]
ASCIICHAT_API unsigned short int opt_width
⚙️ Command-line options parsing and configuration management for ascii-chat

Command-Line Options:

Common options (see usage() function for complete list):

Client address syntax (positional argument, not option flag):

Thread Safety:

Options are parsed once at startup in the main thread before any worker threads are created. After parsing, options are effectively read-only (with some exceptions for dynamic updates like terminal dimensions). Therefore, thread safety is not a concern for most options. If options need to be modified at runtime, ensure proper synchronization.

Option Validation:

The parser validates:

Invalid options result in ERROR_USAGE being returned, and usage information is printed to help the user correct their command line.

Note
All options are stored as global variables. This is intentional for simplicity.
Options are parsed once at startup via options_init().
Most options remain constant after parsing (read-only).
Some options (e.g., terminal dimensions) can be updated dynamically.
See also
options_init() for option parsing
usage() for usage information
platform/terminal.h for terminal capability detection
palette.h for Character Palettes configuration
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

This header provides validation functions used during command-line option parsing and configuration file loading. These functions validate user input and provide detailed error messages for invalid values.

All validation functions follow a consistent pattern:

Note
These functions are used by both options.c and config.c

Options README

Overview

The Options system provides command-line argument parsing support for ascii-chat. It handles server and client options, validates settings, and manages application configuration.

Implementation: lib/options.h, lib/config.h

Key Features:

  • Command-line argument parsing with getopt
  • Server and client mode options
  • Automatic help generation
  • Configuration validation
  • Default value management

Operation Modes

Server Mode:

./ascii-chat server [options]

Client Mode:

./ascii-chat client [options]

Common Options

Network Options:

  • [address][:port] (positional for client) - Server address with optional port (default: localhost:27224)
  • [address1] [address2] (positional for server) - Bind addresses, 0-2 IPv4/IPv6 addresses
  • --port PORT - Server port (default: 27224)

Display Options:

  • --width WIDTH - Terminal width (default: auto-detect)
  • --height HEIGHT - Terminal height (default: auto-detect)
  • --color - Enable color output
  • --stretch - Stretch video to fill terminal
  • --half-block - Use half-block rendering (2x vertical resolution)

Video Options:

  • --webcam INDEX - Webcam device index (default: 0)
  • --webcam-flip - Flip webcam horizontally
  • --test-pattern - Use test pattern instead of webcam
  • --snapshot - Capture single frame and exit
  • --snapshot-delay SEC - Delay before snapshot (default: 1.0)

Audio Options:

  • --audio - Enable audio (client only, server always has audio)
  • --no-audio - Disable audio

Crypto Options:

  • --key PATH - SSH private key for authentication
  • --server-key KEY - Server public key or github:username
  • --password PASS - Shared password for encryption
  • --insecure - Skip host identity verification (NOT RECOMMENDED)
  • --client-keys KEYS - Whitelist of allowed client keys (comma-separated)

Logging Options:

  • --log-file PATH - Write logs to file
  • --log-level LEVEL - Set log level (0-4)

Configuration Options:

  • --config PATH - Load configuration from TOML file
  • --config-create [PATH] - Create default config file and exit

Usage Examples

Server Examples

Basic Server:

./ascii-chat server

Server with Authentication:

./ascii-chat server --key ~/.ssh/id_ed25519 --client-keys github:user1,github:user2

Server with Custom Port:

./ascii-chat server --port 8080

Server with Logging:

./ascii-chat server --log-file /var/log/ascii-chat.log --log-level 1

Client Examples

Basic Client:

./ascii-chat client

Connect to Remote Server:

./ascii-chat client 192.168.1.100:27224

Client with Audio and Color:

./ascii-chat client --audio --color

Client with Custom Webcam:

./ascii-chat client --webcam 1 --webcam-flip

Snapshot Mode:

./ascii-chat client --snapshot --snapshot-delay 5

Client with Server Verification:

./ascii-chat client --server-key github:zfogg

Programmatic API

Parse Options:

options_t opts;
asciichat_error_t err = parse_options(argc, argv, &opts);
if (err != ASCIICHAT_OK) {
return err;
}
Consolidated options structure.
Definition options.h:439

Error Handling:

asciichat_error_t err = parse_options(argc, argv, &opts);
if (err != ASCIICHAT_OK) {
if (HAS_ERRNO(&ctx)) {
log_error("Invalid options: %s", ctx.context_message);
}
return err;
}
#define HAS_ERRNO(var)
Check if an error occurred and get full context.
#define log_error(...)
Log an ERROR message.
Error context structure.
char * context_message
Optional custom message (dynamically allocated, owned by system)

Help System

Show Help:

./ascii-chat --help
./ascii-chat server --help
./ascii-chat client --help

Help Output:

  • Lists all available options
  • Shows default values
  • Provides usage examples
  • Displays mode-specific options
See also
Configuration for configuration files and precedence
options.h
config.h

Macro Definition Documentation

◆ ASCIICHAT_ACDS_OPTIONS_STRUCT

#define ASCIICHAT_ACDS_OPTIONS_STRUCT

#include <options.h>

Value:
ASCIICHAT_COMMON_OPTIONS_STRUCT \
char address[OPTIONS_BUFF_SIZE]; \
char port[OPTIONS_BUFF_SIZE]; \
unsigned short int require_server_identity; \
unsigned short int require_client_identity; \
unsigned short int require_server_verify; \
unsigned short int require_client_verify; \
char stun_servers[OPTIONS_BUFF_SIZE]; \
char turn_servers[OPTIONS_BUFF_SIZE]; \
char turn_username[OPTIONS_BUFF_SIZE]; \
char turn_credential[OPTIONS_BUFF_SIZE]; \
char turn_secret[OPTIONS_BUFF_SIZE];
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:176

ACDS mode options.

Complete set of options for ACDS (discovery service) mode.

Definition at line 407 of file options.h.

425 {
429 MODE_ACDS
431
438typedef struct options_state {
439 // ============================================================================
440 // Mode Detection (auto-detected during options_init)
441 // ============================================================================
443
444 // ============================================================================
445 // Binary-Level Options (parsed first, before mode selection)
446 // ============================================================================
447 bool help;
448 bool version;
449
450 // ============================================================================
451 // Terminal Dimensions
452 // ============================================================================
453 unsigned short int width;
454 unsigned short int height;
455 bool auto_width;
456 bool auto_height;
457
458 // ============================================================================
459 // Network Options
460 // ============================================================================
463 char port[OPTIONS_BUFF_SIZE];
464 int max_clients;
465 char session_string[64];
466
467 // ============================================================================
468 // ACDS Discovery Options (server only)
469 // ============================================================================
470 bool acds;
472 int acds_port;
473 bool webrtc;
476
477 // ============================================================================
478 // LAN Discovery Options
479 // ============================================================================
480 bool lan_discovery;
481 bool no_mdns_advertise;
482
483 // ============================================================================
484 // Network Performance Options
485 // ============================================================================
487 bool no_compress;
488 bool encode_audio;
489
490 // ============================================================================
491 // Client Reconnection Options
492 // ============================================================================
494
495 // ============================================================================
496 // Webcam Options
497 // ============================================================================
498 unsigned short int webcam_index;
499 bool webcam_flip;
500 bool test_pattern;
501 bool no_audio_mixer;
502
503 // ============================================================================
504 // Display Options
505 // ============================================================================
508 unsigned short int show_capabilities;
509 unsigned short int force_utf8;
510 int fps;
511
512 // ============================================================================
513 // Audio Configuration
514 // ============================================================================
515 unsigned short int audio_enabled;
516 int microphone_index;
517 int speakers_index;
518 unsigned short int audio_analysis_enabled;
519 unsigned short int audio_no_playback;
520
521 // ============================================================================
522 // Image Options
523 // ============================================================================
524 unsigned short int stretch;
525
526 // ============================================================================
527 // Output Options
528 // ============================================================================
529 unsigned short int quiet;
530 unsigned short int verbose_level;
531 unsigned short int snapshot_mode;
532 double snapshot_delay;
533 unsigned short int strip_ansi;
536
537 // ============================================================================
538 // Encryption Options
539 // ============================================================================
540 unsigned short int encrypt_enabled;
544 unsigned short int no_encrypt;
547
548 // ============================================================================
549 // Identity Verification Options (ACDS + Crypto Handshake)
550 // ============================================================================
555 bool acds_expose_ip;
556 bool acds_insecure;
557
558 // ============================================================================
559 // WebRTC Connection Strategy Options (client-side fallback control)
560 // ============================================================================
561 bool prefer_webrtc;
562 bool no_webrtc;
563 bool webrtc_skip_stun;
565
566 // ============================================================================
567 // WebRTC Connectivity Options (ACDS mode only)
568 // ============================================================================
569 bool enable_upnp;
570 bool no_upnp;
576
577 // ============================================================================
578 // Palette Configuration
579 // ============================================================================
581 char palette_custom[256];
582 bool palette_custom_set;
583
584 // Note: Luminance weights (weight_red, weight_green, weight_blue) and
585 // lookup tables (RED[], GREEN[], BLUE[], GRAY[]) are kept as globals
586 // since they're precomputed constants, not user-configurable options.
587} options_t;
588
589// ============================================================================
590// RCU-based thread-safe options access
591// ============================================================================
592
603const options_t *options_get(void);
604
643#define GET_OPTION(field) \
644 ({ \
645 const options_t *_opts = options_get(); \
646 if (!_opts) { \
647 log_warn("GET_OPTION(" #field ") called but options not initialized"); \
648 } \
649 static typeof(((options_t *)0)->field) _default = {0}; \
650 (_opts ? (_opts->field) : _default); \
651 })
652
667asciichat_error_t options_update(void (*updater)(options_t *, void *), void *context);
668
678asciichat_error_t options_set_dimensions(unsigned short int width, unsigned short int height);
679
689
699
709
717static inline unsigned short int options_get_width(void) {
718 return options_get()->width;
719}
720
728static inline unsigned short int options_get_height(void) {
729 return options_get()->height;
730}
731
732extern const float weight_red;
733
742extern const float weight_green;
743
752extern const float weight_blue;
753
768extern unsigned short int RED[];
769
776extern unsigned short int GREEN[];
777
784extern unsigned short int BLUE[];
785
793extern unsigned short int GRAY[];
794
906asciichat_error_t options_init(int argc, char **argv);
907
943void usage(FILE *desc, asciichat_mode_t mode);
944
963void usage_client(FILE *desc);
964
981void usage_server(FILE *desc);
982
998void usage_mirror(FILE *desc);
999
1016void usage_acds(FILE *desc);
1017
1052
1083
log_level_t
Logging levels enumeration.
Definition log/logging.h:59
void usage_mirror(FILE *desc)
Print mirror usage information.
Definition mirror.c:71
unsigned short int GRAY[]
Grayscale lookup table.
void usage_client(FILE *desc)
Print client usage information.
unsigned short int BLUE[]
Blue channel lookup table.
asciichat_mode_t
Mode type for options parsing.
Definition options.h:426
struct options_state options_t
Consolidated options structure.
void usage_server(FILE *desc)
Print server usage information.
void update_dimensions_to_terminal_size(options_t *opts)
Update dimensions to match terminal size.
const float weight_blue
Blue weight for luminance calculation.
asciichat_error_t options_set_dimensions(unsigned short int width, unsigned short int height)
Update terminal dimensions.
Definition rcu.c:294
asciichat_error_t options_set_color_mode(terminal_color_mode_t mode)
Update color mode.
Definition rcu.c:304
const options_t * options_get(void)
Get current options (lock-free read)
Definition rcu.c:222
const float weight_red
asciichat_error_t options_set_log_level(log_level_t level)
Update log level.
Definition rcu.c:322
void usage_acds(FILE *desc)
Print ACDS usage information.
Definition acds.c:109
asciichat_error_t options_set_render_mode(render_mode_t mode)
Update render mode.
Definition rcu.c:313
unsigned short int GREEN[]
Green channel lookup table.
const float weight_green
Green weight for luminance calculation.
asciichat_error_t options_update(void(*updater)(options_t *, void *), void *context)
Update options using copy-on-write (thread-safe)
Definition rcu.c:237
unsigned short int RED[]
Red channel lookup table.
void update_dimensions_for_full_height(options_t *opts)
Update dimensions for full height display.
@ MODE_CLIENT
Client mode - network client options.
Definition options.h:428
@ MODE_ACDS
Discovery service mode - session management and WebRTC signaling.
Definition options.h:430
@ MODE_SERVER
Server mode - network server options.
Definition options.h:427
@ MODE_MIRROR
Mirror mode - local webcam viewing (no network)
Definition options.h:429
palette_type_t
Built-in palette type enumeration.
Definition palette.h:84
render_mode_t
Render mode preferences.
Definition terminal.h:467
terminal_color_mode_t
Terminal color support levels.
Definition terminal.h:424
bool acds_insecure
ACDS: skip server key verification (MITM-vulnerable, requires explicit opt-in)
Definition options.h:557
bool webrtc
Enable WebRTC mode for ACDS session (default: false, Direct TCP)
Definition options.h:474
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor)
Definition options.h:507
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:573
char port[256]
Server port number.
Definition options.h:464
bool acds_expose_ip
ACDS: explicitly allow public IP disclosure without verification (opt-in)
Definition options.h:556
int compression_level
zstd compression level (1-9)
Definition options.h:487
char acds_key_path[256]
ACDS identity key file path (default: ~/.ascii-chat/acds_identity)
Definition options.h:475
unsigned short int no_encrypt
Disable encryption (opt-out)
Definition options.h:545
bool no_mdns_advertise
Disable mDNS service advertisement (server only)
Definition options.h:482
char password[256]
Password string.
Definition options.h:543
int microphone_index
Microphone device index (-1 = default)
Definition options.h:517
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:443
bool no_upnp
ACDS: Explicitly disable UPnP/NAT-PMP port mapping.
Definition options.h:571
char stun_servers[256]
ACDS: Comma-separated list of STUN server URLs.
Definition options.h:572
bool enable_upnp
ACDS: Enable UPnP/NAT-PMP port mapping for direct TCP.
Definition options.h:570
bool webrtc_skip_stun
–webrtc-skip-stun: Skip Stage 2 (STUN), go to TURN
Definition options.h:564
unsigned short int force_utf8
Force UTF-8 support.
Definition options.h:510
bool lan_discovery
Enable LAN service discovery via mDNS (client only)
Definition options.h:481
unsigned short int quiet
Quiet mode (suppress logs)
Definition options.h:530
bool no_webrtc
–no-webrtc: Disable WebRTC, use Direct TCP only
Definition options.h:563
unsigned short int encrypt_enabled
Enable encryption.
Definition options.h:541
unsigned short int webcam_index
Webcam device index (0 = first)
Definition options.h:499
bool webrtc_disable_turn
–webrtc-disable-turn: Disable Stage 3 (TURN), use STUN only
Definition options.h:565
char acds_server[256]
ACDS server address (default: 127.0.0.1)
Definition options.h:472
char session_string[64]
Session string for ACDS discovery (client only)
Definition options.h:466
unsigned short int width
Terminal width in characters.
Definition options.h:454
bool auto_height
Auto-detect height from terminal.
Definition options.h:457
log_level_t log_level
Log level threshold.
Definition options.h:536
char turn_credential[256]
ACDS: Credential/password for TURN authentication.
Definition options.h:575
bool require_server_identity
ACDS: require servers to provide signed Ed25519 identity.
Definition options.h:552
char palette_custom[256]
Custom palette characters.
Definition options.h:582
unsigned short int height
Terminal height in characters.
Definition options.h:455
char acds_database_path[256]
ACDS database file path (default: ~/.ascii-chat/acds.db)
Definition options.h:476
int max_clients
Maximum concurrent clients (server only)
Definition options.h:465
bool palette_custom_set
True if custom palette was set.
Definition options.h:583
render_mode_t render_mode
Render mode (foreground/background/half-block)
Definition options.h:508
unsigned short int audio_no_playback
Disable speaker playback (debug)
Definition options.h:520
char server_key[256]
Expected server public key (client)
Definition options.h:546
unsigned short int show_capabilities
Show terminal capabilities and exit.
Definition options.h:509
bool no_audio_mixer
Disable audio mixer (debug)
Definition options.h:502
char encrypt_keyfile[256]
Alternative key file path.
Definition options.h:544
bool version
Show version information.
Definition options.h:449
int acds_port
ACDS server port (default: 27225)
Definition options.h:473
bool no_compress
Disable compression entirely.
Definition options.h:488
char address6[256]
IPv6 bind address (server only)
Definition options.h:463
int speakers_index
Speakers device index (-1 = default)
Definition options.h:518
bool help
Show help message.
Definition options.h:448
bool prefer_webrtc
–prefer-webrtc: Try WebRTC before Direct TCP
Definition options.h:562
double snapshot_delay
Snapshot delay in seconds.
Definition options.h:533
unsigned short int strip_ansi
Strip ANSI escape sequences.
Definition options.h:534
bool acds
Enable ACDS session registration (default: false)
Definition options.h:471
unsigned short int audio_enabled
Enable audio streaming.
Definition options.h:516
int fps
Target framerate (1-144, 0=use default)
Definition options.h:511
int reconnect_attempts
Number of reconnection attempts (-1=infinite, 0=none)
Definition options.h:494
bool test_pattern
Use test pattern instead of webcam.
Definition options.h:501
bool require_client_verify
Client: only connect to servers whose identity was verified by ACDS.
Definition options.h:555
bool webcam_flip
Flip webcam image horizontally.
Definition options.h:500
unsigned short int snapshot_mode
Snapshot mode (one frame and exit)
Definition options.h:532
bool require_server_verify
Server: only accept clients who verified via ACDS.
Definition options.h:554
palette_type_t palette_type
Selected palette type.
Definition options.h:581
char turn_secret[256]
ACDS: Shared secret for dynamic TURN credential generation (HMAC-SHA1)
Definition options.h:576
unsigned short int audio_analysis_enabled
Enable audio analysis (debug)
Definition options.h:519
bool require_client_identity
ACDS: require clients to provide signed Ed25519 identity.
Definition options.h:553
unsigned short int stretch
Allow aspect ratio distortion.
Definition options.h:525
bool encode_audio
Enable Opus audio encoding.
Definition options.h:489
char encrypt_key[256]
SSH/GPG key file path.
Definition options.h:542
char turn_username[256]
ACDS: Username for TURN authentication.
Definition options.h:574
char log_file[256]
Log file path.
Definition options.h:535
unsigned short int verbose_level
Verbosity level (stackable -V)
Definition options.h:531
char address[256]
Server address (client) or bind address (server)
Definition options.h:462
bool auto_width
Auto-detect width from terminal.
Definition options.h:456
char client_keys[256]
Allowed client keys (server)
Definition options.h:547

◆ ASCIICHAT_BINARY_OPTIONS_STRUCT

#define ASCIICHAT_BINARY_OPTIONS_STRUCT

#include <options.h>

Value:
bool help; \
bool version; \
log_level_t log_level; \
unsigned short int quiet; \
unsigned short int verbose_level;
#define log_file(...)
File-only logging - writes to log file only, no stderr output.

Binary-level options (parsed before mode selection)

These options are common to all modes and parsed first.

Definition at line 311 of file options.h.

◆ ASCIICHAT_CLIENT_OPTIONS_STRUCT

#define ASCIICHAT_CLIENT_OPTIONS_STRUCT

#include <options.h>

Value:
ASCIICHAT_COMMON_OPTIONS_STRUCT \
char address[OPTIONS_BUFF_SIZE]; \
char port[OPTIONS_BUFF_SIZE]; \
int reconnect_attempts; \
unsigned short int webcam_index; \
bool webcam_flip; \
bool test_pattern; \
terminal_color_mode_t color_mode; \
render_mode_t render_mode; \
unsigned short int show_capabilities; \
unsigned short int force_utf8; \
unsigned short int audio_enabled; \
int microphone_index; \
int speakers_index; \
unsigned short int stretch; \
unsigned short int snapshot_mode; \
double snapshot_delay; \
char server_key[OPTIONS_BUFF_SIZE]; \
char encrypt_key[OPTIONS_BUFF_SIZE]; \
char password[OPTIONS_BUFF_SIZE]; \
unsigned short int require_client_verify;

Client mode options.

Complete set of options for client mode.

Definition at line 364 of file options.h.

◆ ASCIICHAT_COMMON_OPTIONS_STRUCT

#define ASCIICHAT_COMMON_OPTIONS_STRUCT

#include <options.h>

Value:
ASCIICHAT_BINARY_OPTIONS_STRUCT \
unsigned short int width; \
unsigned short int height; \
bool auto_width; \
ASCIICHAT_API bool auto_width
ASCIICHAT_API bool auto_height

Common options (all modes after binary parsing)

These options extend binary options with terminal dimensions.

Definition at line 324 of file options.h.

◆ ASCIICHAT_MIRROR_OPTIONS_STRUCT

#define ASCIICHAT_MIRROR_OPTIONS_STRUCT

#include <options.h>

Value:
ASCIICHAT_COMMON_OPTIONS_STRUCT \
unsigned short int webcam_index; \
bool webcam_flip; \
bool test_pattern; \
terminal_color_mode_t color_mode; \
render_mode_t render_mode; \
unsigned short int force_utf8; \
unsigned short int stretch;

Mirror mode options.

Complete set of options for mirror mode (local webcam viewing).

Definition at line 392 of file options.h.

◆ ASCIICHAT_SERVER_OPTIONS_STRUCT

#define ASCIICHAT_SERVER_OPTIONS_STRUCT

#include <options.h>

Value:
ASCIICHAT_COMMON_OPTIONS_STRUCT \
char address[OPTIONS_BUFF_SIZE]; \
char address6[OPTIONS_BUFF_SIZE]; \
char port[OPTIONS_BUFF_SIZE]; \
int max_clients; \
int compression_level; \
bool no_compress; \
bool encode_audio; \
unsigned short int encrypt_enabled; \
char encrypt_key[OPTIONS_BUFF_SIZE]; \
char password[OPTIONS_BUFF_SIZE]; \
char encrypt_keyfile[OPTIONS_BUFF_SIZE]; \
unsigned short int no_encrypt; \
char client_keys[OPTIONS_BUFF_SIZE]; \
unsigned short int require_server_verify; \
bool acds; /* Enable ACDS session registration (default: false) */ \
bool acds_expose_ip; /* Explicitly allow public IP disclosure in ACDS sessions (opt-in) */ \
bool acds_insecure; /* Skip server key verification (MITM-vulnerable, requires explicit opt-in) */ \
char acds_server[OPTIONS_BUFF_SIZE]; \
int acds_port; \
bool webrtc; /* Enable WebRTC mode for ACDS session (default: Direct TCP) */

Server mode options.

Complete set of options for server mode.

Definition at line 336 of file options.h.

◆ COLOR_MODE_16

#define COLOR_MODE_16   TERM_COLOR_16

#include <options.h>

16-color mode (alias)

Definition at line 158 of file options.h.

◆ COLOR_MODE_16_COLOR

#define COLOR_MODE_16_COLOR   TERM_COLOR_16

#include <options.h>

16-color mode (full name)

Definition at line 159 of file options.h.

◆ COLOR_MODE_256

#define COLOR_MODE_256   TERM_COLOR_256

#include <options.h>

256-color mode (alias)

Definition at line 160 of file options.h.

◆ COLOR_MODE_256_COLOR

#define COLOR_MODE_256_COLOR   TERM_COLOR_256

#include <options.h>

256-color mode (full name)

Definition at line 161 of file options.h.

◆ COLOR_MODE_AUTO

#define COLOR_MODE_AUTO   TERM_COLOR_AUTO

#include <options.h>

Backward compatibility aliases for color mode enum values.

Auto-detect color support

Definition at line 156 of file options.h.

◆ COLOR_MODE_NONE

#define COLOR_MODE_NONE   TERM_COLOR_NONE

#include <options.h>

Monochrome mode.

Definition at line 157 of file options.h.

◆ COLOR_MODE_TRUECOLOR

#define COLOR_MODE_TRUECOLOR   TERM_COLOR_TRUECOLOR

#include <options.h>

24-bit truecolor mode

Definition at line 162 of file options.h.

◆ GET_OPTION

#define GET_OPTION (   field)

#include <options.h>

Value:
({ \
const options_t *_opts = options_get(); \
if (!_opts) { \
log_warn("GET_OPTION(" #field ") called but options not initialized"); \
} \
static typeof(((options_t *)0)->field) _default = {0}; \
(_opts ? (_opts->field) : _default); \
})

Safely get a specific option field (lock-free read)

Convenience macro for accessing individual option fields without storing the entire options pointer. Includes NULL check with warning log for safety.

Usage Examples:

// Simple field access
const char *addr = GET_OPTION(address6);
int width = GET_OPTION(width);
bool flip = GET_OPTION(webcam_flip);
// In expressions
if (GET_OPTION(encrypt_enabled)) {
// encryption is enabled
}
// Function arguments
connect_to_server(GET_OPTION(address), GET_OPTION(port));
#define GET_OPTION(field)
Safely get a specific option field (lock-free read)
Definition options.h:644

Design: This macro eliminates the need to store const options_t *opts pointers around the codebase, reducing clutter and making code more readable.

Safety: If options_get() returns NULL (shouldn't happen after initialization), the macro will log a warning and return a zero-initialized field.

Performance: Equivalent cost to direct options_get()->field access.

Parameters
fieldThe field name to access (e.g., address, port, width, etc.)
Returns
The value of the requested field
Note
Must be called after options_init() has completed
Zero-initialized fields are returned if options pointer is somehow NULL

Definition at line 644 of file options.h.

645 { \
646 const options_t *_opts = options_get(); \
647 if (!_opts) { \
648 log_warn("GET_OPTION(" #field ") called but options not initialized"); \
649 } \
650 static typeof(((options_t *)0)->field) _default = {0}; \
651 (_opts ? (_opts->field) : _default); \
652 })

◆ LEVENSHTEIN_SUGGESTION_THRESHOLD

#define LEVENSHTEIN_SUGGESTION_THRESHOLD   3

#include <levenshtein.h>

Maximum edit distance to suggest an option.

Threshold of 2 catches most typos (single char errors, transpositions) without suggesting unrelated options.

Definition at line 29 of file levenshtein.h.

◆ OPT_ADDRESS6_DEFAULT

#define OPT_ADDRESS6_DEFAULT   "::1"

#include <options.h>

Default IPv6 server address.

Definition at line 222 of file options.h.

◆ OPT_ADDRESS_DEFAULT

#define OPT_ADDRESS_DEFAULT   "localhost"

#include <options.h>

Default server address for client connections.

Definition at line 219 of file options.h.

◆ OPT_COLOR_MODE_DEFAULT

#define OPT_COLOR_MODE_DEFAULT   COLOR_MODE_AUTO

#include <options.h>

Default color mode (auto-detect terminal capabilities)

Definition at line 249 of file options.h.

◆ OPT_COMPRESSION_LEVEL_DEFAULT

#define OPT_COMPRESSION_LEVEL_DEFAULT   1

#include <options.h>

Default compression level (1-9)

Definition at line 228 of file options.h.

◆ OPT_ENCODE_AUDIO_DEFAULT

#define OPT_ENCODE_AUDIO_DEFAULT   true

#include <options.h>

Default audio encoding state (true = Opus encoding enabled)

Definition at line 255 of file options.h.

◆ OPT_FPS_DEFAULT

#define OPT_FPS_DEFAULT   60

#include <options.h>

Default FPS (frames per second)

Definition at line 231 of file options.h.

◆ OPT_HEIGHT_DEFAULT

#define OPT_HEIGHT_DEFAULT   70

#include <options.h>

Default terminal height in characters.

Default height used when terminal size cannot be detected or when auto-detection is disabled. This default provides a reasonable size for ASCII art display.

Note
This is used as a fallback if --height is not specified and auto-detection fails.

Definition at line 198 of file options.h.

◆ OPT_MAX_CLIENTS_DEFAULT

#define OPT_MAX_CLIENTS_DEFAULT   9

#include <options.h>

Default maximum concurrent clients (server only)

Definition at line 225 of file options.h.

◆ OPT_MICROPHONE_INDEX_DEFAULT

#define OPT_MICROPHONE_INDEX_DEFAULT   (-1)

#include <options.h>

Default microphone device index (-1 means system default)

Definition at line 237 of file options.h.

◆ OPT_PORT_DEFAULT

#define OPT_PORT_DEFAULT   "27224"

#include <options.h>

Default TCP port for client/server communication.

Definition at line 216 of file options.h.

◆ OPT_RECONNECT_ATTEMPTS_DEFAULT

#define OPT_RECONNECT_ATTEMPTS_DEFAULT   (-1)

#include <options.h>

Default reconnect attempts (-1 means auto/infinite)

Definition at line 243 of file options.h.

◆ OPT_RENDER_MODE_DEFAULT

#define OPT_RENDER_MODE_DEFAULT   RENDER_MODE_FOREGROUND

#include <options.h>

Default render mode (foreground characters only)

Definition at line 252 of file options.h.

◆ OPT_SPEAKERS_INDEX_DEFAULT

#define OPT_SPEAKERS_INDEX_DEFAULT   (-1)

#include <options.h>

Default speakers device index (-1 means system default)

Definition at line 240 of file options.h.

◆ OPT_WEBCAM_FLIP_DEFAULT

#define OPT_WEBCAM_FLIP_DEFAULT   true

#include <options.h>

Default webcam flip state (true = horizontally flipped)

Definition at line 246 of file options.h.

◆ OPT_WEBCAM_INDEX_DEFAULT

#define OPT_WEBCAM_INDEX_DEFAULT   0

#include <options.h>

Default webcam device index.

Definition at line 234 of file options.h.

◆ OPT_WIDTH_DEFAULT

#define OPT_WIDTH_DEFAULT   110

#include <options.h>

Default terminal width in characters.

Default width used when terminal size cannot be detected or when auto-detection is disabled. This default provides a reasonable size for ASCII art display.

Note
This is used as a fallback if --width is not specified and auto-detection fails.

Definition at line 187 of file options.h.

◆ OPTIONS_BUFF_SIZE

#define OPTIONS_BUFF_SIZE   256

#include <options.h>

Buffer size for option string values.

Maximum size for string-based options (e.g., addresses, file paths, passwords). Used for arrays that store option values.

Definition at line 176 of file options.h.

◆ SNAPSHOT_DELAY_DEFAULT

#define SNAPSHOT_DELAY_DEFAULT   3.0f

#include <options.h>

Default snapshot delay in seconds.

Default delay for snapshot mode before exiting. macOS webcams show pure black first then fade up into a real color image over a few seconds, so we use a longer delay on macOS.

Definition at line 212 of file options.h.

Typedef Documentation

◆ options_t

typedef struct options_state options_t

#include <options.h>

Consolidated options structure.

All options from the scattered extern globals are now in a single struct. This struct is immutable once published via RCU - modifications create a new copy.

Enumeration Type Documentation

◆ asciichat_mode_t

#include <options.h>

Mode type for options parsing.

Determines which set of options to use when parsing command-line arguments.

Enumerator
MODE_SERVER 

Server mode - network server options.

MODE_CLIENT 

Client mode - network client options.

MODE_MIRROR 

Mirror mode - local webcam viewing (no network)

MODE_ACDS 

Discovery service mode - session management and WebRTC signaling.

Definition at line 426 of file options.h.

Function Documentation

◆ levenshtein()

ASCIICHAT_API size_t levenshtein ( const char *  a,
const char *  b 
)

#include <levenshtein.h>

Calculate Levenshtein distance between two strings.

The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.

Parameters
aFirst string
bSecond string
Returns
Edit distance, or SIZE_MAX on error
See also
https://en.wikipedia.org/wiki/Levenshtein_distance

Definition at line 72 of file levenshtein.c.

72 {
73 if (!a || !b) {
74 return SIZE_MAX;
75 }
76 const size_t length = strlen(a);
77 const size_t bLength = strlen(b);
78
79 return levenshtein_n(a, length, b, bLength);
80}
size_t levenshtein_n(const char *a, const size_t length, const char *b, const size_t bLength)
Calculate Levenshtein distance with explicit string lengths.
Definition levenshtein.c:20

References levenshtein_n().

Referenced by find_similar_option(), and levenshtein_find_similar().

◆ levenshtein_find_similar()

ASCIICHAT_API const char * levenshtein_find_similar ( const char *  unknown,
const char *const *  candidates 
)

#include <levenshtein.h>

Find the most similar string from a NULL-terminated array.

Searches through an array of candidate strings to find the one most similar to the input string, using Levenshtein distance.

Parameters
unknownThe string to match against
candidatesNULL-terminated array of candidate strings
Returns
Best matching string, or NULL if no match within threshold

Definition at line 82 of file levenshtein.c.

82 {
83 if (!unknown || !candidates) {
84 return NULL;
85 }
86
87 const char *best_match = NULL;
88 size_t best_distance = SIZE_MAX;
89
90 for (int i = 0; candidates[i] != NULL; i++) {
91 size_t dist = levenshtein(unknown, candidates[i]);
92 if (dist < best_distance) {
93 best_distance = dist;
94 best_match = candidates[i];
95 }
96 }
97
98 // Only suggest if the distance is within our threshold
99 if (best_distance <= LEVENSHTEIN_SUGGESTION_THRESHOLD) {
100 return best_match;
101 }
102
103 return NULL;
104}
#define LEVENSHTEIN_SUGGESTION_THRESHOLD
Maximum edit distance to suggest an option.
Definition levenshtein.h:29
size_t levenshtein(const char *a, const char *b)
Calculate Levenshtein distance between two strings.
Definition levenshtein.c:72

References levenshtein(), and LEVENSHTEIN_SUGGESTION_THRESHOLD.

◆ levenshtein_n()

ASCIICHAT_API size_t levenshtein_n ( const char *  a,
const size_t  length,
const char *  b,
const size_t  bLength 
)

#include <levenshtein.h>

Calculate Levenshtein distance with explicit string lengths.

Parameters
aFirst string
lengthLength of first string
bSecond string
bLengthLength of second string
Returns
Edit distance, or SIZE_MAX on error

Definition at line 20 of file levenshtein.c.

20 {
21 // Shortcut optimizations / degenerate cases.
22 if (a == b) {
23 return 0;
24 }
25
26 if (length == 0) {
27 return bLength;
28 }
29
30 if (bLength == 0) {
31 return length;
32 }
33
34 size_t *cache = SAFE_CALLOC(length, sizeof(size_t), size_t *);
35 if (!cache) {
36 return SIZE_MAX; // Allocation failed
37 }
38
39 size_t index = 0;
40 size_t bIndex = 0;
41 size_t distance;
42 size_t bDistance;
43 size_t result = 0;
44 char code;
45
46 // initialize the vector.
47 while (index < length) {
48 cache[index] = index + 1;
49 index++;
50 }
51
52 // Loop.
53 while (bIndex < bLength) {
54 code = b[bIndex];
55 result = distance = bIndex++;
56
57 for (index = 0; index < length; index++) {
58 bDistance = code == a[index] ? distance : distance + 1;
59 distance = cache[index];
60
61 cache[index] = result = distance > result ? bDistance > result ? result + 1 : bDistance
62 : bDistance > distance ? distance + 1
63 : bDistance;
64 }
65 }
66
67 SAFE_FREE(cache);
68
69 return result;
70}
#define SAFE_FREE(ptr)
Definition common.h:320
#define SAFE_CALLOC(count, size, cast)
Definition common.h:218

References SAFE_CALLOC, and SAFE_FREE.

Referenced by levenshtein().

◆ options_get()

const options_t * options_get ( void  )

#include <options.h>

Get current options (lock-free read)

Returns a pointer to the current options struct. This pointer is guaranteed to remain valid for the lifetime of your function (no one will free it under you).

Performance: Single atomic pointer load (~1-2ns on modern CPUs)

Returns
Pointer to current options (never NULL after options_init())

Definition at line 222 of file rcu.c.

222 {
223 // Lock-free read with acquire semantics
224 // Guarantees we see all writes made before the pointer was published
225 options_t *current = atomic_load_explicit(&g_options, memory_order_acquire);
226
227 // Should never be NULL after initialization
228 if (!current) {
229 log_fatal("Options not initialized! Call options_state_init() first");
230 log_warn("options_get() called before options initialization - this will cause a crash");
231 abort();
232 }
233
234 return current;
235}
#define log_warn(...)
Log a WARN message.
#define log_fatal(...)
Log a FATAL message.

References log_fatal, and log_warn.

Referenced by asciichat_shared_init(), client_crypto_init(), client_main(), log_set_terminal_output(), main(), main(), server_crypto_handshake(), tcp_client_send_terminal_capabilities(), and threaded_send_terminal_size_with_auto_detect().

◆ options_init()

asciichat_error_t options_init ( int  argc,
char **  argv 
)

#include <options.h>

Initialize options by parsing command-line arguments.

Parameters
argcArgument count from main()
argvArgument vector from main()
is_clienttrue if parsing client options, false for server options
Returns
ASCIICHAT_OK on success, ERROR_USAGE on parse errors

Parses command-line arguments and initializes all option global variables. This function must be called once at program startup before accessing any options.

Parsing Process:

  1. Parse command-line arguments using getopt() (POSIX-compliant)
  2. Validate option values (ranges, file existence, formats)
  3. Apply default values for unspecified options
  4. Perform mode-specific validation (client vs server)
  5. Initialize global option variables

Special Return Values:

  • ASCIICHAT_OK: Parsing succeeded (normal case)
  • ASCIICHAT_OK: Also returned for --help and --version (after printing info)
  • ERROR_USAGE: Parse error or invalid option (usage info should be printed)

Mode-Specific Behavior:

  • Client mode (is_client = true): Parses client-specific options (color mode, webcam, snapshot mode, etc.)
  • Server mode (is_client = false): Parses server-specific options (bind address, client keys whitelist, etc.)

Validation:

  • Numeric ranges (e.g., port 1-65535, webcam index >= 0)
  • File existence (key files, log files)
  • Format correctness (IP addresses, port numbers)
  • Mode compatibility (rejects client-only options in server mode)

Default Value Application: After parsing, unspecified options are set to defaults:

  • Terminal dimensions: Auto-detect or use OPT_WIDTH_DEFAULT/OPT_HEIGHT_DEFAULT
  • Network: localhost:27224
  • Webcam: Index 0 (first device)
  • Color mode: Auto-detect
  • Encryption: Enabled if keys found, disabled otherwise

Environment Variables: The following environment variables are checked during option parsing:

  • WEBCAM_DISABLED: When set to "1", "true", "yes", or "on", automatically enables test pattern mode (opt_test_pattern = true). Useful for CI/CD environments and testing without a physical webcam.
Example:
int main(int argc, char **argv) {
// Parse options (client mode)
asciichat_error_t err = options_init(argc, argv, true);
if (err != ASCIICHAT_OK) {
if (err == ERROR_USAGE) {
usage(stderr, true); // Print usage
}
return 1;
}
// Options are now available via global variables
printf("Connecting to %s:%s\n", opt_address, opt_port);
return 0;
}
Note
Must be called once at program startup before accessing options
Global option variables are initialized by this function
Returns ERROR_USAGE for invalid options (caller should print usage)
--help and --version cause early exit (function still returns ASCIICHAT_OK)

Initialize options by parsing command-line arguments with unified mode detection

Parameters
argcArgument count from main()
argvArgument vector from main()
Returns
ASCIICHAT_OK on success, ERROR_USAGE on parse errors

Unified options initialization that handles:

  • Mode detection from argv (or defaults to server)
  • Binary-level option parsing (–help, –version, –log-file, etc.)
  • Mode-specific option parsing
  • Configuration file loading
  • Post-processing and validation

The detected mode is stored in options_t->detected_mode for retrieval via options_get()->detected_mode after this function returns.

Mode Detection Priority:

  1. –help or –version → handled internally, may exit(0)
  2. First non-option positional argument → matched against mode names
  3. Session string pattern (word-word-word) → treated as client mode
  4. No mode specified → defaults to show help and exit(0)
Note
Must be called once at program startup before accessing options
Global option variables are initialized by this function
Returns ERROR_USAGE for invalid options (after printing error)
–help and –version may exit directly (returns ASCIICHAT_OK if they print first)

Definition at line 144 of file options.c.

144 {
145 // Validate arguments (safety check for tests)
146 if (argc < 0 || argc > 1000) {
147 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid argc: %d", argc);
148 }
149 if (argv == NULL) {
150 return SET_ERRNO(ERROR_INVALID_PARAM, "argv is NULL");
151 }
152 // Validate all argv elements are non-NULL up to argc
153 for (int i = 0; i < argc; i++) {
154 if (argv[i] == NULL) {
155 return SET_ERRNO(ERROR_INVALID_PARAM, "argv[%d] is NULL (argc=%d)", i, argc);
156 }
157 }
158
159 // Initialize RCU options system (must be done before any threads start)
160 asciichat_error_t rcu_init_result = options_state_init();
161 if (rcu_init_result != ASCIICHAT_OK) {
162 return rcu_init_result;
163 }
164
165 // Create local options struct and initialize with defaults
166 options_t opts = {0}; // Zero-initialize all fields
167
168 // ========================================================================
169 // STAGE 1: Mode Detection and Binary-Level Option Handling
170 // ========================================================================
171
172 asciichat_mode_t detected_mode = MODE_SERVER; // Default mode
173 char detected_session_string[64] = {0};
174 int mode_index = -1;
175
176 // First, detect the mode from command-line arguments
177 asciichat_error_t mode_detect_result =
178 options_detect_mode(argc, argv, &detected_mode, detected_session_string, &mode_index);
179 if (mode_detect_result != ASCIICHAT_OK) {
180 return mode_detect_result;
181 }
182
183 opts.detected_mode = detected_mode;
184
185 // Check for binary-level --help, --version, or --config-create
186 // These only trigger if:
187 // 1. No mode was detected (mode_index == -1), OR
188 // 2. The option appears BEFORE the mode in argv
189 bool show_help = false;
190 bool show_version = false;
191 bool create_config = false;
192 const char *config_create_path = NULL;
193
194 int search_limit = (mode_index == -1) ? argc : mode_index;
195 for (int i = 1; i < search_limit; i++) {
196 if (argv[i][0] == '-') {
197 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
198 show_help = true;
199 break;
200 }
201 if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
202 show_version = true;
203 break;
204 }
205 if (strcmp(argv[i], "--config-create") == 0) {
206 create_config = true;
207 // Check if next argument is a path (not a flag)
208 if (i + 1 < argc && argv[i + 1][0] != '-') {
209 config_create_path = argv[i + 1];
210 }
211 break;
212 }
213 }
214 }
215
216 if (show_help) {
217 // Show binary-level help from src/main.c
218 opts.help = true;
219 options_state_set(&opts);
220 return ASCIICHAT_OK;
221 }
222
223 if (show_version) {
224 // Show binary-level version from src/main.c
225 opts.version = true;
226 options_state_set(&opts);
227 return ASCIICHAT_OK;
228 }
229
230 if (create_config) {
231 // Handle --config-create: create default config file and exit
232 // Use provided path or default to user config location
233 char config_path[PLATFORM_MAX_PATH_LENGTH];
234 if (config_create_path) {
235 SAFE_STRNCPY(config_path, config_create_path, sizeof(config_path));
236 } else {
237 // Use default config path: ~/.ascii-chat/config.toml
238 char *config_dir = get_config_dir();
239 if (!config_dir) {
240 fprintf(stderr, "Error: Failed to determine default config directory\n");
241 return ERROR_CONFIG;
242 }
243 snprintf(config_path, sizeof(config_path), "%sconfig.toml", config_dir);
244 SAFE_FREE(config_dir);
245 }
246
247 // Create config with default options
248 asciichat_error_t result = config_create_default(config_path, &opts);
249 if (result != ASCIICHAT_OK) {
251 if (HAS_ERRNO(&err_ctx)) {
252 fprintf(stderr, "Error creating config: %s\n", err_ctx.context_message);
253 } else {
254 fprintf(stderr, "Error: Failed to create config file at %s\n", config_path);
255 }
256 return result;
257 }
258
259 printf("Created default config file at: %s\n", config_path);
260 exit(0); // Exit successfully after creating config
261 }
262
263 // ========================================================================
264 // STAGE 2: Build argv for mode-specific parsing
265 // ========================================================================
266
267 // If mode was found, build argv with only arguments after the mode
268 // If mode_index == -1, we use all arguments (they become mode-specific args)
269 int mode_argc = argc;
270 char **mode_argv = (char **)argv;
271
272 if (mode_index != -1) {
273 // Mode found at position mode_index
274 // Build new argv: [program_name, args_before_mode..., args_after_mode...]
275 // This preserves binary-level options like --log-file that appear before mode
276
277 // Special case: if mode_index == 0, argv[0] is the mode name (test compatibility)
278 // Use "ascii-chat" as the binary name
279 int args_before_mode = (mode_index == 0) ? 0 : (mode_index - 1);
280 int args_after_mode = argc - mode_index - 1;
281 mode_argc = 1 + args_before_mode + args_after_mode;
282
283 if (mode_argc > 256) {
284 return SET_ERRNO(ERROR_INVALID_PARAM, "Too many arguments: %d", mode_argc);
285 }
286
287 // Allocate mode_argc+1 to accommodate NULL terminator
288 char **new_mode_argv = SAFE_MALLOC((size_t)(mode_argc + 1) * sizeof(char *), char **);
289 if (!new_mode_argv) {
290 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate mode_argv");
291 }
292
293 // Copy: [program_name, args_before_mode..., args_after_mode...]
294 if (mode_index == 0) {
295 // Mode is at argv[0], use "ascii-chat" as program name
296 new_mode_argv[0] = "ascii-chat";
297 } else {
298 new_mode_argv[0] = argv[0];
299 }
300 for (int i = 0; i < args_before_mode; i++) {
301 new_mode_argv[1 + i] = argv[1 + i]; // argv[1] to argv[mode_index-1]
302 }
303 for (int i = 0; i < args_after_mode; i++) {
304 new_mode_argv[1 + args_before_mode + i] = argv[mode_index + 1 + i];
305 }
306 new_mode_argv[mode_argc] = NULL;
307
308 mode_argv = new_mode_argv;
309 }
310
311 // ========================================================================
312 // STAGE 3: Set Mode-Specific Defaults
313 // ========================================================================
314
315 // Set default dimensions (fallback if terminal size detection fails)
318 opts.auto_width = true;
319 opts.auto_height = true;
320
321 // Set default port
323
324 // Set other non-zero defaults (using macros from options.h)
334
335 // Set default log file paths based on build type
336 // Release: $tmpdir/ascii-chat/MODE.log (e.g., /tmp/ascii-chat/server.log)
337 // Debug: MODE.log in current working directory (e.g., ./server.log)
338 char *log_dir = get_log_dir();
339 if (log_dir) {
340 // Determine log filename based on mode
341 const char *log_filename;
342 switch (detected_mode) {
343 case MODE_SERVER:
344 log_filename = "server.log";
345 break;
346 case MODE_CLIENT:
347 log_filename = "client.log";
348 break;
349 case MODE_MIRROR:
350 log_filename = "mirror.log";
351 break;
352 case MODE_ACDS:
353 log_filename = "acds.log";
354 break;
355 default:
356 log_filename = "ascii-chat.log";
357 break;
358 }
359
360 // Build full log file path: log_dir + separator + log_filename
361 char default_log_path[PLATFORM_MAX_PATH_LENGTH];
362 safe_snprintf(default_log_path, sizeof(default_log_path), "%s%s%s", log_dir, PATH_SEPARATOR_STR, log_filename);
363
364 // Validate and normalize the path
365 char *normalized_default_log = NULL;
366 if (path_validate_user_path(default_log_path, PATH_ROLE_LOG_FILE, &normalized_default_log) == ASCIICHAT_OK) {
367 SAFE_SNPRINTF(opts.log_file, OPTIONS_BUFF_SIZE, "%s", normalized_default_log);
368 SAFE_FREE(normalized_default_log);
369 } else {
370 // Validation failed - use the path as-is (validation may fail in debug builds)
371 SAFE_SNPRINTF(opts.log_file, OPTIONS_BUFF_SIZE, "%s", default_log_path);
372 }
373
374 SAFE_FREE(log_dir);
375 } else {
376 // Fallback if get_log_dir() fails - use simple filename in CWD
377 const char *log_filename;
378 switch (detected_mode) {
379 case MODE_SERVER:
380 log_filename = "server.log";
381 break;
382 case MODE_CLIENT:
383 log_filename = "client.log";
384 break;
385 case MODE_MIRROR:
386 log_filename = "mirror.log";
387 break;
388 case MODE_ACDS:
389 log_filename = "acds.log";
390 break;
391 default:
392 log_filename = "ascii-chat.log";
393 break;
394 }
395 SAFE_SNPRINTF(opts.log_file, OPTIONS_BUFF_SIZE, "%s", log_filename);
396 }
397
398 // Encryption options default to disabled/empty
399 opts.no_encrypt = 0;
400 opts.encrypt_key[0] = '\0';
401 opts.password[0] = '\0';
402 opts.encrypt_keyfile[0] = '\0';
403 opts.server_key[0] = '\0';
404 opts.client_keys[0] = '\0';
405 opts.palette_custom[0] = '\0';
406
407 // Set different default addresses for different modes
408 if (detected_mode == MODE_CLIENT || detected_mode == MODE_MIRROR) {
409 // Client/Mirror: connects to localhost by default
410 SAFE_SNPRINTF(opts.address, OPTIONS_BUFF_SIZE, "localhost");
411 opts.address6[0] = '\0'; // Client doesn't use address6
412 } else if (detected_mode == MODE_SERVER) {
413 // Server: binds to 127.0.0.1 (IPv4) and ::1 (IPv6) by default
414 SAFE_SNPRINTF(opts.address, OPTIONS_BUFF_SIZE, "127.0.0.1");
415 // address6 is now a positional argument, not an option
416 opts.address6[0] = '\0';
417 } else if (detected_mode == MODE_ACDS) {
418 // ACDS: binds to all interfaces by default
419 SAFE_SNPRINTF(opts.address, OPTIONS_BUFF_SIZE, "0.0.0.0");
420 opts.address6[0] = '\0';
421 }
422
423 // ========================================================================
424 // STAGE 4: Load Configuration Files
425 // ========================================================================
426
427 bool is_client_or_mirror = (detected_mode == MODE_CLIENT || detected_mode == MODE_MIRROR);
428 asciichat_error_t config_result = config_load_system_and_user(is_client_or_mirror, NULL, false, &opts);
429 (void)config_result; // Continue with defaults and CLI parsing regardless of result
430
431 // ========================================================================
432 // STAGE 5: Parse Command-Line Arguments (Mode-Specific)
433 // ========================================================================
434
436 switch (detected_mode) {
437 case MODE_SERVER:
438 result = parse_server_options(mode_argc, mode_argv, &opts);
439 break;
440 case MODE_CLIENT:
441 result = parse_client_options(mode_argc, mode_argv, &opts);
442 break;
443 case MODE_MIRROR:
444 result = parse_mirror_options(mode_argc, mode_argv, &opts);
445 break;
446 case MODE_ACDS:
447 result = parse_acds_options(mode_argc, mode_argv, &opts);
448 break;
449 default:
450 result = SET_ERRNO(ERROR_INVALID_PARAM, "Invalid detected mode: %d", detected_mode);
451 }
452
453 // Free the temporary mode_argv if we allocated it
454 if (mode_argv != (char **)argv) {
455 SAFE_FREE(mode_argv);
456 }
457
458 if (result != ASCIICHAT_OK) {
459 return result;
460 }
461
462 // Set session string if it was detected (ACDS mode via session string pattern)
463 if (detected_session_string[0] != '\0') {
464 SAFE_STRNCPY(opts.session_string, detected_session_string, sizeof(opts.session_string));
465 }
466
467 // ========================================================================
468 // STAGE 6: Post-Processing & Validation
469 // ========================================================================
470
471 // After parsing command line options, update dimensions
472 // First set any auto dimensions to terminal size, then apply full height logic
475
476 // Apply verbose level to log threshold
477 // Each -V decreases the log level by 1 (showing more verbose output)
478 // Minimum level is LOG_DEV (0)
479 if (opts.verbose_level > 0) {
480 log_level_t current_level = log_get_level();
481 int new_level = (int)current_level - (int)opts.verbose_level;
482 if (new_level < LOG_DEV) {
483 new_level = LOG_DEV;
484 }
485 log_set_level((log_level_t)new_level);
486 }
487
488 // Check WEBCAM_DISABLED environment variable to enable test pattern mode
489 // Useful for CI/CD and testing environments without a physical webcam
490 const char *webcam_disabled = SAFE_GETENV("WEBCAM_DISABLED");
491 if (webcam_disabled &&
492 (strcmp(webcam_disabled, "1") == 0 || platform_strcasecmp(webcam_disabled, "true") == 0 ||
493 platform_strcasecmp(webcam_disabled, "yes") == 0 || platform_strcasecmp(webcam_disabled, "on") == 0)) {
494 opts.test_pattern = true;
495 }
496
497 // Apply --no-compress interaction with audio encoding
498 if (opts.no_compress) {
499 opts.encode_audio = false;
500 log_debug("--no-compress set: disabling audio encoding");
501 }
502
503 // ========================================================================
504 // STAGE 7: Publish to RCU
505 // ========================================================================
506
507 // Publish parsed options to RCU state (replaces options_state_populate_from_globals)
508 // This makes the options visible to all threads via lock-free reads
509 asciichat_error_t publish_result = options_state_set(&opts);
510 if (publish_result != ASCIICHAT_OK) {
511 log_error("Failed to publish parsed options to RCU state");
512 return publish_result;
513 }
514
515 return ASCIICHAT_OK;
516}
asciichat_error_t parse_acds_options(int argc, char **argv, options_t *opts)
Parse ACDS-specific command-line options.
Definition acds.c:48
#define SAFE_STRNCPY(dst, src, size)
Definition common.h:358
#define SAFE_MALLOC(size, cast)
Definition common.h:208
#define SAFE_GETENV(name)
Definition common.h:378
#define SAFE_SNPRINTF(buffer, buffer_size,...)
Definition common.h:412
#define PLATFORM_MAX_PATH_LENGTH
Definition common.h:91
asciichat_error_t config_create_default(const char *config_path, const options_t *opts)
Create default configuration file with all default values.
Definition config.c:999
asciichat_error_t config_load_system_and_user(bool is_client, const char *user_config_path, bool strict, options_t *opts)
Load system config first, then user config (user config overrides system)
Definition config.c:1207
#define SET_ERRNO(code, context_msg,...)
Set error code with custom context message and log it.
@ ERROR_MEMORY
Definition error_codes.h:53
@ ERROR_CONFIG
Definition error_codes.h:54
@ ERROR_INVALID_PARAM
log_level_t log_get_level(void)
Get the current minimum log level.
void log_set_level(log_level_t level)
Set the minimum log level.
#define log_debug(...)
Log a DEBUG message.
@ LOG_DEV
Definition log/logging.h:60
#define OPT_MICROPHONE_INDEX_DEFAULT
Default microphone device index (-1 means system default)
Definition options.h:237
#define OPT_ENCODE_AUDIO_DEFAULT
Default audio encoding state (true = Opus encoding enabled)
Definition options.h:255
#define OPT_COLOR_MODE_DEFAULT
Default color mode (auto-detect terminal capabilities)
Definition options.h:249
#define OPT_RECONNECT_ATTEMPTS_DEFAULT
Default reconnect attempts (-1 means auto/infinite)
Definition options.h:243
#define OPT_WEBCAM_FLIP_DEFAULT
Default webcam flip state (true = horizontally flipped)
Definition options.h:246
#define OPT_COMPRESSION_LEVEL_DEFAULT
Default compression level (1-9)
Definition options.h:228
#define OPT_RENDER_MODE_DEFAULT
Default render mode (foreground characters only)
Definition options.h:252
#define OPT_PORT_DEFAULT
Default TCP port for client/server communication.
Definition options.h:216
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
Definition options.h:198
#define OPT_MAX_CLIENTS_DEFAULT
Default maximum concurrent clients (server only)
Definition options.h:225
#define OPT_SPEAKERS_INDEX_DEFAULT
Default speakers device index (-1 means system default)
Definition options.h:240
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
Definition options.h:187
int safe_snprintf(char *buffer, size_t buffer_size, const char *format,...)
Safe version of snprintf that ensures null termination.
#define PATH_SEPARATOR_STR
Definition system.h:606
int platform_strcasecmp(const char *s1, const char *s2)
Case-insensitive string comparison.
char * get_log_dir(void)
Get log directory path appropriate for current build type.
Definition path.c:277
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:498
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:223
@ PATH_ROLE_LOG_FILE
Definition path.h:255
asciichat_error_t parse_client_options(int argc, char **argv, options_t *opts)
Parse client-specific command-line options.
asciichat_error_t parse_server_options(int argc, char **argv, options_t *opts)
Parse server-specific command-line options.
asciichat_error_t parse_mirror_options(int argc, char **argv, options_t *opts)
Parse mirror-specific command-line options.
Definition mirror.c:35
asciichat_error_t options_state_init(void)
Initialize RCU options system.
Definition rcu.c:117
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:176

References options_state::address, options_state::address6, ASCIICHAT_OK, options_state::auto_height, options_state::auto_width, options_state::client_keys, options_state::color_mode, options_state::compression_level, config_create_default(), config_load_system_and_user(), asciichat_error_context_t::context_message, options_state::detected_mode, options_state::encode_audio, options_state::encrypt_key, options_state::encrypt_keyfile, ERROR_CONFIG, ERROR_INVALID_PARAM, ERROR_MEMORY, get_config_dir(), get_log_dir(), HAS_ERRNO, options_state::height, options_state::help, log_debug, LOG_DEV, log_error, options_state::log_file, log_get_level(), log_set_level(), options_state::max_clients, options_state::microphone_index, MODE_ACDS, MODE_CLIENT, MODE_MIRROR, MODE_SERVER, options_state::no_compress, options_state::no_encrypt, OPT_COLOR_MODE_DEFAULT, OPT_COMPRESSION_LEVEL_DEFAULT, OPT_ENCODE_AUDIO_DEFAULT, OPT_HEIGHT_DEFAULT, OPT_MAX_CLIENTS_DEFAULT, OPT_MICROPHONE_INDEX_DEFAULT, OPT_PORT_DEFAULT, OPT_RECONNECT_ATTEMPTS_DEFAULT, OPT_RENDER_MODE_DEFAULT, OPT_SPEAKERS_INDEX_DEFAULT, OPT_WEBCAM_FLIP_DEFAULT, OPT_WIDTH_DEFAULT, OPTIONS_BUFF_SIZE, options_state_init(), options_state_set(), options_state::palette_custom, parse_acds_options(), parse_client_options(), parse_mirror_options(), parse_server_options(), options_state::password, PATH_ROLE_LOG_FILE, PATH_SEPARATOR_STR, path_validate_user_path(), PLATFORM_MAX_PATH_LENGTH, platform_strcasecmp(), options_state::port, options_state::reconnect_attempts, options_state::render_mode, SAFE_FREE, SAFE_GETENV, SAFE_MALLOC, SAFE_SNPRINTF, safe_snprintf(), SAFE_STRNCPY, options_state::server_key, options_state::session_string, SET_ERRNO, options_state::speakers_index, options_state::test_pattern, update_dimensions_for_full_height(), update_dimensions_to_terminal_size(), options_state::verbose_level, options_state::version, options_state::webcam_flip, and options_state::width.

Referenced by main(), and main().

◆ options_set_color_mode()

asciichat_error_t options_set_color_mode ( terminal_color_mode_t  mode)

#include <options.h>

Update color mode.

Thread-safe setter for color mode. Uses RCU update internally.

Parameters
modeNew color mode
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 304 of file rcu.c.

304 {
305 return options_update(color_mode_updater, &mode);
306}

References options_update().

◆ options_set_dimensions()

asciichat_error_t options_set_dimensions ( unsigned short int  width,
unsigned short int  height 
)

#include <options.h>

Update terminal dimensions.

Thread-safe setter for width/height. Uses RCU update internally.

Parameters
widthNew terminal width in characters
heightNew terminal height in characters
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 294 of file rcu.c.

294 {
295 struct dimensions_update_ctx ctx = {.width = width, .height = height};
296 return options_update(dimensions_updater, &ctx);
297}
unsigned short int height
Definition rcu.c:285
unsigned short int width
Definition rcu.c:284

References dimensions_update_ctx::height, options_update(), and dimensions_update_ctx::width.

◆ options_set_log_level()

asciichat_error_t options_set_log_level ( log_level_t  level)

#include <options.h>

Update log level.

Thread-safe setter for log level. Uses RCU update internally.

Parameters
levelNew log level
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 322 of file rcu.c.

322 {
323 return options_update(log_level_updater, &level);
324}

References options_update().

◆ options_set_render_mode()

asciichat_error_t options_set_render_mode ( render_mode_t  mode)

#include <options.h>

Update render mode.

Thread-safe setter for render mode. Uses RCU update internally.

Parameters
modeNew render mode
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 313 of file rcu.c.

313 {
314 return options_update(render_mode_updater, &mode);
315}

References options_update().

◆ options_update()

asciichat_error_t options_update ( void(*)(options_t *, void *)  updater,
void *  context 
)

#include <options.h>

Update options using copy-on-write (thread-safe)

Callback-based update interface. Allocates a new options struct, copies current values, calls your callback to modify the copy, then atomically swaps the global pointer.

Thread Safety: Multiple writers are serialized with a mutex. Readers are never blocked.

Parameters
updaterCallback function that modifies the new options struct
contextUser context pointer passed to callback (can be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 237 of file rcu.c.

237 {
238 if (!updater) {
239 return SET_ERRNO(ERROR_INVALID_PARAM, "updater function is NULL");
240 }
241
242 if (!g_options_initialized) {
243 return SET_ERRNO(ERROR_INVALID_STATE, "Options state not initialized");
244 }
245
246 // Serialize writers with mutex
247 mutex_lock(&g_options_write_mutex);
248
249 // 1. Load current options (acquire semantics)
250 options_t *old_opts = atomic_load_explicit(&g_options, memory_order_acquire);
251
252 // 2. Allocate new options struct
253 options_t *new_opts = SAFE_MALLOC(sizeof(options_t), options_t *);
254 if (!new_opts) {
255 mutex_unlock(&g_options_write_mutex);
256 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate new options struct");
257 }
258
259 // 3. Copy current values to new struct
260 memcpy(new_opts, old_opts, sizeof(options_t));
261
262 // 4. Call user updater to modify the new struct
263 updater(new_opts, context);
264
265 // 5. Atomically swap global pointer (release semantics)
266 // This makes the new struct visible to all readers
267 atomic_store_explicit(&g_options, new_opts, memory_order_release);
268
269 // 6. Add old struct to deferred free list
270 deferred_free_add(old_opts);
271
272 mutex_unlock(&g_options_write_mutex);
273
274 log_debug("Options updated via RCU (old=%p, new=%p)", (void *)old_opts, (void *)new_opts);
275 return ASCIICHAT_OK;
276}
@ ERROR_INVALID_STATE
#define mutex_lock(mutex)
Lock a mutex (with debug tracking in debug builds)
Definition mutex.h:140
#define mutex_unlock(mutex)
Unlock a mutex (with debug tracking in debug builds)
Definition mutex.h:175

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, log_debug, mutex_lock, mutex_unlock, SAFE_MALLOC, and SET_ERRNO.

Referenced by main(), options_set_color_mode(), options_set_dimensions(), options_set_log_level(), and options_set_render_mode().

◆ strtoint_safe()

int strtoint_safe ( const char *  str)

#include <options.h>

Safely parse string to integer with validation.

Parameters
strString to parse (must not be NULL)
Returns
Integer value on success, INT_MIN on error

Parses a string to an integer with comprehensive validation:

  • Validates that string is not NULL or empty
  • Performs base-10 conversion using strtol()
  • Checks for partial conversions (characters left unconverted)
  • Validates result is within int range (INT_MIN to INT_MAX)
  • Returns INT_MIN on any error condition

This function is used internally by the options parser to safely convert command-line argument strings to integer values with proper error handling.

Note
Returns INT_MIN on error (which is distinguishable from valid negative values since INT_MIN is a valid integer, but unlikely to be used as an option value). The options parser checks for INT_MIN to detect parse errors.
Thread-safe: Uses only local variables, no static state.
Example:
const char *arg = "80";
int width = strtoint_safe(arg);
if (width == INT_MIN) {
// Parse error
} else {
// Valid integer: width == 80
}
int strtoint_safe(const char *str)
Safely parse string to integer with validation.

Parses a string to integer using parse_int32() with full range checking. Returns INT_MIN on error (NULL input, empty string, invalid format, out of range).

Parameters
strString to parse
Returns
Parsed integer value, or INT_MIN on error
Warning
INT_MIN is used as error sentinel, so cannot represent INT_MIN value

Example:

int val = strtoint_safe(optarg);
if (val == INT_MIN) {
fprintf(stderr, "Invalid integer: %s\n", optarg);
}

Definition at line 67 of file options/common.c.

67 {
68 if (!str || *str == '\0') {
69 return INT_MIN; // Error: NULL or empty string
70 }
71
72 int32_t result = 0;
73 // Use safe parsing utility with full int32 range validation
74 if (parse_int32(str, &result, INT_MIN, INT_MAX) != ASCIICHAT_OK) {
75 return INT_MIN; // Error: invalid input or out of range
76 }
77
78 return (int)result;
79}
asciichat_error_t parse_int32(const char *str, int32_t *out_value, int32_t min_value, int32_t max_value)
Parse signed 32-bit integer with range validation.
Definition parsing.c:240

References ASCIICHAT_OK, and parse_int32().

Referenced by client_crypto_init(), server_main(), validate_fps_opt(), validate_opt_compression_level(), validate_opt_device_index(), validate_opt_fps(), validate_opt_max_clients(), validate_opt_non_negative_int(), validate_opt_positive_int(), validate_opt_reconnect(), and validate_positive_int_opt().

◆ update_dimensions_for_full_height()

void update_dimensions_for_full_height ( options_t opts)

#include <options.h>

Update dimensions for full height display.

Adjusts opt_width and opt_height to use the full terminal height while maintaining the original aspect ratio. Useful for maximizing vertical space usage when the terminal is resized.

Calculation:

  • Uses full terminal height (from terminal size detection)
  • Calculates width to maintain aspect ratio
  • Updates opt_width and opt_height global variables

Usage: Call this function when terminal is resized or when you want to maximize vertical space usage while preserving aspect ratio.

Example: If terminal is 120×40 and original dimensions were 80×30:

  • Original aspect ratio: 80/30 = 2.67
  • New dimensions: 107×40 (maintains 2.67 aspect ratio, uses full height)
Note
Updates global variables opt_width and opt_height
Maintains aspect ratio of current dimensions
Uses terminal size detection to get full height
Useful for dynamic terminal resizing

Update dimensions for full height display.

Sets opt_height to terminal height when auto-detected. Used during initialization to maximize vertical space usage.

Behavior:

  • Both auto: Set both width and height to terminal size
  • Only height auto: Set height to terminal height
  • Only width auto: Set width to terminal width
  • Neither auto: No change
Note
Does not use log_debug because logging may not be initialized yet
Fails silently if terminal size detection fails (keeps defaults)

Example:

// During options_init():
}

Definition at line 535 of file options/common.c.

535 {
536 if (!opts) {
537 return;
538 }
539
540 unsigned short int term_width, term_height;
541
542 // Note: Logging is not available during options_init, so we can't use log_debug here
543 asciichat_error_t result = get_terminal_size(&term_width, &term_height);
544 if (result == ASCIICHAT_OK) {
545 // If both dimensions are auto, set height to terminal height and let
546 // aspect_ratio calculate width
547 if (opts->auto_height && opts->auto_width) {
548 opts->height = term_height;
549 opts->width = term_width; // Also set width when both are auto
550 }
551 // If only height is auto, use full terminal height
552 else if (opts->auto_height) {
553 opts->height = term_height;
554 }
555 // If only width is auto, use full terminal width
556 else if (opts->auto_width) {
557 opts->width = term_width;
558 }
559 } else {
560 // Terminal size detection failed, but we can still continue with defaults
561 }
562}
asciichat_error_t get_terminal_size(unsigned short int *width, unsigned short int *height)
Get terminal size with multiple fallback methods.

References ASCIICHAT_OK, options_state::auto_height, options_state::auto_width, get_terminal_size(), options_state::height, and options_state::width.

Referenced by options_init().

◆ update_dimensions_to_terminal_size()

void update_dimensions_to_terminal_size ( options_t opts)

#include <options.h>

Update dimensions to match terminal size.

Sets opt_width and opt_height to exactly match the current terminal dimensions. This function queries the terminal for its size and updates the option variables accordingly.

Detection: Uses platform-specific terminal size detection:

  • POSIX: TIOCGWINSZ ioctl on stdout
  • Windows: Console API GetConsoleScreenBufferInfo
  • Fallback: Environment variables ($COLUMNS, $LINES)
  • Final fallback: Default dimensions (OPT_WIDTH_DEFAULT, OPT_HEIGHT_DEFAULT)

Usage: Call this function:

  • After terminal resize (POSIX: SIGWINCH signal handler)
  • When auto-detection is enabled and dimensions need refreshing
  • When you want to sync dimensions with current terminal size

Example: Terminal is 160×60:

  • opt_width is set to 160
  • opt_height is set to 60
Note
Updates global variables opt_width and opt_height
Uses platform-specific terminal size detection
Handles detection failures gracefully (uses fallbacks)
Useful for terminal resize handling

Update dimensions to match terminal size.

Updates opt_width and opt_height to current terminal size for auto-detected dimensions. Used after logging is initialized (can use log_debug).

Behavior:

  • auto_width: Set width to terminal width
  • auto_height: Set height to terminal height
  • Neither: No change
Note
Logs debug messages about dimension updates
Logs debug message if terminal size detection fails

Example:

// After logging initialization:
log_info("Terminal dimensions: %dx%d", opt_width, opt_height);
#define log_info(...)
Log an INFO message.

Definition at line 564 of file options/common.c.

564 {
565 if (!opts) {
566 return;
567 }
568
569 unsigned short int term_width, term_height;
570 // Get current terminal size (get_terminal_size already handles ioctl first, then $COLUMNS/$LINES fallback)
571 asciichat_error_t terminal_result = get_terminal_size(&term_width, &term_height);
572 if (terminal_result == ASCIICHAT_OK) {
573 if (opts->auto_width) {
574 opts->width = term_width;
575 }
576 if (opts->auto_height) {
577 opts->height = term_height;
578 }
579 log_debug("After update_dimensions_to_terminal_size: width=%d, height=%d", opts->width, opts->height);
580 } else {
581 // Terminal detection failed - keep the default values set in options_init()
582 log_debug(
583 "Failed to get terminal size in update_dimensions_to_terminal_size, keeping defaults: width=%d, height=%d",
584 opts->width, opts->height);
585 }
586}

References ASCIICHAT_OK, options_state::auto_height, options_state::auto_width, get_terminal_size(), options_state::height, log_debug, and options_state::width.

Referenced by options_init().

◆ usage()

void usage ( FILE *  desc,
asciichat_mode_t  mode 
)

#include <options.h>

Print usage information for client, server, or mirror mode.

Parameters
descFile descriptor to write to (typically stdout or stderr)
modeMode to show usage for (MODE_SERVER, MODE_CLIENT, or MODE_MIRROR)

Prints comprehensive usage information including:

  • Program description and synopsis
  • All available command-line options
  • Option descriptions and default values
  • Usage examples
  • Mode-specific options (client vs server)

Usage: Called automatically by options_init() for --help, or manually by application code when ERROR_USAGE is returned.

Output: Formatted usage text including:

  • Program name and version
  • Synopsis with command syntax
  • Option list with short/long forms and descriptions
  • Examples of common usage patterns
Example:
if (options_init(argc, argv, true) == ERROR_USAGE) {
usage(stderr, true); // Print client usage
return 1;
}
Note
Typically printed to stderr for error cases, stdout for --help
Output is mode-specific (different options for client vs server)
Includes all available options with descriptions

Definition at line 592 of file options/common.c.

592 {
593 switch (mode) {
594 case MODE_SERVER:
595 usage_server(desc);
596 break;
597 case MODE_CLIENT:
598 usage_client(desc);
599 break;
600 case MODE_MIRROR:
601 usage_mirror(desc);
602 break;
603 case MODE_ACDS:
604 usage_acds(desc);
605 break;
606 default:
607 (void)fprintf(desc, "Unknown mode\n");
608 break;
609 }
610}

References MODE_ACDS, MODE_CLIENT, MODE_MIRROR, MODE_SERVER, usage_acds(), usage_client(), usage_mirror(), and usage_server().

Referenced by main().

◆ usage_acds()

void usage_acds ( FILE *  desc)

#include <options.h>

Print ACDS usage information.

Parameters
descFile descriptor to write to (typically stdout or stderr)

Prints ACDS (ASCII Chat Discovery Service) specific usage information.

Usage: Called when displaying ACDS help or error messages.

Includes: All ACDS-specific options:

  • Network binding options (address, port)
  • Database configuration
  • Identity key management
  • STUN/TURN server configuration

Definition at line 109 of file acds.c.

109 {
110 // Get config with program name and description
111 const options_config_t *config = options_preset_acds("acds", "ascii-chat discovery service");
112 if (!config) {
113 (void)fprintf(desc, "Error: Failed to create options config\n");
114 return;
115 }
116
117 (void)fprintf(desc, "%s - %s\n\n", config->program_name, config->description);
118 (void)fprintf(desc, "USAGE:\n");
119 (void)fprintf(desc, " %s [options...]\n\n", config->program_name);
120
121 // Print positional argument examples programmatically if they exist
122 if (config->num_positional_args > 0) {
123 const positional_arg_descriptor_t *pos_arg = &config->positional_args[0];
124 if (pos_arg->section_heading && pos_arg->examples && pos_arg->num_examples > 0) {
125 (void)fprintf(desc, "%s:\n", pos_arg->section_heading);
126 for (size_t i = 0; i < pos_arg->num_examples; i++) {
127 (void)fprintf(desc, " %s\n", pos_arg->examples[i]);
128 }
129 (void)fprintf(desc, "\n");
130 }
131 }
132
133 // Generate options from builder configuration
134 options_config_print_usage(config, desc);
135
136 // Clean up the config
138}
void options_config_print_usage(const options_config_t *config, FILE *stream)
Print usage/help text.
Definition builder.c:1236
void options_config_destroy(options_config_t *config)
Free options config.
Definition builder.c:329
const options_config_t * options_preset_acds(const char *program_name, const char *description)
Get acds mode options preset.
Definition presets.c:571
Options configuration.
Definition builder.h:165
positional_arg_descriptor_t * positional_args
Array of positional argument descriptors.
Definition builder.h:172
const char * program_name
For usage header.
Definition builder.h:176
size_t num_positional_args
Number of positional arguments.
Definition builder.h:173
const char * description
For usage header.
Definition builder.h:177
Positional argument descriptor.
Definition builder.h:136
const char * section_heading
Section heading for examples (e.g., "ADDRESS FORMATS")
Definition builder.h:142
const char ** examples
Array of example strings with descriptions.
Definition builder.h:143
size_t num_examples
Number of examples.
Definition builder.h:144

References options_config_t::description, positional_arg_descriptor_t::examples, positional_arg_descriptor_t::num_examples, options_config_t::num_positional_args, options_config_destroy(), options_config_print_usage(), options_preset_acds(), options_config_t::positional_args, options_config_t::program_name, and positional_arg_descriptor_t::section_heading.

Referenced by usage().

◆ usage_client()

void usage_client ( FILE *  desc)

#include <options.h>

Print client usage information.

Parameters
descFile descriptor to write to (typically stdout or stderr)

Convenience function that prints client-specific usage information. Equivalent to usage(desc, true).

Usage: Called when displaying client help or error messages.

Includes: All client-specific options:

  • Display options (color mode, render mode, UTF-8)
  • Webcam options (device index, flip, test pattern)
  • Snapshot mode options
  • Terminal dimension options
  • Client-specific encryption options (server key verification)

Print client usage information.

Displays comprehensive help for all client options, including:

  • Description of client mode
  • Positional argument format and examples
  • All client-specific flags with descriptions
  • Shared flags (palette, encryption, output)
  • Usage examples for common scenarios

Output Format:

Client mode: Connect to ascii-chat server and display video grid
Usage: ascii-chat client [OPTIONS] [address][:port]
Positional Arguments:
[address][:port] Server address with optional port (default: localhost:27224)
Examples: localhost, 192.168.1.100:8080, [::1]:27224
Network Options:
-p, --port PORT Server port (default: 27224)
Note: Conflicts with port in positional argument
Webcam Options:
-c, --webcam-index N Webcam device index (default: 0)
-f, --webcam-flip Mirror webcam horizontally (default: true)
--test-pattern Use test pattern instead of real webcam
--list-webcams List available webcams and exit
[... continues with all option categories ...]
#define true
Definition stdbool.h:23
Parameters
streamOutput stream (stdout for –help, stderr for errors)
Note
Does not exit - caller decides whether to exit after printing
Always includes mode description, positional args, and all flags
Examples show real-world usage patterns

Example usage:

// Print help and exit successfully
if (help_requested) {
usage_client(stdout);
exit(0);
}
// Print usage hint on error
if (parse_error) {
fprintf(stderr, "Error: Invalid option\n\n");
usage_client(stderr);
exit(1);
}
See also
usage_server()
usage_mirror()

Definition at line 86 of file lib/options/client.c.

86 {
87 // Get config with program name and description
88 const options_config_t *config = options_preset_client("ascii-chat client", "connect to an ascii-chat server");
89 if (!config) {
90 (void)fprintf(desc, "Error: Failed to create options config\n");
91 return;
92 }
93
94 // Print custom address format help first
95 (void)fprintf(desc, "%s - %s\n\n", config->program_name, config->description);
96 (void)fprintf(desc, "USAGE:\n");
97 (void)fprintf(desc, " %s [address][:port] [options...]\n\n", config->program_name);
98
99 // Print positional argument examples programmatically
100 if (config->num_positional_args > 0) {
101 const positional_arg_descriptor_t *pos_arg = &config->positional_args[0];
102 if (pos_arg->section_heading && pos_arg->examples && pos_arg->num_examples > 0) {
103 (void)fprintf(desc, "%s:\n", pos_arg->section_heading);
104 for (size_t i = 0; i < pos_arg->num_examples; i++) {
105 (void)fprintf(desc, " %s\n", pos_arg->examples[i]);
106 }
107 (void)fprintf(desc, "\n");
108 }
109 }
110
111 // Generate options from builder configuration
112 options_config_print_usage(config, desc);
113
114 // Clean up the config
116}
const options_config_t * options_preset_client(const char *program_name, const char *description)
Get client mode options preset.
Definition presets.c:398

References options_config_t::description, positional_arg_descriptor_t::examples, positional_arg_descriptor_t::num_examples, options_config_t::num_positional_args, options_config_destroy(), options_config_print_usage(), options_preset_client(), options_config_t::positional_args, options_config_t::program_name, and positional_arg_descriptor_t::section_heading.

Referenced by action_help_client(), and usage().

◆ usage_mirror()

void usage_mirror ( FILE *  desc)

#include <options.h>

Print mirror usage information.

Parameters
descFile descriptor to write to (typically stdout or stderr)

Prints mirror mode (local webcam preview) usage information.

Usage: Called when displaying mirror help or error messages.

Includes: Mirror-specific options:

  • Display options (color mode, palette)
  • Webcam options
  • Terminal dimension options

Print mirror usage information.

Displays comprehensive help for all mirror options, including:

  • Description of mirror mode and use cases
  • All mirror-specific flags with descriptions
  • Palette and output options
  • Debug options
  • Usage examples for common scenarios
  • Notes on differences from client mode

Output Format:

Mirror mode: Display local webcam as ASCII art (no network connection)
Usage: ascii-chat mirror [OPTIONS]
Display Options:
-x, --width WIDTH Terminal width in characters (default: auto-detect)
-y, --height HEIGHT Terminal height in characters (default: auto-detect)
--fps FPS Target framerate (1-144, default: 30)
--color-mode MODE Color mode: auto, mono, 16, 256, truecolor (default: auto)
--render-mode MODE Render mode: foreground, background (default: foreground)
Webcam Options:
-c, --webcam-index N Webcam device index (default: 0)
-f, --webcam-flip Mirror webcam horizontally (default: true)
--test-pattern Use test pattern instead of real webcam
--list-webcams List available webcams and exit
Output Options:
-s, --stretch Stretch/shrink without preserving aspect ratio
-q, --quiet Disable console logging (log to file only)
-S, --snapshot Capture one frame and exit
--snapshot-delay SEC Delay before snapshot (default: 3.0 seconds)
--strip-ansi Strip ANSI escape sequences from output
Palette Options:
-P, --palette TYPE Palette type: standard, blocks, digital, minimal, cool, custom
-C, --palette-chars S Custom palette characters (dark to bright)
Debug Options:
--show-capabilities Show terminal capabilities and exit
--utf8 Force UTF-8 output (enables multi-byte characters)
[... continues with examples ...]
Parameters
streamOutput stream (stdout for –help, stderr for errors)
Note
Does not exit - caller decides whether to exit after printing
Explicitly mentions that network/audio/crypto options are not available
Examples show standalone local usage patterns

Example usage:

// Print help and exit successfully
if (help_requested) {
usage_mirror(stdout);
exit(0);
}
// Print usage hint on error
if (parse_error) {
fprintf(stderr, "Error: Invalid option\n\n");
usage_mirror(stderr);
exit(1);
}
See also
usage_client()
usage_server()

Definition at line 71 of file mirror.c.

71 {
72 // Get config with program name and description
73 const options_config_t *config = options_preset_mirror("ascii-chat mirror", "view local webcam as ascii art");
74 if (!config) {
75 (void)fprintf(desc, "Error: Failed to create options config\n");
76 return;
77 }
78
79 (void)fprintf(desc, "%s - %s\n\n", config->program_name, config->description);
80 (void)fprintf(desc, "USAGE:\n");
81 (void)fprintf(desc, " %s [options...]\n\n", config->program_name);
82
83 // Generate options from builder configuration
84 options_config_print_usage(config, desc);
85
86 // Clean up the config
88}
const options_config_t * options_preset_mirror(const char *program_name, const char *description)
Get mirror mode options preset.
Definition presets.c:530

References options_config_t::description, options_config_destroy(), options_config_print_usage(), options_preset_mirror(), and options_config_t::program_name.

Referenced by action_help_mirror(), and usage().

◆ usage_server()

void usage_server ( FILE *  desc)

#include <options.h>

Print server usage information.

Parameters
descFile descriptor to write to (typically stdout or stderr)

Convenience function that prints server-specific usage information. Equivalent to usage(desc, false).

Usage: Called when displaying server help or error messages.

Includes: All server-specific options:

  • Network binding options (address, port, IPv6)
  • Server-specific encryption options (client keys whitelist)
  • Server configuration options

Definition at line 80 of file lib/options/server.c.

80 {
81 // Get config with program name and description
82 const options_config_t *config =
83 options_preset_server("ascii-chat server", "host a server mixing video and audio for ascii-chat clients");
84 if (!config) {
85 (void)fprintf(desc, "Error: Failed to create options config\n");
86 return;
87 }
88
89 // Print custom bind address help first
90 (void)fprintf(desc, "%s - %s\n\n", config->program_name, config->description);
91 (void)fprintf(desc, "USAGE:\n");
92 (void)fprintf(desc, " %s [bind-address] [bind-address6] [options...]\n\n", config->program_name);
93
94 // Print positional argument examples programmatically
95 if (config->num_positional_args > 0) {
96 const positional_arg_descriptor_t *pos_arg = &config->positional_args[0];
97 if (pos_arg->section_heading && pos_arg->examples && pos_arg->num_examples > 0) {
98 (void)fprintf(desc, "%s:\n", pos_arg->section_heading);
99 for (size_t i = 0; i < pos_arg->num_examples; i++) {
100 (void)fprintf(desc, " %s\n", pos_arg->examples[i]);
101 }
102 (void)fprintf(desc, "\n");
103 }
104 }
105
106 // Generate options from builder configuration
107 options_config_print_usage(config, desc);
108
109 // Clean up the config
111}
const options_config_t * options_preset_server(const char *program_name, const char *description)
Get server mode options preset.
Definition presets.c:300

References options_config_t::description, positional_arg_descriptor_t::examples, positional_arg_descriptor_t::num_examples, options_config_t::num_positional_args, options_config_destroy(), options_config_print_usage(), options_preset_server(), options_config_t::positional_args, options_config_t::program_name, and positional_arg_descriptor_t::section_heading.

Referenced by action_help_server(), and usage().

◆ validate_opt_color_mode()

ASCIICHAT_API int validate_opt_color_mode ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate color mode string.

Parameters
value_strColor mode value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed color mode enum value on success, -1 on error

Valid values: auto, none, mono, 16, 16color, 256, 256color, truecolor, 24bit

Validate color mode string Returns parsed color mode on success, -1 on error

Definition at line 94 of file validation.c.

94 {
95 if (!value_str) {
96 if (error_msg) {
97 SAFE_SNPRINTF(error_msg, error_msg_size, "Color mode value is required");
98 }
99 return -1;
100 }
101
102 if (strcmp(value_str, "auto") == 0) {
103 return COLOR_MODE_AUTO;
104 }
105 if (strcmp(value_str, "none") == 0 || strcmp(value_str, "mono") == 0) {
106 return COLOR_MODE_NONE;
107 }
108 if (strcmp(value_str, "16") == 0 || strcmp(value_str, "16color") == 0) {
109 return COLOR_MODE_16_COLOR;
110 }
111 if (strcmp(value_str, "256") == 0 || strcmp(value_str, "256color") == 0) {
113 }
114 if (strcmp(value_str, "truecolor") == 0 || strcmp(value_str, "24bit") == 0) {
116 }
117 if (error_msg) {
118 SAFE_SNPRINTF(error_msg, error_msg_size,
119 "Invalid color mode '%s'. Valid modes: auto, none, mono, 16, 256, truecolor", value_str);
120 }
121 return -1;
122}
#define COLOR_MODE_16_COLOR
16-color mode (full name)
Definition options.h:159
#define COLOR_MODE_256_COLOR
256-color mode (full name)
Definition options.h:161
#define COLOR_MODE_TRUECOLOR
24-bit truecolor mode
Definition options.h:162
#define COLOR_MODE_AUTO
Backward compatibility aliases for color mode enum values.
Definition options.h:156
#define COLOR_MODE_NONE
Monochrome mode.
Definition options.h:157

References COLOR_MODE_16_COLOR, COLOR_MODE_256_COLOR, COLOR_MODE_AUTO, COLOR_MODE_NONE, COLOR_MODE_TRUECOLOR, and SAFE_SNPRINTF.

◆ validate_opt_compression_level()

ASCIICHAT_API int validate_opt_compression_level ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate compression level (1-9)

Parameters
value_strCompression level as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed level on success, -1 on error

Validates zstd compression level in range 1-9.

Validate compression level (1-9) Returns parsed value on success, -1 on error

Definition at line 327 of file validation.c.

327 {
328 if (!value_str || strlen(value_str) == 0) {
329 if (error_msg) {
330 SAFE_SNPRINTF(error_msg, error_msg_size, "Compression level value is required");
331 }
332 return -1;
333 }
334
335 int level = strtoint_safe(value_str);
336 if (level == INT_MIN || level < 1 || level > 9) {
337 if (error_msg) {
338 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid compression level '%s'. Must be between 1 and 9.", value_str);
339 }
340 return -1;
341 }
342 return level;
343}

References SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_device_index()

ASCIICHAT_API int validate_opt_device_index ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate device index (-1 for default, 0+ for specific device)

Parameters
value_strDevice index as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed index on success, INT_MIN on error

Used for microphone-index, speakers-index, webcam-index. -1 means use system default device.

Validate device index (-1 for default, or 0+ for specific device) Returns parsed value on success, INT_MIN on error

Definition at line 422 of file validation.c.

422 {
423 if (!value_str || strlen(value_str) == 0) {
424 if (error_msg) {
425 SAFE_SNPRINTF(error_msg, error_msg_size, "Device index value is required");
426 }
427 return INT_MIN;
428 }
429
430 int index = strtoint_safe(value_str);
431 if (index == INT_MIN) {
432 if (error_msg) {
433 SAFE_SNPRINTF(error_msg, error_msg_size,
434 "Invalid device index '%s'. Must be -1 (default) or a non-negative integer.", value_str);
435 }
436 return INT_MIN;
437 }
438
439 // -1 is valid (system default), otherwise must be >= 0
440 if (index < -1) {
441 if (error_msg) {
442 SAFE_SNPRINTF(error_msg, error_msg_size,
443 "Invalid device index '%d'. Must be -1 (default) or a non-negative integer.", index);
444 }
445 return INT_MIN;
446 }
447 return index;
448}

References SAFE_SNPRINTF, and strtoint_safe().

Referenced by validate_webcam_index().

◆ validate_opt_float_non_negative()

ASCIICHAT_API float validate_opt_float_non_negative ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate non-negative float value.

Parameters
value_strFloat value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed float value on success, -1.0f on error

Validates that the string is a valid non-negative floating-point number.

Validate float value (non-negative) Returns parsed value on success, returns -1.0f on error (caller must check)

Definition at line 276 of file validation.c.

276 {
277 if (!value_str || strlen(value_str) == 0) {
278 if (error_msg) {
279 SAFE_SNPRINTF(error_msg, error_msg_size, "Value is required");
280 }
281 return -1.0f;
282 }
283
284 char *endptr;
285 float val = strtof(value_str, &endptr);
286 if (*endptr != '\0' || value_str == endptr) {
287 if (error_msg) {
288 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid float value '%s'. Must be a number.", value_str);
289 }
290 return -1.0f;
291 }
292 if (val < 0.0f) {
293 if (error_msg) {
294 SAFE_SNPRINTF(error_msg, error_msg_size, "Value must be non-negative (got %.2f)", val);
295 }
296 return -1.0f;
297 }
298 return val;
299}

References SAFE_SNPRINTF.

◆ validate_opt_fps()

ASCIICHAT_API int validate_opt_fps ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate FPS value (1-144)

Parameters
value_strFPS value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed FPS value on success, -1 on error

Validates that the FPS is in the valid range of 1-144.

Validate FPS value (1-144) Returns parsed value on success, -1 on error

Definition at line 349 of file validation.c.

349 {
350 if (!value_str || strlen(value_str) == 0) {
351 if (error_msg) {
352 SAFE_SNPRINTF(error_msg, error_msg_size, "FPS value is required");
353 }
354 return -1;
355 }
356
357 int fps_val = strtoint_safe(value_str);
358 if (fps_val == INT_MIN || fps_val < 1 || fps_val > 144) {
359 if (error_msg) {
360 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid FPS value '%s'. FPS must be between 1 and 144.", value_str);
361 }
362 return -1;
363 }
364 return fps_val;
365}

References SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_ip_address()

ASCIICHAT_API int validate_opt_ip_address ( const char *  value_str,
char *  parsed_address,
size_t  address_size,
bool  is_client,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate IP address or hostname.

Parameters
value_strIP address or hostname as string
parsed_addressBuffer to store resolved/parsed address
address_sizeSize of parsed_address buffer
is_clientTrue if client mode (for error messages)
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
0 on success, -1 on error

Validates IPv4, IPv6 addresses, or resolves hostname to IP.

Validate IP address or hostname Returns 0 on success, -1 on error Sets parsed_address on success (resolved if hostname)

Definition at line 224 of file validation.c.

225 {
226 (void)is_client; // Parameter not used but kept for API consistency
227 if (!value_str || strlen(value_str) == 0) {
228 if (error_msg) {
229 SAFE_SNPRINTF(error_msg, error_msg_size, "Address value is required");
230 }
231 return -1;
232 }
233
234 // Parse IPv6 address (remove brackets if present)
235 char parsed_addr[OPTIONS_BUFF_SIZE];
236 if (parse_ipv6_address(value_str, parsed_addr, sizeof(parsed_addr)) == 0) {
237 value_str = parsed_addr;
238 }
239
240 // Check if it's a valid IPv4 address
241 if (is_valid_ipv4(value_str)) {
242 SAFE_SNPRINTF(parsed_address, address_size, "%s", value_str);
243 return 0;
244 }
245 // Check if it's a valid IPv6 address
246 if (is_valid_ipv6(value_str)) {
247 SAFE_SNPRINTF(parsed_address, address_size, "%s", value_str);
248 return 0;
249 }
250 // Check if it looks like an invalid IP (has dots but not valid IPv4 format)
251 if (strchr(value_str, '.') != NULL) {
252 if (error_msg) {
253 SAFE_SNPRINTF(error_msg, error_msg_size,
254 "Invalid IP address format '%s'. IPv4 addresses must have exactly 4 octets.", value_str);
255 }
256 return -1;
257 }
258
259 // Otherwise, try to resolve as hostname
260 char resolved_ip[OPTIONS_BUFF_SIZE];
261 if (platform_resolve_hostname_to_ipv4(value_str, resolved_ip, sizeof(resolved_ip)) == 0) {
262 SAFE_SNPRINTF(parsed_address, address_size, "%s", resolved_ip);
263 return 0;
264 } else {
265 if (error_msg) {
266 SAFE_SNPRINTF(error_msg, error_msg_size, "Failed to resolve hostname '%s' to IP address.", value_str);
267 }
268 return -1;
269 }
270}
asciichat_error_t platform_resolve_hostname_to_ipv4(const char *hostname, char *ipv4_out, size_t ipv4_out_size)
Resolve hostname to IPv4 address.
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:22
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:77
int parse_ipv6_address(const char *input, char *output, size_t output_size)
Parse IPv6 address, removing brackets if present.
Definition ip.c:167

References is_valid_ipv4(), is_valid_ipv6(), OPTIONS_BUFF_SIZE, parse_ipv6_address(), platform_resolve_hostname_to_ipv4(), and SAFE_SNPRINTF.

◆ validate_opt_log_level()

ASCIICHAT_API int validate_opt_log_level ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate log level string.

Parameters
value_strLog level as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed log level enum value on success, -1 on error

Valid values (case-insensitive): dev, debug, info, warn, error, fatal

Validate log level string Returns parsed log level on success, -1 on error

Definition at line 190 of file validation.c.

190 {
191 if (!value_str) {
192 if (error_msg) {
193 SAFE_SNPRINTF(error_msg, error_msg_size, "Log level value is required");
194 }
195 return -1;
196 }
197
198 if (platform_strcasecmp(value_str, "dev") == 0) {
199 return LOG_DEV;
200 } else if (platform_strcasecmp(value_str, "debug") == 0) {
201 return LOG_DEBUG;
202 } else if (platform_strcasecmp(value_str, "info") == 0) {
203 return LOG_INFO;
204 } else if (platform_strcasecmp(value_str, "warn") == 0) {
205 return LOG_WARN;
206 } else if (platform_strcasecmp(value_str, "error") == 0) {
207 return LOG_ERROR;
208 } else if (platform_strcasecmp(value_str, "fatal") == 0) {
209 return LOG_FATAL;
210 } else {
211 if (error_msg) {
212 SAFE_SNPRINTF(error_msg, error_msg_size,
213 "Invalid log level '%s'. Valid levels: dev, debug, info, warn, error, fatal", value_str);
214 }
215 return -1;
216 }
217}
@ LOG_ERROR
Definition log/logging.h:64
@ LOG_INFO
Definition log/logging.h:62
@ LOG_DEBUG
Definition log/logging.h:61
@ LOG_FATAL
Definition log/logging.h:65
@ LOG_WARN
Definition log/logging.h:63

References LOG_DEBUG, LOG_DEV, LOG_ERROR, LOG_FATAL, LOG_INFO, LOG_WARN, platform_strcasecmp(), and SAFE_SNPRINTF.

Referenced by parse_log_level_option().

◆ validate_opt_max_clients()

ASCIICHAT_API int validate_opt_max_clients ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate max clients value (1-32)

Parameters
value_strMax clients value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed value on success, -1 on error

Validates that the max clients is in the valid range of 1-32.

Validate max clients (1-32) Returns parsed value on success, -1 on error

Definition at line 305 of file validation.c.

305 {
306 if (!value_str || strlen(value_str) == 0) {
307 if (error_msg) {
308 SAFE_SNPRINTF(error_msg, error_msg_size, "Max clients value is required");
309 }
310 return -1;
311 }
312
313 int max = strtoint_safe(value_str);
314 if (max == INT_MIN || max < 1 || max > 32) {
315 if (error_msg) {
316 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid max clients '%s'. Must be between 1 and 32.", value_str);
317 }
318 return -1;
319 }
320 return max;
321}

References SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_non_negative_int()

ASCIICHAT_API int validate_opt_non_negative_int ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate non-negative integer.

Parameters
value_strInteger value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed value on success, -1 on error

Validates that the string is a non-negative integer (>= 0).

Validate non-negative integer Returns parsed value on success, -1 on error

Definition at line 72 of file validation.c.

72 {
73 if (!value_str || strlen(value_str) == 0) {
74 if (error_msg) {
75 SAFE_SNPRINTF(error_msg, error_msg_size, "Value is required");
76 }
77 return -1;
78 }
79
80 int val = strtoint_safe(value_str);
81 if (val == INT_MIN || val < 0) {
82 if (error_msg) {
83 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid value '%s'. Must be a non-negative integer.", value_str);
84 }
85 return -1;
86 }
87 return val;
88}

References SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_palette()

ASCIICHAT_API int validate_opt_palette ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate palette type string.

Parameters
value_strPalette type as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed palette type enum value on success, -1 on error

Valid values: standard, blocks, digital, minimal, cool, custom

Validate palette type string Returns parsed palette type on success, -1 on error

Definition at line 156 of file validation.c.

156 {
157 if (!value_str) {
158 if (error_msg) {
159 SAFE_SNPRINTF(error_msg, error_msg_size, "Palette value is required");
160 }
161 return -1;
162 }
163
164 if (strcmp(value_str, "standard") == 0) {
165 return PALETTE_STANDARD;
166 } else if (strcmp(value_str, "blocks") == 0) {
167 return PALETTE_BLOCKS;
168 } else if (strcmp(value_str, "digital") == 0) {
169 return PALETTE_DIGITAL;
170 } else if (strcmp(value_str, "minimal") == 0) {
171 return PALETTE_MINIMAL;
172 } else if (strcmp(value_str, "cool") == 0) {
173 return PALETTE_COOL;
174 } else if (strcmp(value_str, "custom") == 0) {
175 return PALETTE_CUSTOM;
176 } else {
177 if (error_msg) {
178 SAFE_SNPRINTF(error_msg, error_msg_size,
179 "Invalid palette '%s'. Valid palettes: standard, blocks, digital, minimal, cool, custom",
180 value_str);
181 }
182 return -1;
183 }
184}
@ PALETTE_BLOCKS
Unicode block characters: " ░░▒▒▓▓██".
Definition palette.h:88
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:96
@ PALETTE_COOL
Ascending blocks: " ▁▂▃▄▅▆▇█".
Definition palette.h:94
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:86
@ PALETTE_DIGITAL
Digital/glitch aesthetic: " -=≡≣▰▱◼".
Definition palette.h:90
@ PALETTE_MINIMAL
Simple ASCII: " .-+*#".
Definition palette.h:92

References PALETTE_BLOCKS, PALETTE_COOL, PALETTE_CUSTOM, PALETTE_DIGITAL, PALETTE_MINIMAL, PALETTE_STANDARD, and SAFE_SNPRINTF.

◆ validate_opt_password()

ASCIICHAT_API int validate_opt_password ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate password (8-256 characters)

Parameters
value_strPassword string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
0 on success, -1 on error

Validates password length is 8-256 characters and contains no null bytes.

Validate password (8-256 characters, no null bytes) Returns 0 on success, -1 on error

Definition at line 454 of file validation.c.

454 {
455 if (!value_str) {
456 if (error_msg) {
457 SAFE_SNPRINTF(error_msg, error_msg_size, "Password value is required");
458 }
459 return -1;
460 }
461
462 size_t len = strlen(value_str);
463 if (len < 8) {
464 if (error_msg) {
465 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too short (%zu chars). Must be at least 8 characters.", len);
466 }
467 return -1;
468 }
469 if (len > 256) {
470 if (error_msg) {
471 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too long (%zu chars). Must be at most 256 characters.", len);
472 }
473 return -1;
474 }
475
476 // Note: No need to check for embedded null bytes - strlen() already stopped at the first null,
477 // so by definition there are no null bytes within [0, len).
478
479 return 0;
480}

References SAFE_SNPRINTF.

◆ validate_opt_port()

ASCIICHAT_API int validate_opt_port ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate port number (1-65535)

Parameters
value_strPort number as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
0 on success, -1 on error

Validates that the port string is a valid number in the range 1-65535.

Validate port number (1-65535) Returns 0 on success, non-zero on error

Definition at line 26 of file validation.c.

26 {
27 if (!value_str || strlen(value_str) == 0) {
28 if (error_msg) {
29 SAFE_SNPRINTF(error_msg, error_msg_size, "Port value is required");
30 }
31 return -1;
32 }
33
34 // Use safe integer parsing with range validation
35 uint16_t port_num;
36 if (parse_port(value_str, &port_num) != ASCIICHAT_OK) {
37 if (error_msg) {
38 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid port value '%s'. Port must be a number between 1 and 65535.",
39 value_str);
40 }
41 return -1;
42 }
43 return 0;
44}
unsigned short uint16_t
Definition common.h:57
asciichat_error_t parse_port(const char *str, uint16_t *out_port)
Parse port number (1-65535) from string.
Definition parsing.c:221

References ASCIICHAT_OK, parse_port(), and SAFE_SNPRINTF.

◆ validate_opt_positive_int()

ASCIICHAT_API int validate_opt_positive_int ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate positive integer.

Parameters
value_strInteger value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed value on success, -1 on error

Validates that the string is a positive integer (> 0).

Validate positive integer Returns parsed value on success, -1 on error

Definition at line 50 of file validation.c.

50 {
51 if (!value_str || strlen(value_str) == 0) {
52 if (error_msg) {
53 SAFE_SNPRINTF(error_msg, error_msg_size, "Value is required");
54 }
55 return -1;
56 }
57
58 int val = strtoint_safe(value_str);
59 if (val == INT_MIN || val <= 0) {
60 if (error_msg) {
61 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid value '%s'. Must be a positive integer.", value_str);
62 }
63 return -1;
64 }
65 return val;
66}

References SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_reconnect()

ASCIICHAT_API int validate_opt_reconnect ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate reconnect value.

Parameters
value_strReconnect value as string ("off", "auto", or 0-999)
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
0 for off, -1 for auto, 1-999 for count, INT_MIN on error

Valid values:

  • "off" or "0": No reconnection (returns 0)
  • "auto" or "-1": Unlimited reconnection (returns -1)
  • "1" to "999": Retry count (returns the count)

Validate reconnect value (off, auto, 0, -1, or 1-999) Returns: 0 for "off" (no retries) -1 for "auto" (unlimited retries) 1-999 for specific retry count INT_MIN on parse error

Definition at line 375 of file validation.c.

375 {
376 if (!value_str || strlen(value_str) == 0) {
377 if (error_msg) {
378 SAFE_SNPRINTF(error_msg, error_msg_size, "Reconnect value is required");
379 }
380 return INT_MIN;
381 }
382
383 // Check for string values first
384 if (platform_strcasecmp(value_str, "off") == 0) {
385 return 0; // No retries
386 }
387 if (platform_strcasecmp(value_str, "auto") == 0) {
388 return -1; // Unlimited retries
389 }
390
391 // Parse as integer
392 int val = strtoint_safe(value_str);
393 if (val == INT_MIN) {
394 if (error_msg) {
395 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect value '%s'. Use 'off', 'auto', or a number 0-999.",
396 value_str);
397 }
398 return INT_MIN;
399 }
400
401 // 0 means off, -1 means auto, 1-999 is valid range
402 if (val == 0) {
403 return 0; // No retries
404 }
405 if (val == -1) {
406 return -1; // Unlimited retries
407 }
408 if (val < 1 || val > 999) {
409 if (error_msg) {
410 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect count '%s'. Must be 'off', 'auto', or 1-999.",
411 value_str);
412 }
413 return INT_MIN;
414 }
415 return val;
416}

References platform_strcasecmp(), SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_render_mode()

ASCIICHAT_API int validate_opt_render_mode ( const char *  value_str,
char *  error_msg,
size_t  error_msg_size 
)

#include <validation.h>

Validate render mode string.

Parameters
value_strRender mode value as string
error_msgBuffer for error message (can be NULL)
error_msg_sizeSize of error message buffer
Returns
Parsed render mode enum value on success, -1 on error

Valid values: foreground, fg, background, bg, half-block, halfblock

Validate render mode string Returns parsed render mode on success, -1 on error

Definition at line 128 of file validation.c.

128 {
129 if (!value_str) {
130 if (error_msg) {
131 SAFE_SNPRINTF(error_msg, error_msg_size, "Render mode value is required");
132 }
133 return -1;
134 }
135
136 if (strcmp(value_str, "foreground") == 0 || strcmp(value_str, "fg") == 0) {
138 }
139 if (strcmp(value_str, "background") == 0 || strcmp(value_str, "bg") == 0) {
141 }
142 if (strcmp(value_str, "half-block") == 0 || strcmp(value_str, "halfblock") == 0) {
144 }
145 if (error_msg) {
146 SAFE_SNPRINTF(error_msg, error_msg_size,
147 "Invalid render mode '%s'. Valid modes: foreground, background, half-block", value_str);
148 }
149 return -1;
150}
@ RENDER_MODE_FOREGROUND
Foreground colors only (text color)
Definition terminal.h:469
@ RENDER_MODE_BACKGROUND
Background colors (block colors)
Definition terminal.h:471
@ RENDER_MODE_HALF_BLOCK
Unicode half-block characters (mixed foreground/background)
Definition terminal.h:473

References RENDER_MODE_BACKGROUND, RENDER_MODE_FOREGROUND, RENDER_MODE_HALF_BLOCK, and SAFE_SNPRINTF.

Variable Documentation

◆ BLUE

unsigned short int BLUE[]
extern

#include <options.h>

Blue channel lookup table.

Lookup table for blue channel values. See RED[] for details.

Definition at line 354 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ GRAY

unsigned short int GRAY[]
extern

#include <options.h>

Grayscale lookup table.

Lookup table for grayscale values. Used for monochrome ASCII conversion when color information is not needed or available.

Definition at line 355 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ GREEN

unsigned short int GREEN[]
extern

#include <options.h>

Green channel lookup table.

Lookup table for green channel values. See RED[] for details.

Definition at line 353 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ opt_acds_database_path

ASCIICHAT_API char opt_acds_database_path[OPTIONS_BUFF_SIZE]
extern

#include <acds.h>

SQLite database path (ACDS mode only)

Path to SQLite database for session storage and management.

Default: ~/.config/ascii-chat/acds.db

Command-line: --database <path> or -d <path>

Note
ACDS mode only

Definition at line 41 of file acds.c.

Referenced by main(), and parse_acds_options().

◆ opt_acds_key_path

ASCIICHAT_API char opt_acds_key_path[OPTIONS_BUFF_SIZE]
extern

#include <acds.h>

Ed25519 identity key path (ACDS mode only)

Path to Ed25519 identity key for server identity.

Default: ~/.config/ascii-chat/acds_identity

Command-line: --key <path> or -k <path>

Note
ACDS mode only

Definition at line 42 of file acds.c.

Referenced by main(), and parse_acds_options().

◆ opt_acds_port

ASCIICHAT_API int opt_acds_port
extern

#include <acds.h>

TCP listen port (ACDS mode only)

Port number for the discovery service to listen on.

Default: 27225 (ACDS default port)

Command-line: --port <port> or -p <port>

Note
ACDS mode only

Definition at line 40 of file acds.c.

Referenced by main().

◆ RED

unsigned short int RED[]
extern

#include <options.h>

Red channel lookup table.

Lookup table for red channel values. Used for efficient color-to-ASCII character mapping. Precomputed table for fast palette lookups.

Usage: These lookup tables are used internally by the ASCII conversion algorithm for efficient color mapping.

Note
These are internal implementation details
Tables are precomputed based on palette and color mode
Access these tables via palette functions, not directly

Definition at line 352 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ weight_blue

const float weight_blue
extern

#include <options.h>

Blue weight for luminance calculation.

Weight for blue channel in luminance calculation. See weight_red for details.

Default: Typically 0.114 (standard ITU-R BT.601 weights)

Definition at line 348 of file options/common.c.

Referenced by server_main().

◆ weight_green

const float weight_green
extern

#include <options.h>

Green weight for luminance calculation.

Weight for green channel in luminance calculation. See weight_red for details.

Default: Typically 0.587 (standard ITU-R BT.601 weights)

Definition at line 347 of file options/common.c.

Referenced by server_main().

◆ weight_red

const float weight_red
extern

#include <options.h>

Definition at line 346 of file options/common.c.

Referenced by server_main().