ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
Options Module

⚙️ Command-line option parsing with unified mode detection, builder API, and RCU-based thread-safe access More...

Files

file  colorscheme.c
 Color scheme management implementation and early initialization.
file  common.c
 Common utilities and helpers for option parsing.
file  bash.c
 Bash shell completion script generator.
file  completions.c
 Implementation of shell completion generation from options registry.
file  fish.c
 Fish shell completion script generator.
file  powershell.c
 PowerShell completion script generator.
file  zsh.c
 Zsh shell completion script generator with described values.
file  presets.c
 Preset option configurations for ascii-chat modes.
file  schema.c
 Schema metadata registry for config file options.
file  help_api.c
 Public API for retrieving option help text.
file  manpage.c
 Man page generation using modular architecture.
file  core.c
 ⚙️ Main entry point for unified options parsing with mode detection
file  actions.c
 Action option callbacks for ascii-chat.
file  parsers.c
 Custom option parsers implementation.
file  audio.c
 Audio processing options.
file  categories.h
 Extern declarations for all category entry arrays.
file  common.h
 Shared structures and macros for registry implementation.
file  configuration.c
 Configuration file options.
file  core.h
 Internal helper functions and data for registry implementation.
file  database.c
 Discovery service database options.
file  debug.c
 Debug options registry (backtrace, sync-state).
file  display.c
 Display layout and rendering options.
file  general.c
 General options.
file  logging.c
 Logging category options.
file  media.c
 Media file and stream options.
file  mode_defaults.c
 Mode-aware default value getters for options.
file  mode_defaults.h
 Mode-aware default value getters and mode metadata.
file  network.c
 Network protocol options.
file  public_api.c
 Public API functions for the options registry.
file  registry.c
 Master registry composition - combines all category arrays.
file  registry.h
 Central registry of all command-line options with mode applicability.
file  security.c
 Security and authentication options.
file  terminal.c
 Terminal display options.
file  webcam.c
 Webcam capture options.
file  strings.c
 Centralized enum and mode string conversion - single source of truth.
file  actions.h
 Action option callbacks for ascii-chat.
file  builder.h
 Options builder API for flexible command-line option configuration.
file  common.h
 Common utilities and helpers for option parsing across all modes.
file  bash.h
 Bash shell completion generator.
file  completions.h
 Auto-generated shell completions from options registry.
file  fish.h
 Fish shell completion generator.
file  powershell.h
 PowerShell completion generator.
file  zsh.h
 Zsh shell completion generator.
file  enums.h
 Option enum value definitions - single source of truth.
file  explicit.h
 Check if an option was explicitly set via command-line.
file  groups.h
 Option group definitions for composable mode presets.
file  levenshtein.h
 Levenshtein distance algorithm for fuzzy string matching.
file  manpage.h
 Man page template generation from options builder.
file  options.h
 ⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
file  parsers.h
 Custom option parsers for enum types.
file  presets.h
 Preset option configurations for ascii-chat modes.
file  registry.h
 Central registry of all command-line options with mode applicability.
file  categories.h
 Extern declarations for all category entry arrays.
file  common.h
 Shared structures and macros for registry implementation.
file  core.h
 Internal helper functions and data for registry implementation.
file  mode_defaults.h
 Mode-aware default value getters and mode metadata.
file  schema.h
 Schema metadata for config file options.
file  strings.h
 Centralized enum and mode string conversion API.
file  validation.h
 Validation functions for options parsing.

Data Structures

struct  options_state
 Immutable, RCU-published snapshot of the application's runtime configuration. More...

Macros

#define MODE_SERVER_GROUPS
 Mode group presets.
#define LEVENSHTEIN_SUGGESTION_THRESHOLD   4
 Maximum edit distance to suggest an option.
#define OPTIONS_YT_DLP_OPTIONS_BUFFER_SIZE   512
#define OPTIONS_COLOR_SCHEME_NAME_BUFFER_SIZE   64
#define OPTIONS_VIDEO_CODEC_BUFFER_SIZE   64
#define OPTIONS_PALETTE_CUSTOM_BUFFER_SIZE   256
#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 OPT_WEBRTC_DEFAULT   true
 Default WebRTC mode flag (true = P2P WebRTC, false = direct TCP).
#define OPT_PREFER_WEBRTC_DEFAULT   false
 Default prefer WebRTC flag (false = try direct TCP first).
#define OPT_NO_WEBRTC_DEFAULT   false
 Default no WebRTC flag (false = WebRTC enabled).
#define OPT_WEBRTC_SKIP_STUN_DEFAULT   false
 Default WebRTC skip STUN flag (false = use STUN).
#define OPT_WEBRTC_DISABLE_TURN_DEFAULT   false
 Default WebRTC disable TURN flag (false = use TURN).
#define OPT_WEBRTC_SKIP_HOST_DEFAULT   false
 Default WebRTC skip host candidates flag (false = use host candidates).
#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT   10000
 Default WebRTC ICE gathering timeout in milliseconds (10 seconds).
#define OPT_WEBRTC_RECONNECT_ATTEMPTS_DEFAULT   3
 Default WebRTC reconnection attempts (3 = try initial + 3 retries).
#define OPT_TURN_USERNAME_DEFAULT   ""
 Default TURN username (empty = use ACDS credentials).
#define OPT_TURN_CREDENTIAL_DEFAULT   ""
 Default TURN credential (empty = use ACDS credentials).
#define OPT_AUDIO_ENABLED_DEFAULT   true
 Default audio enabled flag (true = audio enabled by default).
#define OPT_AUDIO_SOURCE_DEFAULT   AUDIO_SOURCE_ALL
 Visualize all available sources by default.
#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT   AUDIO_CAPTURE_SOURCE_AUTO
 Preserve automatic local audio capture selection by default.
#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_MICROPHONE_SENSITIVITY_DEFAULT   1.0
 Default microphone sensitivity (1.0 = normal volume).
#define OPT_SPEAKERS_VOLUME_DEFAULT   1.0
 Default speakers volume (1.0 = normal volume).
#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT   false
 Default audio analysis enabled flag.
#define OPT_AUDIO_NO_PLAYBACK_DEFAULT   false
 Default audio playback flag (false = enable playback).
#define OPT_ENCODE_AUDIO_DEFAULT   true
 Default audio encoding state (true = Opus encoding enabled).
#define OPT_ENCRYPT_ENABLED_DEFAULT   false
 Default encrypt enabled flag (true = encryption required).
#define OPT_NO_ENCRYPT_DEFAULT   false
 Default no encrypt flag (false = allow encryption).
#define OPT_NO_AUTH_DEFAULT   false
 Default no auth flag (false = allow authentication).
#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT   false
 Default require server verify flag (false = not required).
#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT   false
 Default require client verify flag (false = not required).
#define OPT_STRING_EMPTY_DEFAULT   ""
 Default empty string for string option fields that have no configured value.
#define OPT_RENDER_FILE_DEFAULT   ""
#define OPT_RENDER_THEME_DEFAULT   0
#define OPT_RENDER_FONT_DEFAULT   ""
#define OPT_RENDER_FONT_SIZE_DEFAULT   0.0
#define OPTION_MODE_SERVER_LIKE   (OPTION_MODE_SERVER | OPTION_MODE_DISCOVERY_SVC)
 Mode group macros for examples.
#define OPTION_MODE_CLIENT_LIKE   (OPTION_MODE_CLIENT | OPTION_MODE_MIRROR | OPTION_MODE_DISCOVERY)
#define OPTION_MODE_NETWORKED   (OPTION_MODE_SERVER | OPTION_MODE_CLIENT | OPTION_MODE_DISCOVERY_SVC | OPTION_MODE_DISCOVERY)
#define ASCII_RENDERER_DEFAULT   ASCII_RENDERER_GLYPH
 Consolidated options structure.
#define options_terminal_settings()
#define ASCIICHAT_OPTION_FIELD_TYPE(field)
 Safely get a specific option field (lock-free read).
#define GET_OPTION(field)

Typedefs

typedef struct options_state options_t
 Immutable, RCU-published snapshot of the application's runtime configuration.

Enumerations

enum  option_group_t {
  OPT_GROUP_NONE = 0 , OPT_GROUP_BINARY , OPT_GROUP_TERMINAL = (1 << 1) , OPT_GROUP_NETWORK = (1 << 2) ,
  OPT_GROUP_WEBCAM = (1 << 3) , OPT_GROUP_DISPLAY , OPT_GROUP_AUDIO = (1 << 5) , OPT_GROUP_SNAPSHOT = (1 << 6) ,
  OPT_GROUP_CRYPTO = (1 << 7) , OPT_GROUP_COMPRESSION = (1 << 8) , OPT_GROUP_ACDS = (1 << 9) , OPT_GROUP_MEDIA = (1 << 10) ,
  OPT_GROUP_SERVER , OPT_GROUP_CLIENT , OPT_GROUP_WEBRTC = (1 << 13)
}
 Option group identifiers. More...
enum  color_setting_t { COLOR_SETTING_AUTO = 0 , COLOR_SETTING_TRUE = 1 , COLOR_SETTING_FALSE = -1 }
 For options state, this is the live record that ties detected_mode, mode_arg_index, help, version together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record. More...
enum  utf8_setting_t { UTF8_SETTING_AUTO = 0 , UTF8_SETTING_TRUE = 1 , UTF8_SETTING_FALSE = -1 }
 UTF-8 support setting (–utf8 flag values). More...
enum  audio_source_t {
  AUDIO_SOURCE_ALL = 0 , AUDIO_SOURCE_CALL = 1 , AUDIO_SOURCE_MIC = 2 , AUDIO_SOURCE_MEDIA = 3 ,
  AUDIO_SOURCE_AUTO = AUDIO_SOURCE_ALL
}
 Audio source selected for visualization. More...
enum  audio_capture_source_t {
  AUDIO_CAPTURE_SOURCE_AUTO = 0 , AUDIO_CAPTURE_SOURCE_MIC = 1 , AUDIO_CAPTURE_SOURCE_MEDIA = 2 , AUDIO_CAPTURE_SOURCE_BOTH = 3 ,
  AUDIO_CAPTURE_SOURCE_REMOTE = 4
}
enum  asciichat_mode_t {
  MODE_SERVER , MODE_CLIENT , MODE_MIRROR , MODE_DISCOVERY_SERVICE ,
  MODE_DISCOVERY , MODE_MCP_SERVER , MODE_API_SERVER , MODE_INVALID
}
 Mode type for options parsing. More...
enum  option_mode_bitmask_t {
  OPTION_MODE_NONE = 0 , OPTION_MODE_SERVER = (1 << MODE_SERVER) , OPTION_MODE_CLIENT = (1 << MODE_CLIENT) , OPTION_MODE_MIRROR = (1 << MODE_MIRROR) ,
  OPTION_MODE_DISCOVERY_SVC = (1 << MODE_DISCOVERY_SERVICE) , OPTION_MODE_DISCOVERY = (1 << MODE_DISCOVERY) , OPTION_MODE_MCP_SERVER = (1 << MODE_MCP_SERVER) , OPTION_MODE_API_SERVER = (1 << MODE_API_SERVER) ,
  OPTION_MODE_BINARY = 0x100 , OPTION_MODE_ALL = 0x7F | 0x100
}
 Option mode bitmask. More...

Functions

size_t levenshtein (const char *a, const char *b)
 Calculate Levenshtein distance between two strings.
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.
const char * levenshtein_find_similar (const char *unknown, const char *const *candidates)
 Find the most similar string from a NULL-terminated array.
asciichat_error_t options_config_generate_manpage_template (const options_config_t *config, const char *program_name, const char *mode_name, const char *output_path, const char *brief_description)
 Generate a man page template from options builder configuration.
asciichat_error_t options_builder_generate_manpage_template (options_builder_t *builder, const char *program_name, const char *mode_name, const char *output_path, const char *brief_description)
 Generate man page template from builder (before build()).
asciichat_error_t options_config_generate_manpage_merged (const options_config_t *config, const char *program_name, const char *mode_name, const char *output_path, const char *brief_description)
 Generate merged man page template preserving manual content.
parsed_section_t * parse_manpage_sections (const char *filepath, size_t *num_sections)
 Parse existing man page template to extract sections.
void free_parsed_sections (parsed_section_t *sections, size_t num_sections)
 Free parsed sections array.
const parsed_section_t * find_section (const parsed_section_t *sections, size_t num_sections, const char *section_name)
 Find section by name.
asciichat_error_t options_config_generate_final_manpage (const char *template_path, const char *output_path, const char *version_string, const char *content_file_path)
 Generate final man page (.1) from template (.1.in) with version substitution and optional content file.
const char * escape_groff_special (const char *str)
 Escape special groff/troff characters in text.
const char * format_mode_names (option_mode_bitmask_t bitmask)
 Format option mode names as human-readable string.
const options_t * options_get (void)
 Get current options (lock-free read).
const terminal_options_t * options_terminal_settings_ptr (void)
asciichat_error_t options_set_int (const char *field_name, int value)
 Check if an option was explicitly set via command-line.
asciichat_error_t options_set_bool (const char *field_name, bool value)
asciichat_error_t options_set_string (const char *field_name, const char *value)
asciichat_error_t options_set_double (const char *field_name, double value)
const char * options_get_help_text (asciichat_mode_t mode, const char *option_name)
 Get help text for an option in a specific mode.
bool has_action_flag (void)
 Check if an action flag was detected.
asciichat_error_t validate_glyph_palette (const options_t *opts)

Variables

const float weight_red
 Red weight for luminance calculation.
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

options_t options_t_new (void)
 Initialize options by parsing command-line arguments.
asciichat_error_t options_init (int argc, char **argv)
 Initialize options by parsing command-line arguments with unified mode detection.
void usage (FILE *stream, asciichat_mode_t mode)
 Print usage information for a specific mode.

Dimension Update Functions

void update_dimensions_to_terminal_size (options_t *opts)
 Update dimensions to match current terminal size.
void update_dimensions_for_full_height (options_t *opts)
 Update dimensions to use full terminal height while maintaining aspect ratio.

Validation Functions

int validate_opt_port (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate port number (1-65535).
int validate_opt_positive_int (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate positive integer.
int validate_opt_non_negative_int (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate non-negative integer.
int validate_opt_color_mode (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate color mode string.
int validate_opt_render_mode (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate render mode string.
int validate_opt_palette (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate palette type string.
int validate_opt_log_level (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate log level string.
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.
float validate_opt_float_non_negative (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate non-negative float value.
float validate_opt_volume (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate volume value (0.0-1.0).
int validate_opt_fps (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate FPS value (0 for auto, otherwise 1-144).
int validate_opt_max_clients (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate max clients value (1-128).
int validate_opt_compression_level (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate compression level (1-9).
int validate_opt_reconnect (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate reconnect value.
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).
int validate_opt_password (const char *value_str, char *error_msg, size_t error_msg_size)
 Validate password (8-256 characters).
int options_collect_identity_keys (options_t *opts, int argc, char *argv[])
 Collect multiple –key flags into identity_keys array.
bool is_remote_key_path (const char *key_path)
 Check if a key path is a remote/virtual key (not a local file).

Configuration Constants

#define OPTIONS_BUFF_SIZE   256
 Buffer size for option string values.
#define OPT_HELP_DEFAULT   false
 Default help flag (false = don't show help).
#define OPT_VERSION_DEFAULT   false
 Default version flag (false = don't show version).
#define OPT_SPLASH_DEFAULT   true
 Default splash screen flag (true = show splash, false = hide splash).
#define OPT_SPLASH_SCREEN_EXPLICITLY_SET_DEFAULT   false
 Default splash screen explicitly set flag (false = use default splash setting).
#define OPT_STATUS_SCREEN_DEFAULT   true
 Default status screen flag (true = show status, false = hide status).
#define OPT_STATUS_SCREEN_EXPLICITLY_SET_DEFAULT   false
 Default status screen explicitly set flag (false = use default status screen setting).
#define OPT_ENABLE_KEEPAWAKE_DEFAULT   false
 Default keep-awake (prevent system sleep) flag (false = normal system sleep).
#define OPT_DISABLE_KEEPAWAKE_DEFAULT   false
 Default disable keep-awake flag (false = allow system sleep prevention).
#define OPT_NO_CHECK_UPDATE_DEFAULT   false
 Default no-check-update flag (false = check for updates enabled).
#define OPT_QUIET_DEFAULT   false
 Default quiet mode flag (false = logging enabled).
#define OPT_OTEL_ENDPOINT_DEFAULT   ""
 Debug and Dev builds export to the local Spaniel Compose collector.
#define OPT_VERBOSE_LEVEL_DEFAULT   0
 Default verbose level (0 = not verbose).
#define OPT_LOG_LEVEL_DEFAULT   LOG_INFO
 Default log level (LOG_INFO).
#define OPT_GREP_PATTERN_DEFAULT   ""
 Default grep pattern (empty = no filtering).
#define OPT_JSON_DEFAULT   false
 Default JSON logging flag (false = text output).
#define OPT_COLOR_SCHEME_NAME_DEFAULT   "pastel"
 Default color scheme name (pastel).
#define OPT_LOG_TEMPLATE_DEFAULT_RELEASE
 Default log format string - release mode (simple format with timestamp, level, and message).
#define OPT_LOG_TEMPLATE_DEFAULT_DEBUG
 Default log format string - debug mode (verbose with thread name, file relative path, line, and function).
#define OPT_LOG_TEMPLATE_DEFAULT   OPT_LOG_TEMPLATE_DEFAULT_DEBUG
 Default log template string (selected based on build mode).
#define OPT_LOG_FORMAT_OUTPUT_DEFAULT   LOG_OUTPUT_TEXT
 Default log format output type (TEXT = human-readable, JSON = structured).
#define OPT_LOG_FORMAT_CONSOLE_DEFAULT   false
 Default log format console only flag (false = use default format everywhere).
#define OPT_WIDTH_DEFAULT   110
 Default terminal width in characters.
#define OPT_HEIGHT_DEFAULT   70
 Default terminal height in characters.
#define OPT_AUTO_WIDTH_DEFAULT   true
 Default auto-detect width flag (true = auto-detect from terminal).
#define OPT_AUTO_HEIGHT_DEFAULT   true
 Default auto-detect height flag (true = auto-detect from terminal).
#define OPT_COLOR_MODE_DEFAULT   COLOR_MODE_AUTO
 Default color mode (auto-detect terminal capabilities).
#define OPT_LIST_WEBCAMS_DEFAULT   false
 Default list webcams flag (false = don't list and exit).
#define OPT_LIST_MICROPHONES_DEFAULT   false
 Default list microphones flag (false = don't list and exit).
#define OPT_LIST_SPEAKERS_DEFAULT   false
 Default list speakers flag (false = don't list and exit).
#define OPT_SHOW_CAPABILITIES_DEFAULT   false
 Default show terminal capabilities flag.
#define OPT_FORCE_UTF8_DEFAULT   UTF8_SETTING_AUTO
 Default force UTF-8 support setting (auto-detect).
#define OPT_STRIP_ANSI_DEFAULT   false
 Default strip ANSI escape sequences flag.
#define OPT_COLOR_DEFAULT   COLOR_SETTING_AUTO
 Default color setting (COLOR_SETTING_AUTO = smart detection).
#define OPT_COLOR_FILTER_DEFAULT   COLOR_FILTER_NONE
 Default color filter (none - no filtering).
#define OPT_RENDER_MODE_DEFAULT   RENDER_MODE_FOREGROUND
 Default render mode (foreground characters only).
#define OPT_PALETTE_TYPE_DEFAULT   PALETTE_STANDARD
 Default palette type (standard ASCII art).
#define OPT_PALETTE_CUSTOM_SET_DEFAULT   false
 Default custom palette set flag (false = not set).
#define OPT_STRETCH_DEFAULT   false
 Default allow aspect ratio distortion flag.
#define OPT_FPS_DEFAULT   0
 Default FPS (frames per second).
#define OPT_SNAPSHOT_MODE_DEFAULT   false
 Default snapshot mode flag (false = continuous).
#define OPT_SNAPSHOT_DELAY_DEFAULT   3.0f
 Default snapshot delay in seconds.
#define OPT_MATRIX_RAIN_DEFAULT   false
 Default Matrix rain effect flag (false = disabled).
#define OPT_FPS_COUNTER_DEFAULT   false
 Default FPS counter overlay flag (false = disabled).
#define OPT_FLIP_X_DEFAULT   true
 Webcam input is mirrored unless an orientation is explicitly selected.
#define OPT_FLIP_Y_DEFAULT   false
 Default vertical flip state (false = no vertical flip).
#define OPT_WEBCAM_INDEX_DEFAULT   0
 Default webcam device index.
#define OPT_TEST_PATTERN_DEFAULT   false
 Default test pattern mode (false = use actual webcam).
#define OPT_NO_AUDIO_MIXER_DEFAULT   false
 Default no audio mixer flag (false = enable mixer).
#define OPT_MEDIA_LOOP_DEFAULT   false
 Default loop media flag (false = play once).
#define OPT_MEDIA_FROM_STDIN_DEFAULT   false
 Default media from stdin flag (false = not reading from stdin).
#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT   0.0
 Default media seek timestamp (start from beginning).
#define OPT_PAUSE_DEFAULT   false
 Default pause media flag (false = play immediately).
#define OPT_ADDRESS_DEFAULT   "localhost"
 Default server address for client connections.
#define OPT_ADDRESS6_DEFAULT   "::1"
 Default IPv6 server address.
#define OPT_ENDPOINT_DISCOVERY_SERVICE   "localhost"
 Default discovery service endpoint (what to connect to by default).
#define OPT_PORT_DEFAULT   "27224"
 Default TCP port for client/server communication (string).
#define OPT_PORT_INT_DEFAULT   27224
 Default TCP port for client/server communication (integer).
#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT   27226
 Default WebSocket port for server mode (integer).
#define OPT_WEBSOCKET_PORT_ACDS_DEFAULT   27227
 Default WebSocket port for discovery-service mode (integer).
#define OPT_MCP_PORT_DEFAULT   27228
#define OPT_MAX_CLIENTS_DEFAULT   9
 Default maximum concurrent clients (server only).
#define OPT_RECONNECT_ATTEMPTS_DEFAULT   (-1)
 Default reconnect attempts (-1 means auto/infinite).
#define OPT_COMPRESSION_LEVEL_DEFAULT   3
 Default compression level (1-9).
#define OPT_NO_COMPRESS_DEFAULT   false
 Default no compression flag (false = enable compression).
#define OPT_ACDS_DEFAULT   false
 Default ACDS registration flag (false = disabled).
#define OPT_ACDS_PORT_INT_DEFAULT   27225
 Default ACDS discovery service port (integer).
#define OPT_ACDS_PORT_DEFAULT   "27225"
 Default ACDS discovery service port (string).
#define OPT_ACDS_EXPOSE_IP_DEFAULT   false
 Default ACDS expose IP flag (false = private by default).
#define OPT_ACDS_INSECURE_DEFAULT   false
 Default ACDS insecure mode flag (false = verify server).
#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT   false
 Default require-server-identity setting for ACDS.
#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT   false
 Default require-client-identity setting for ACDS.
#define OPT_LAN_DISCOVERY_DEFAULT   false
 Default LAN discovery flag (false = discovery disabled).
#define OPT_NO_MDNS_ADVERTISE_DEFAULT   false
 Default no mDNS advertise flag (false = advertise enabled).
#define OPT_ENABLE_UPNP_DEFAULT   false
 Default enable UPnP flag (false = UPnP disabled).

Network Endpoint Defaults (WebRTC)

Centralized definitions for STUN/TURN servers

#define OPT_ENDPOINT_STUN_PRIMARY   "stun:stun.ascii-chat.com:3478"
 Primary STUN server (ascii-chat hosted).
#define OPT_ENDPOINT_STUN_FALLBACK   "stun:stun.l.google.com:19302"
 Fallback STUN server (Google public STUN).
#define OPT_ENDPOINT_STUN_SERVERS_DEFAULT   OPT_ENDPOINT_STUN_PRIMARY "," OPT_ENDPOINT_STUN_FALLBACK
 Default STUN servers (comma-separated list).
#define OPT_ENDPOINT_TURN_PRIMARY   "turn:turn.ascii-chat.com:3478"
 Primary TURN server (ascii-chat hosted).
#define OPT_ENDPOINT_TURN_SERVERS_DEFAULT   OPT_ENDPOINT_TURN_PRIMARY
 Default TURN servers (comma-separated list).
#define OPT_STUN_SERVER_HOST_PRIMARY   "stun.ascii-chat.com"
 STUN server hostname only (without protocol/port).
#define OPT_STUN_SERVER_PORT_PRIMARY   3478
 STUN server port for primary server.
#define OPT_STUN_SERVER_HOST_FALLBACK   "stun.l.google.com"
 Fallback STUN server hostname only.
#define OPT_STUN_SERVER_PORT_FALLBACK   19302
 Fallback STUN server port.
#define OPT_TURN_SERVER_HOST   "turn.ascii-chat.com"
 TURN server hostname only.
#define OPT_TURN_SERVER_PORT   3478
 TURN server port.
#define OPT_STUN_SERVERS_DEFAULT   OPT_ENDPOINT_STUN_SERVERS_DEFAULT
 Default STUN server URLs (comma-separated).
#define OPT_TURN_SERVERS_DEFAULT   OPT_ENDPOINT_TURN_SERVERS_DEFAULT
 Default TURN server URLs (comma-separated).

Detailed Description

⚙️ Command-line option parsing with unified mode detection, builder API, and RCU-based thread-safe access

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 module provides comprehensive command-line argument parsing, configuration management, and unified options state for ascii-chat with support for multiple modes (server, client, mirror, discovery service). The system unifies several layers:

  • Builder API (builder.h): Flexible option configuration with mode bitmasks
  • Registry (registry.h): Single definition of all options with mode applicability
  • RCU Thread-Safety (rcu.h): Lock-free read access to options via GET_OPTION() macro
  • Unified State (options_t struct): Single source of truth for all option values

Architecture Overview:

The options system is built in layers from bottom to top:

  1. Option Descriptors (registry.c): Single-source-of-truth definitions of all options with metadata (long name, short name, mode bitmask, defaults, validators, etc.)
  2. Builder Pattern (builder.h): Flexible API for programmatically constructing option configurations. Supports mode-specific options, dependencies, and custom validators.
  3. Presets (presets.h): Pre-built configurations for common modes (unified, server, client, mirror, discovery service). Use options_preset_unified() for the standard multi-mode setup.
  4. Unified Parsing (options.c): Single entry point options_init() that:
    • Detects mode from command-line arguments
    • Parses binary-level options (–help, –version, –log-file)
    • Parses mode-specific options
    • Validates and applies defaults
    • Publishes options via RCU for lock-free access
  5. RCU Thread-Safety (rcu.h): Lock-free read access to options after initialization:

Design Philosophy:

  • Single Source of Truth: All options defined once in registry.c with mode bitmasks
  • Builder Pattern Flexibility: Clients can create custom option configs using builder API
  • Unified State: Single options_t struct replaces scattered global variables
  • Lock-Free Reads: RCU (Read-Copy-Update) allows lock-free option access after startup
  • Mode Awareness: Options include mode bitmask so they apply to correct modes automatically
  • Sensible Defaults: All options have OPT_*_DEFAULT values that work out-of-the-box
  • Comprehensive Validation: Options validated at parse time, cross-field validators supported
  • Environment Variable Fallbacks: Options can fall back to environment variables

Usage Pattern:

#include "options.h"
int main(int argc, char **argv) {
// Initialize options (detects mode, parses args, validates)
asciichat_error_t err = options_init(argc, argv);
if (err != ASCIICHAT_OK) {
// Could be ERROR_USAGE (invalid options) or others
return 1;
}
// Lock-free read access to options (works from any thread)
const char *addr = GET_OPTION(address);
int port = GET_OPTION(port);
bool audio = GET_OPTION(audio_enabled);
asciichat_mode_t mode = GET_OPTION(detected_mode);
// Or get full options_t pointer for multi-field access
const options_t *opts = options_get();
printf("Mode: %d, Dimensions: %dx%d\n",
opts->detected_mode, opts->width, opts->height);
// Thread-safe updates (if needed at runtime)
options_set_int("width", 120);
options_set_bool("audio_enabled", true);
return 0;
}
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
#define GET_OPTION(field)
Definition options.h:1339
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
asciichat_error_t options_set_int(const char *name, int value)
Check if an option was explicitly set via command-line.
Definition rcu.c:964
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:513
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2541
asciichat_error_t options_set_bool(const char *name, bool value)
Definition rcu.c:973
int main(int argc, char *argv[])
Definition main.c:1353
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:978
int height
Terminal height in characters (int for OPTION_TYPE_INT compat).
Definition options.h:992
int width
Terminal width in characters (int for OPTION_TYPE_INT compat).
Definition options.h:991

Option Lifecycle:

  1. Definition: Options defined in registry.c with metadata and mode bitmasks
  2. Builder Creation: Use options_preset_unified() to create builder with presets
  3. Initialization: Call options_init(argc, argv) once at program startup
    • Mode detection from argv
    • Binary-level option parsing
    • Mode-specific parsing
    • Validation and defaults
    • RCU publishing
  4. Access: Lock-free reads via GET_OPTION() from any thread
  5. Updates (optional): Thread-safe runtime updates via options_set_*()

Mode-Specific Behavior:

Options include a mode_bitmask that indicates which modes they apply to:

Thread Safety:

  • Startup Phase: Options parsed once in main thread before worker threads created
  • Runtime Phase: Options are read-only from worker threads via GET_OPTION()
  • Lock-Free Reads: Guaranteed safe from any thread using RCU (no locks needed)
  • Runtime Updates: Use options_set_*() for thread-safe field updates
  • Performance: Single atomic pointer load (~1-2ns per read)

Builder API for Custom Configurations:

If you need a custom option set (not the standard unified preset), use the builder API:

// Create empty builder
// Add options from registry (filtered by mode)
// Or add custom options
.long_name = "my-option",
.short_name = 'm',
.offset = offsetof(options_t, my_field),
.mode_bitmask = OPTION_MODE_CLIENT,
// ... other fields ...
};
// Build immutable config
// Parse command line with custom config
options_config_parse_args(config, argc, argv, &my_opts);
// Publish to RCU for lock-free access
@ OPTION_TYPE_STRING
String value (–name foo).
Definition builder.h:183
void options_builder_add_descriptor(options_builder_t *builder, const option_descriptor_t *descriptor)
Add full option descriptor (advanced).
options_config_t * options_builder_build(options_builder_t *builder)
Build immutable options config.
options_builder_t * options_builder_create(size_t struct_size)
Mutable owner used to assemble option descriptors, dependencies, help sections, and examples before b...
options_t options_t_new(void)
Initialize options by parsing command-line arguments.
Definition options.c:688
@ OPTION_MODE_CLIENT
Client mode (bit 1).
Definition options.h:936
asciichat_error_t options_registry_add_all_to_builder(options_builder_t *builder)
Add all options from registry to builder.
Definition public_api.c:168
asciichat_error_t options_state_init(void)
Initialize RCU options system.
Definition rcu.c:382
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:459
The complete registry entry for one command-line/configuration option.
Definition builder.h:271
Immutable parsing tables produced from an options builder.
Definition builder.h:502
Immutable parsing tables produced from an options builder.
Definition builder.h:456

Command-Line Syntax:

Supported formats:

  • ascii-chat --help - Show usage (binary-level)
  • ascii-chat --version - Show version (binary-level)
  • ascii-chat server [Options Module] - Server mode
  • ascii-chat client [address][:port] [Options Module] - Client mode
  • ascii-chat mirror [Options Module] - Mirror mode (local preview)
  • ascii-chat acds [Options Module] - Discovery service mode
  • ascii-chat word-word-word [Options Module] - Client mode (session string)

Option Categories:

Organized by functionality for help display:

  • Network Options: address, port, max_clients, webrtc
  • Discovery Service Options: discovery, discovery_server, discovery_port
  • Media Options: webcam, test pattern, audio, compression
  • Display Options: width, height, color mode, palette, render mode
  • Encryption Options: keys, passwords, identity verification
  • Debug Options: logging, quiet, verbose, snapshots

Default Values:

All options have sensible OPT_*_DEFAULT values:

  • Terminal dimensions: Auto-detect or 110x70 fallback
  • Network: localhost:27224
  • Webcam: Device 0, horizontally flipped
  • Color mode: Auto-detect terminal capabilities
  • Encryption: Enabled (can be disabled with –no-encrypt)
Note
All options are stored in the options_t struct, replacing scattered globals
Options are parsed once at startup via options_init()
Most options remain constant after parsing (read-only)
Dynamic updates possible via options_set_*() for specific fields
Access via GET_OPTION() macro is lock-free and thread-safe
See also
options_init() - Main entry point for parsing
options_get() - Get pointer to current Options Module struct
GET_OPTION() - Convenience macro for reading single fields
builder.h - Builder API for custom configurations
registry.h - Central registry of all Options Module
rcu.h - RCU-based thread-safe access
presets.h - Pre-built configurations
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026

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:

  • Return 0 or positive value on success (often the parsed value)
  • Return -1 or negative value on error
  • Write error messages to the provided error_msg buffer
Note
These functions are used by both options.c and config.c

Options System Architecture

Overview

The ascii-chat options system is a comprehensive command-line argument parsing and configuration management framework built on three key components:

  1. Registry (registry.h): Central single-source-of-truth for all option definitions
  2. Builder (builder.h): Flexible API for constructing option configurations
  3. RCU Thread-Safety (rcu.h): Lock-free read access to options from any thread

Together, these provide:

  • Mode-aware parsing: Automatically filter options by detected mode
  • Type-safe defaults: All options have sensible defaults (OPT_*_DEFAULT constants)
  • Validation: Required fields, dependencies, cross-field validators, custom validators
  • Automatic memory management: Strings are auto-duplicated and auto-freed
  • Lock-free thread safety: Read options from 60fps render threads without locking
  • Shell completion support: Metadata for enum values, numeric ranges, examples
  • Grouped help output: Organized by category with semantic coloring
  • Environment variable fallbacks: Options can fall back to env vars

Architecture Diagram

┌─────────────────────────────────────────────────────────────────────────┐
│ COMMAND LINE ARGUMENTS │
│ ./ascii-chat server │
└──────────────────────────┬──────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────┐
│ MODE DETECTION (main.c) │
│ Detects: server / client / mirror │
│ Sets: detected_mode in options_t │
└──────────────────┬────────────────────┘
│
┌──────────────────▼──────────────────────────────────┐
│ REGISTRY LOOKUP (registry.h) │
│ ┌─────────────────────────────────────────────┐ │
│ │ options_registry_t global_registry[] = { │ │
│ │ { .long_name = "port", .mode = SERVER, │ │
│ │ .type = INT, .default = 27224, ...}, │ │
│ │ { .long_name = "color", .mode = ALL, │ │
│ │ .type = CALLBACK, ... }, │ │
│ │ ... │ │
│ │ } │ │
│ └─────────────────────────────────────────────┘ │
│ │
│ Lookup Functions: │
│ - find_by_name("port") │
│ - find_by_short('p') │
│ - get_for_mode(MODE_SERVER) → filters by mode │
│ - get_for_display(MODE_SERVER, true) → help- │
│ aware filtering │
└──────────────────┬───────────────────────────────────┘
│
┌──────────────────▼──────────────────────────────────┐
│ BUILDER CONSTRUCTION (builder.h) │
│ │
│ Step 1: Create builder │
│ ┌──────────────────────────────────────────────┐ │
│ │ builder = options_builder_create( │ │
│ │ sizeof(options_t)) │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 2: Populate from registry │
│ ┌──────────────────────────────────────────────┐ │
│ │ builder) // Copies all registered opts │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 3: Build immutable config │
│ ┌──────────────────────────────────────────────┐ │
│ │ config = options_builder_build(builder) │ │
│ │ // Creates options_config_t with all state │ │
│ │ // Both arrays and descriptors locked/locked │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────┬───────────────────────────────────┘
│
┌──────────────────▼──────────────────────────────────┐
│ COMMAND-LINE PARSING (options.c) │
│ │
│ Step 1: Set defaults from descriptors │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_config_set_defaults(config, │ │
│ │ &options_struct) │ │
│ │ // Fills options_t with defaults │ │
│ │ // Checks env vars for missing options │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 2: Parse command-line arguments │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_config_parse(config, argc, argv, │ │
│ │ &options_struct, MODE_DETECTED, ...) │ │
│ │ // Uses mode_bitmask to filter options │ │
│ │ // Applies custom parsers (OPTION_CALLBACK) │ │
│ │ // Auto-duplicates strings │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 3: Validate parsed options │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_config_validate(config, │ │
│ │ &options_struct, &error_msg) │ │
│ │ // Check required fields set │ │
│ │ // Validate dependencies (REQUIRES, │ │
│ │ // CONFLICTS, IMPLIES) │ │
│ │ // Call custom validators │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 4: Positional argument parsing │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_config_parse_positional(config, │ │
│ │ remaining_argc, remaining_argv, &opts) │ │
│ │ // Parses non-option args (client address, │ │
│ │ // session string, bind address, etc.) │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────┬───────────────────────────────────┘
│
┌──────────────────▼──────────────────────────────────┐
│ RCU THREAD-SAFE PUBLISHING (rcu.h) │
│ │
│ Step 1: Initialize RCU system │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_state_init() │ │
│ │ // Allocates atomic pointer structure │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 2: Publish parsed options │
│ ┌──────────────────────────────────────────────┐ │
│ │ options_state_set(&options_struct) │ │
│ │ // Atomically swaps pointer to new options │ │
│ │ // OLD: options readers see old version │ │
│ │ // NEW: options readers see new version │ │
│ │ // Defers freeing old struct (grace period) │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ Step 3: Spawn worker threads (safe to read) │
│ ┌──────────────────────────────────────────────┐ │
│ │ thread_pool_init() │ │
│ │ // Video render (60fps) │ │
│ │ // Audio playback (172fps) │ │
│ │ // Network packet handling │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────┬───────────────────────────────────┘
│
┌──────────────────▼──────────────────────────────────┐
│ LOCK-FREE READING (60fps video thread) │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ // Render thread (no locks, no blocking) │ │
│ │ const options_t *opts = options_get(); │ │
│ │ int width = opts->width; │ │
│ │ int height = opts->height; │ │
│ │ color_mode_t color = opts->color_mode; │ │
│ │ char *address = opts->server_address; │ │
│ │ │ │
│ │ // Or use convenience macro: │ │
│ │ const options_t *opts = GET_OPTION(width); │ │
│ │ │ │
│ │ // No contention, no cache line bouncing │ │
│ │ // Single atomic load (~1-2ns latency) │ │
│ │ // Consistent snapshot (no partial updates) │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
asciichat_error_t options_config_parse(const options_config_t *config, int argc, char **argv, void *options_struct, option_mode_bitmask_t detected_mode, int *remaining_argc, char ***remaining_argv)
Parse command-line arguments.
asciichat_error_t options_config_validate(const options_config_t *config, const void *options_struct, char **error_message)
Validate options struct.
asciichat_error_t options_config_parse_positional(const options_config_t *config, int remaining_argc, char **remaining_argv, void *options_struct)
Parse positional arguments.
asciichat_error_t options_config_set_defaults(const options_config_t *config, void *options_struct)
Set default values in options struct.
int color_mode
Definition fft.c:26
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
@ MODE_SERVER
Server mode - network server options.
Definition options.h:917
return true
Definition queries.h:15

Component Details

1. Registry (registry.h)

Purpose: Single source of truth for all option definitions

Key Data Structure:

typedef struct {
const char *long_name; // "port"
char short_name; // 'p'
option_type_t type; // INT, STRING, BOOL, CALLBACK, ACTION
size_t offset; // offsetof(options_t, port)
const void *default_value; // &(int){27224}
bool required; // true/false
const char *env_var_name; // "PORT"
bool (*validate)(...); // Custom validator
option_mode_bitmask_t mode_bitmask; // SERVER | CLIENT | MIRROR
option_metadata_t metadata; // Enums, ranges, examples
// ... more fields
option_type_t
Custom help section descriptor.
Definition builder.h:180
option_mode_bitmask_t
Option mode bitmask.
Definition options.h:933
Completion metadata attached to one option descriptor.
Definition builder.h:213

Registry Global Array (registry.c):

static const option_descriptor_t options_registry[] = {
{
.long_name = "port",
.short_name = 'p',
.type = OPTION_TYPE_INT,
.offset = offsetof(options_t, port),
.default_value = &(int){27224},
.help_text = "Server port",
.group = "NETWORK OPTIONS",
.mode_bitmask = OPTION_MODE_SERVER,
.validate = validate_port,
.metadata = {
.input_type = OPTION_INPUT_NUMERIC,
.numeric_range = {.min = 1, .max = 65535, .step = 1},
.examples = (const char *[]){
"27224", "8080", "3000", NULL
}
}
},
// ... more options ...
};
@ OPTION_INPUT_NUMERIC
Numeric value with optional min/max/step.
Definition builder.h:199
@ OPTION_TYPE_INT
Integer value (–count 42).
Definition builder.h:182
@ OPTION_MODE_SERVER
Server mode (bit 0).
Definition options.h:935

Key Functions:

Advantages:

  • No duplication (each option defined once)
  • Type-safe defaults (constants, not magic numbers)
  • Consistent across all modes
  • Easy to add new options
  • Facilitates shell completions

2. Builder (builder.h)

Purpose: Flexible API for constructing option configurations

Key Data Structure:

typedef struct {
option_descriptor_t *descriptors; // Dynamic array
size_t num_descriptors;
size_t descriptor_capacity;
option_dependency_t *dependencies; // Dynamic array
size_t num_dependencies;
size_t dependency_capacity;
// ... more arrays for positional args, examples, modes, sections
A rule connecting one option to another during validation.
Definition builder.h:377

Builder Workflow:

// 1. Create empty builder
// 2. Populate from registry OR add custom options
// 3. Add dependencies (optional)
builder, "tls-cert", "tls-enabled", NULL);
// 4. Add positional arguments (optional)
options_builder_add_positional(builder, "address", ...);
// 5. Add examples (optional, for help)
"Run as server");
// 6. Build immutable config
// 7. Free builder (config is independent)
void options_builder_add_example(options_builder_t *builder, uint32_t mode_bitmask, const char *args, const char *description, bool owns_args)
Add example descriptor.
void options_builder_add_dependency_requires(options_builder_t *builder, const char *option_name, const char *depends_on, const char *error_message)
Add dependency: if option_name is set, depends_on must be set.
void options_builder_add_positional(options_builder_t *builder, const char *name, const char *help_text, bool required, const char *section_heading, const char **examples, size_t num_examples, option_mode_bitmask_t mode_bitmask, int(*parse_fn)(const char *arg, void *config, char **remaining, int num_remaining, char **error_msg))
Add positional argument descriptor.
void options_builder_destroy(options_builder_t *builder)
Free options builder.

Key Functions:

Building Options: Three Approaches

Approach 1: From Registry (Most Common)

Approach 2: From Preset (Pre-built configurations)

options_config_t *preset = options_preset_unified("ascii-chat", "...");
// Modify if needed
options_builder_t * options_builder_from_preset(const options_config_t *preset)
Create builder from preset config.
options_config_t * options_preset_unified(const char *program_name, const char *description)
Build unified options config with ALL options (binary + all modes).
Definition presets.c:58

Approach 3: Custom from Scratch

options_builder_t *b = options_builder_create(sizeof(my_options_t));
options_builder_add_bool(b, "verbose", 'v', offsetof(...), ...);
options_builder_add_int(b, "port", 'p', offsetof(...), ...);
// ... add more options
void options_builder_add_bool(options_builder_t *builder, const char *long_name, char short_name, size_t offset, bool default_value, const char *help_text, const char *group, bool required, const char *env_var_name)
Add boolean flag option.
void options_builder_add_int(options_builder_t *builder, const char *long_name, char short_name, size_t offset, int default_value, const char *help_text, const char *group, bool required, const char *env_var_name, bool(*validate)(const void *options_struct))
Add integer option.

3. RCU Thread-Safety (rcu.h)

Purpose: Lock-free read access to options from any thread

Key Concept: Read-Copy-Update Pattern

RCU is perfect for ascii-chat because:

  • Read-Heavy: Options accessed constantly (60fps video, 172fps audio)
  • Write-Rare: Options set at startup, rarely changed
  • Lock-Free Reads: Zero contention, no blocking, ~1-2ns latency

How RCU Works:

Global atomic pointer to options_t
┌────────────────────────────────────────────────┐
│ atomic<const options_t*> g_options_ptr │
└────────────────────────────────────────────────┘
│
├─→ [options_t] ← Current (readers see this)
│ {
│ width: 120,
│ height: 60,
│ color_mode: TRUECOLOR,
│ port: 27224,
│ ...
│ }
When updating options:
1. Allocate new options_t struct
2. Copy current values
3. Apply modifications
4. Atomic swap pointer
5. Defer freeing old struct
Timeline:
────────────────────────────────────────────
OLD readers: [Old]─┐
├─[Swap]─→ [New]
NEW readers: └────────→ [New]
FREE: Defer until all old readers done

Data Structures:

// Opaque internal structure (rcu.c)
typedef struct {
atomic<const options_t*> ptr; // Atomic pointer
mutex_t update_lock; // Serializes writers
// ... grace period tracking ...
} options_state_t;

API:

// Initialization (main thread, before spawning workers)
options_state_set(&parsed_options)
// Reading (worker threads, lock-free)
const options_t *opts = options_get(); // 1-2ns atomic load
int width = opts->width;
// Convenience macro (same as above)
// Cleanup (program exit)
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:483

Key Features:

  • Lock-Free: No mutexes, spinlocks, or blocking
  • Wait-Free: Guaranteed to complete in bounded time
  • Fallback Defaults: Returns static defaults before init or after destroy
  • Atomic Semantics: acquire/release for proper memory ordering
  • Immutable Snapshots: Readers always see consistent state

Mode Bitmask System

Options are filtered by mode using bitmasks. This enables:

  • Mode-Specific Options: Only server can use –max-clients
  • Mode-Aware Help: Client help doesn't show server options
  • Automatic Filtering: Parser only accepts relevant options
  • Shell Completions: Only suggest options for current mode

Mode Values:

OPTION_MODE_BINARY // Parsed before mode detection
OPTION_MODE_SERVER // Server-only
OPTION_MODE_CLIENT // Client-only
OPTION_MODE_MIRROR // Mirror mode (local preview)
OPTION_MODE_DISCOVERY_SVC // Discovery service (ACDS)
OPTION_MODE_ALL // All modes (combine with |)
@ OPTION_MODE_ALL
All modes + binary.
Definition options.h:943
@ OPTION_MODE_BINARY
Binary-level options (parsed before mode detection).
Definition options.h:942
@ OPTION_MODE_MIRROR
Mirror mode (bit 2).
Definition options.h:937
@ OPTION_MODE_DISCOVERY_SVC
Discovery server mode (bit 3).
Definition options.h:938

Examples:

// Server-only option
.mode_bitmask = OPTION_MODE_SERVER
// Available in client and mirror
// Binary-level (before mode detection)
.mode_bitmask = OPTION_MODE_BINARY
// Available everywhere
.mode_bitmask = OPTION_MODE_ALL

Mode Filtering Workflow:

1. User: ./ascii-chat client example.com
2. Mode Detection: Detects MODE_CLIENT
3. Registry Filter: Get all options with CLIENT bit set
4. Parser: Only parses CLIENT options (--color, --audio, --snapshot)
5. Help: Only shows CLIENT options in --help
6. Completions: Only suggests CLIENT options
@ MODE_CLIENT
Client mode - network client options.
Definition options.h:918

Option Dependencies

Options can express relationships that are validated:

REQUIRES: If A is set, B must be set

builder, "tls-cert", "tls-enabled",
"TLS certificate requires TLS to be enabled");

CONFLICTS: If A is set, B must NOT be set

builder, "no-crypto", "key-file",
"Cannot use key-file with crypto disabled");
void options_builder_add_dependency_conflicts(options_builder_t *builder, const char *option_name, const char *conflicts_with, const char *error_message)
Add anti-dependency: if option_name is set, conflicts_with must NOT be set.

IMPLIES: If A is set, B defaults to true

builder, "tls-enabled", "secure", NULL);
void options_builder_add_dependency_implies(options_builder_t *builder, const char *option_name, const char *implies, const char *error_message)
Add implication: if option_name is set, implies defaults to true.

Dependencies are validated in options_config_validate() after parsing.

Complete Example: Server Mode

int main(int argc, char **argv) {
// 1. Initialize RCU system
if (err != ASCIICHAT_OK) return 1;
// 2. Create builder and populate from registry
// 3. Parse command line
err = options_config_parse(config, argc, argv, &opts,
MODE_DETECTED, NULL, NULL);
if (err != ASCIICHAT_OK) {
options_config_print_usage(config, stderr);
return 1;
}
// 4. Validate options
char *error_msg = NULL;
err = options_config_validate(config, &opts, &error_msg);
if (err != ASCIICHAT_OK) {
log_error("Option validation failed: %s", error_msg);
SAFE_FREE(error_msg);
return 1;
}
// 5. Publish to RCU (before spawning threads)
err = options_state_set(&opts);
if (err != ASCIICHAT_OK) return 1;
// 6. Now safe to spawn worker threads
server_run(); // Uses options_get() or GET_OPTION() for lock-free access
// 7. Cleanup
options_struct_destroy(config, &opts);
return 0;
}
void options_config_print_usage(const options_config_t *config, FILE *stream)
Print usage/help text.
void options_config_destroy(options_config_t *config)
Free options config.
void options_struct_destroy(const options_config_t *config, void *options_struct)
Clean up memory owned by options struct.
#define SAFE_FREE(ptr)
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604

Design Patterns and Best Practices

Pattern 1: Lock-Free Reading (Render Thread)

// Video render thread (60fps, no locks)
void render_frame_thread(void) {
while (running) {
// Safe lock-free read (~1-2ns atomic load)
const options_t *opts = options_get();
// Use options from consistent snapshot
framebuffer_t fb = render_frame(opts->width, opts->height);
apply_color_mode(&fb, opts->color_mode);
display_frame(&fb);
usleep(16667); // ~60fps
}
}
Mutex-protected ring buffer used to exchange video frames.
Definition ringbuffer.h:456
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor).
Definition options.h:1084

Pattern 2: Runtime Option Updates

// Main thread updates option (e.g., terminal resized)
void on_terminal_resize(int new_width, int new_height) {
// Create new options struct with updated values
options_t new_opts = *options_get(); // Copy current
new_opts.width = new_width;
new_opts.height = new_height;
// Publish atomically
options_state_set(&new_opts);
// Render threads now see new dimensions (lock-free)
}

Pattern 3: Mode-Aware Option Filtering

// Get only options for current mode
void show_mode_specific_help(asciichat_mode_t mode) {
size_t num_opts;
const option_descriptor_t *opts =
for (size_t i = 0; i < num_opts; i++) {
if (opts[i].hide_from_mode_help) continue; // Skip binary-only
printf(" --%s %s\n", opts[i].long_name,
opts[i].help_text);
}
}
const option_descriptor_t * options_registry_get_for_mode(asciichat_mode_t mode, size_t *num_options)
Get all options for a specific mode.
Definition public_api.c:181

Pattern 4: Custom Option with Validation

In registry.c:

bool validate_port(const void *options_struct) {
const options_t *opts = (const options_t *)options_struct;
if (opts->port < 1 || opts->port > 65535) {
SET_ERRNO(ERROR_USAGE, "Port must be between 1 and 65535");
return false;
}
return true;
}
// In registry array:
{
.long_name = "port",
.short_name = 'p',
.type = OPTION_TYPE_INT,
.offset = offsetof(options_t, port),
.default_value = &(int){27224},
.help_text = "Server port (1-65535)",
.group = "NETWORK OPTIONS",
.mode_bitmask = OPTION_MODE_SERVER,
.validate = validate_port, // Custom validator
}
#define SET_ERRNO(code,...)
@ ERROR_USAGE
Definition error_codes.h:52
int port
Server port number.
Definition options.h:1004

Thread Safety Summary

Phase Operation Thread Safety
Startup Parse args Main thread only
Startup Validate Main thread only
Startup Publish (options_state_set) Main thread only
Runtime Read (options_get) All threads, lock-free
Runtime Update One writer, readers see atomic update
Shutdown Destroy Main thread only

Performance Characteristics

Operation Latency Threads Notes
options_get() ~1-2ns Lock-free Single atomic load
GET_OPTION(field) ~1-2ns Lock-free Convenience macro
Parse (100 options) ~10μs Main thread One-time startup
Validate ~1μs Main thread One-time startup
options_state_set ~100ns Serialized Defers free old struct

Summary

The options system provides:

  • Registry: Single definition of all options
  • Builder: Flexible configuration construction
  • RCU: Lock-free read access from any thread
  • Mode Bitmasks: Automatic mode-aware filtering
  • Type Safety: Default constants, no magic numbers
  • Validation: Required fields, dependencies, cross-field validators
  • Memory Safety: Auto-duplicated strings, auto-freed
  • Shell Completions: Metadata for rich completions
  • Grouped Help: Organized by category with colors

All components work together to provide a comprehensive, type-safe, thread-safe command-line option handling system.

See also
registry.h - Central registry of option definitions
builder.h - Builder API for option configurations
rcu.h - RCU-based thread-safe access
options.h - Unified Options Module parsing system

Macro Definition Documentation

◆ ASCII_RENDERER_DEFAULT

#define ASCII_RENDERER_DEFAULT   ASCII_RENDERER_GLYPH

#include <include/ascii-chat/options/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.

Definition at line 962 of file options.h.

Referenced by options_t_new().

◆ ASCIICHAT_OPTION_FIELD_TYPE

#define ASCIICHAT_OPTION_FIELD_TYPE ( field)

#include <include/ascii-chat/options/options.h>

Value:
typeof(((options_t *)0)->field)

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);
bool flip_x = GET_OPTION(flip_x);
// In expressions
if (GET_OPTION(encrypt_enabled)) {
// encryption is enabled
}
// Function arguments
connect_to_server(GET_OPTION(address), GET_OPTION(port));

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 1330 of file options.h.

◆ COLOR_MODE_16

#define COLOR_MODE_16   TERM_COLOR_16

#include <include/ascii-chat/options/options.h>

16-color mode (alias)

Definition at line 225 of file options.h.

◆ COLOR_MODE_16_COLOR

#define COLOR_MODE_16_COLOR   TERM_COLOR_16

#include <include/ascii-chat/options/options.h>

16-color mode (full name)

Definition at line 226 of file options.h.

Referenced by append_color_fg_for_mode(), parse_color_mode_option(), and validate_opt_color_mode().

◆ COLOR_MODE_256

#define COLOR_MODE_256   TERM_COLOR_256

#include <include/ascii-chat/options/options.h>

256-color mode (alias)

Definition at line 227 of file options.h.

◆ COLOR_MODE_256_COLOR

#define COLOR_MODE_256_COLOR   TERM_COLOR_256

#include <include/ascii-chat/options/options.h>

256-color mode (full name)

Definition at line 228 of file options.h.

Referenced by append_color_fg_for_mode(), parse_color_mode_option(), and validate_opt_color_mode().

◆ COLOR_MODE_AUTO

#define COLOR_MODE_AUTO   TERM_COLOR_AUTO

#include <include/ascii-chat/options/options.h>

Backward compatibility aliases for color mode enum values.

Auto-detect color support

Definition at line 223 of file options.h.

Referenced by append_color_fg_for_mode(), parse_color_mode_option(), session_protocol_build_capabilities(), validate_opt_color_mode(), and visualization_encode().

◆ COLOR_MODE_NONE

#define COLOR_MODE_NONE   TERM_COLOR_NONE

◆ COLOR_MODE_TRUECOLOR

#define COLOR_MODE_TRUECOLOR   TERM_COLOR_TRUECOLOR

◆ GET_OPTION

#define GET_OPTION ( field)

#include <include/ascii-chat/options/options.h>

Value:
({ \
const options_t *_opts = options_get(); \
if (!_opts) { \
log_warn("GET_OPTION(" #field ") called but options not initialized"); \
} \
static ASCIICHAT_OPTION_FIELD_TYPE(field) _default = {0}; \
(_opts ? (_opts->field) : _default); \
})
#define ASCIICHAT_OPTION_FIELD_TYPE(field)
Safely get a specific option field (lock-free read).
Definition options.h:1330

Definition at line 1339 of file options.h.

1339#define GET_OPTION(field) \
1340 ({ \
1341 const options_t *_opts = options_get(); \
1342 if (!_opts) { \
1343 log_warn("GET_OPTION(" #field ") called but options not initialized"); \
1344 } \
1345 static ASCIICHAT_OPTION_FIELD_TYPE(field) _default = {0}; \
1346 (_opts ? (_opts->field) : _default); \
1347 })

Referenced by add_transport_client(), api_server_main(), ascii_convert(), ascii_write(), ascii_write_destroy(), ascii_write_init(), asciichat_shared_destroy(), audio_cleanup(), audio_client_init(), audio_process_received_samples(), audio_start_duplex(), audio_start_thread(), audio_visualization_render_fft(), audio_visualization_render_waveform(), audio_visualization_submit(), browser_capture_transform_required(), browser_capture_transform_rgba(), browser_client_init(), capture_init(), client_connection_start(), client_crypto_init(), client_init(), client_main(), client_protocol_start(), colored_string(), debug_stats_poll(), discovery_main(), display_init(), ffmpeg_decoder_create_stdin(), ffmpeg_encoder_write_frame(), SessionUiBinding::fps(), frame_buffer_render_border(), get_font_default_ptr(), get_font_default_size(), handle_client_capabilities_packet(), key_identity_format_terminal(), keyboard_help_is_active(), keyboard_help_toggle_terminal(), log_level_color_for_output(), mcp_http_run(), mcp_server_main(), media_source_create_interruptible(), media_source_read_video(), media_source_start_video(), media_source_uses_webcam(), mirror_convert_frame(), mirror_init(), mirror_render_audio_visualization(), mixer_create_channels(), mixer_process_excluding_source(), prompt_unknown_host(), render_file_create(), send_packet_secure(), server_main(), session_capture_at_end(), session_capture_create(), session_capture_toggle_media(), session_client_like_run(), session_connection_establish(), session_display_create(), session_display_encode_frame(), session_display_init_render_file(), session_display_render_frame(), session_display_write_ascii_frame(), session_participant_start_video(), session_pipeline_run_main(), session_protocol_init(), session_quic_listeners_open(), session_render_loop(), session_server_like_run(), splash_intro_done(), splash_intro_start(), splash_should_display(), stats_runtime_start(), term_renderer_create(), terminal_get_effective_color_mode(), terminal_get_effective_height(), terminal_get_effective_width(), terminal_should_use_utf8(), tui_stats_render(), ui_buttons_render(), ui_controller_show_volume(), ui_controller_title_start(), ui_controller_toggle_logs(), ui_controller_write(), ui_error_popup_preserve(), ui_error_popup_render(), ui_input_read_key(), ui_mdns_prompt_selection(), ui_media_panel_render(), ui_notice_confirm_kind(), ui_notice_present(), ui_notice_present_first_use(), ui_password_prompt_present(), ui_popup_frame(), ui_progress_format(), ui_prompt_present_kind(), ui_reconnect_render(), ui_scrollbar_cell(), ui_session_context_help_render(), ui_session_help_render(), ui_session_key(), ui_session_render(), ui_session_splash_render(), ui_spinner_glyph(), ui_spinner_render(), ui_status_render_header(), ui_status_update(), ui_sync_render(), ui_table_row(), update_banner_print_instructions(), update_banner_show_prompt(), utf8_output_enabled(), visualization_encode(), and SessionUiBinding::volume().

◆ LEVENSHTEIN_SUGGESTION_THRESHOLD

#define LEVENSHTEIN_SUGGESTION_THRESHOLD   4

#include <include/ascii-chat/options/levenshtein.h>

Maximum edit distance to suggest an option.

Threshold of 4 catches common typos including:

  • Single character errors (e.g., port-forwad → port-forwarding: distance 4)
  • Transpositions (e.g., colo-mod → color-mode: distance 2)
  • Short option typos (e.g., prot → port: distance 2) While still filtering out completely unrelated options.

Definition at line 32 of file levenshtein.h.

Referenced by find_similar_option_with_mode(), and levenshtein_find_similar().

◆ MODE_SERVER_GROUPS

#define MODE_SERVER_GROUPS

#include <include/ascii-chat/options/groups.h>

Value:
@ OPT_GROUP_CRYPTO
Encryption and authentication options.
Definition groups.h:67
@ OPT_GROUP_ACDS
ACDS discovery service options.
Definition groups.h:69
@ OPT_GROUP_BINARY
Binary-level options (help, version, logging).
Definition groups.h:58
@ OPT_GROUP_COMPRESSION
Compression options.
Definition groups.h:68
@ OPT_GROUP_NETWORK
Network options (address, port, reconnect).
Definition groups.h:61
@ OPT_GROUP_SERVER
Server-specific options (max_clients, client-keys).
Definition groups.h:71
@ OPT_GROUP_WEBRTC
WebRTC connectivity options (STUN/TURN).
Definition groups.h:75

Mode group presets.

Predefined combinations of option groups for each mode. These define which options are available in each mode. Server mode options: network binding, crypto, compression, ACDS

Definition at line 88 of file groups.h.

88#define MODE_SERVER_GROUPS \
89 (OPT_GROUP_BINARY | OPT_GROUP_NETWORK | OPT_GROUP_CRYPTO | \
90 OPT_GROUP_COMPRESSION | OPT_GROUP_ACDS | OPT_GROUP_SERVER | \
91 OPT_GROUP_WEBRTC)

◆ OPT_ACDS_DEFAULT

#define OPT_ACDS_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default ACDS registration flag (false = disabled).

Definition at line 590 of file options.h.

Referenced by options_t_new().

◆ OPT_ACDS_EXPOSE_IP_DEFAULT

#define OPT_ACDS_EXPOSE_IP_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default ACDS expose IP flag (false = private by default).

Definition at line 599 of file options.h.

Referenced by options_t_new().

◆ OPT_ACDS_INSECURE_DEFAULT

#define OPT_ACDS_INSECURE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default ACDS insecure mode flag (false = verify server).

Definition at line 602 of file options.h.

Referenced by options_t_new().

◆ OPT_ACDS_PORT_DEFAULT

#define OPT_ACDS_PORT_DEFAULT   "27225"

#include <include/ascii-chat/options/options.h>

Default ACDS discovery service port (string).

Definition at line 596 of file options.h.

◆ OPT_ACDS_PORT_INT_DEFAULT

#define OPT_ACDS_PORT_INT_DEFAULT   27225

#include <include/ascii-chat/options/options.h>

Default ACDS discovery service port (integer).

Definition at line 593 of file options.h.

Referenced by apply_mode_specific_defaults(), discovery_config_init_defaults(), and options_t_new().

◆ OPT_ADDRESS6_DEFAULT

#define OPT_ADDRESS6_DEFAULT   "::1"

#include <include/ascii-chat/options/options.h>

Default IPv6 server address.

Definition at line 539 of file options.h.

Referenced by options_t_new().

◆ OPT_ADDRESS_DEFAULT

#define OPT_ADDRESS_DEFAULT   "localhost"

#include <include/ascii-chat/options/options.h>

Default server address for client connections.

Definition at line 536 of file options.h.

Referenced by options_t_new().

◆ OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT

#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default audio analysis enabled flag.

Definition at line 722 of file options.h.

Referenced by options_t_new().

◆ OPT_AUDIO_CAPTURE_SOURCE_DEFAULT

#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT   AUDIO_CAPTURE_SOURCE_AUTO

#include <include/ascii-chat/options/options.h>

Preserve automatic local audio capture selection by default.

Definition at line 707 of file options.h.

Referenced by options_t_new().

◆ OPT_AUDIO_ENABLED_DEFAULT

#define OPT_AUDIO_ENABLED_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default audio enabled flag (true = audio enabled by default).

Definition at line 702 of file options.h.

Referenced by options_t_new().

◆ OPT_AUDIO_NO_PLAYBACK_DEFAULT

#define OPT_AUDIO_NO_PLAYBACK_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default audio playback flag (false = enable playback).

Definition at line 725 of file options.h.

Referenced by options_t_new().

◆ OPT_AUDIO_SOURCE_DEFAULT

#define OPT_AUDIO_SOURCE_DEFAULT   AUDIO_SOURCE_ALL

#include <include/ascii-chat/options/options.h>

Visualize all available sources by default.

Definition at line 705 of file options.h.

Referenced by options_t_new().

◆ OPT_AUTO_HEIGHT_DEFAULT

#define OPT_AUTO_HEIGHT_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default auto-detect height flag (true = auto-detect from terminal).

Definition at line 425 of file options.h.

Referenced by options_t_new().

◆ OPT_AUTO_WIDTH_DEFAULT

#define OPT_AUTO_WIDTH_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default auto-detect width flag (true = auto-detect from terminal).

Definition at line 422 of file options.h.

Referenced by options_t_new().

◆ OPT_COLOR_DEFAULT

#define OPT_COLOR_DEFAULT   COLOR_SETTING_AUTO

#include <include/ascii-chat/options/options.h>

Default color setting (COLOR_SETTING_AUTO = smart detection).

Definition at line 449 of file options.h.

Referenced by options_t_new().

◆ OPT_COLOR_FILTER_DEFAULT

#define OPT_COLOR_FILTER_DEFAULT   COLOR_FILTER_NONE

#include <include/ascii-chat/options/options.h>

Default color filter (none - no filtering).

Definition at line 456 of file options.h.

Referenced by options_t_new().

◆ OPT_COLOR_MODE_DEFAULT

#define OPT_COLOR_MODE_DEFAULT   COLOR_MODE_AUTO

#include <include/ascii-chat/options/options.h>

Default color mode (auto-detect terminal capabilities).

Definition at line 428 of file options.h.

Referenced by options_t_new().

◆ OPT_COLOR_SCHEME_NAME_DEFAULT

#define OPT_COLOR_SCHEME_NAME_DEFAULT   "pastel"

#include <include/ascii-chat/options/options.h>

Default color scheme name (pastel).

Definition at line 365 of file options.h.

Referenced by options_t_new().

◆ OPT_COMPRESSION_LEVEL_DEFAULT

#define OPT_COMPRESSION_LEVEL_DEFAULT   3

#include <include/ascii-chat/options/options.h>

Default compression level (1-9).

Definition at line 584 of file options.h.

Referenced by options_t_new().

◆ OPT_DISABLE_KEEPAWAKE_DEFAULT

#define OPT_DISABLE_KEEPAWAKE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default disable keep-awake flag (false = allow system sleep prevention).

Definition at line 333 of file options.h.

Referenced by options_t_new().

◆ OPT_ENABLE_KEEPAWAKE_DEFAULT

#define OPT_ENABLE_KEEPAWAKE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default keep-awake (prevent system sleep) flag (false = normal system sleep).

Definition at line 330 of file options.h.

Referenced by options_t_new().

◆ OPT_ENABLE_UPNP_DEFAULT

#define OPT_ENABLE_UPNP_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default enable UPnP flag (false = UPnP disabled).

Definition at line 617 of file options.h.

Referenced by options_t_new().

◆ OPT_ENCODE_AUDIO_DEFAULT

#define OPT_ENCODE_AUDIO_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default audio encoding state (true = Opus encoding enabled).

Definition at line 728 of file options.h.

Referenced by options_t_new().

◆ OPT_ENCRYPT_ENABLED_DEFAULT

#define OPT_ENCRYPT_ENABLED_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default encrypt enabled flag (true = encryption required).

Definition at line 735 of file options.h.

Referenced by options_t_new().

◆ OPT_ENDPOINT_DISCOVERY_SERVICE

#define OPT_ENDPOINT_DISCOVERY_SERVICE   "localhost"

#include <include/ascii-chat/options/options.h>

Default discovery service endpoint (what to connect to by default).

Production: connects to official server by default Debug: connects to localhost by default for local testing

Note
This is different from is_official_server() in crypto/discovery_keys.c which determines which servers have automatic HTTPS key trust. In debug builds:
  • DEFAULT ENDPOINT (this constant): localhost
  • AUTO-TRUST ENDPOINTS (discovery_keys.c): localhost AND official server

Definition at line 555 of file options.h.

Referenced by options_t_new().

◆ OPT_ENDPOINT_STUN_FALLBACK

#define OPT_ENDPOINT_STUN_FALLBACK   "stun:stun.l.google.com:19302"

#include <include/ascii-chat/options/options.h>

Fallback STUN server (Google public STUN).

Definition at line 630 of file options.h.

◆ OPT_ENDPOINT_STUN_PRIMARY

#define OPT_ENDPOINT_STUN_PRIMARY   "stun:stun.ascii-chat.com:3478"

#include <include/ascii-chat/options/options.h>

Primary STUN server (ascii-chat hosted).

Definition at line 627 of file options.h.

◆ OPT_ENDPOINT_STUN_SERVERS_DEFAULT

#define OPT_ENDPOINT_STUN_SERVERS_DEFAULT   OPT_ENDPOINT_STUN_PRIMARY "," OPT_ENDPOINT_STUN_FALLBACK

#include <include/ascii-chat/options/options.h>

Default STUN servers (comma-separated list).

Definition at line 633 of file options.h.

◆ OPT_ENDPOINT_TURN_PRIMARY

#define OPT_ENDPOINT_TURN_PRIMARY   "turn:turn.ascii-chat.com:3478"

#include <include/ascii-chat/options/options.h>

Primary TURN server (ascii-chat hosted).

Definition at line 636 of file options.h.

◆ OPT_ENDPOINT_TURN_SERVERS_DEFAULT

#define OPT_ENDPOINT_TURN_SERVERS_DEFAULT   OPT_ENDPOINT_TURN_PRIMARY

#include <include/ascii-chat/options/options.h>

Default TURN servers (comma-separated list).

Definition at line 639 of file options.h.

◆ OPT_FLIP_X_DEFAULT

#define OPT_FLIP_X_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Webcam input is mirrored unless an orientation is explicitly selected.

Definition at line 497 of file options.h.

Referenced by options_t_new().

◆ OPT_FLIP_Y_DEFAULT

#define OPT_FLIP_Y_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default vertical flip state (false = no vertical flip).

Definition at line 500 of file options.h.

Referenced by options_t_new().

◆ OPT_FORCE_UTF8_DEFAULT

#define OPT_FORCE_UTF8_DEFAULT   UTF8_SETTING_AUTO

#include <include/ascii-chat/options/options.h>

Default force UTF-8 support setting (auto-detect).

Definition at line 443 of file options.h.

Referenced by options_t_new().

◆ OPT_FPS_COUNTER_DEFAULT

#define OPT_FPS_COUNTER_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default FPS counter overlay flag (false = disabled).

Definition at line 494 of file options.h.

◆ OPT_FPS_DEFAULT

#define OPT_FPS_DEFAULT   0

#include <include/ascii-chat/options/options.h>

Default FPS (frames per second).

Definition at line 471 of file options.h.

Referenced by options_t_new().

◆ OPT_GREP_PATTERN_DEFAULT

#define OPT_GREP_PATTERN_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Default grep pattern (empty = no filtering).

Definition at line 359 of file options.h.

◆ OPT_HEIGHT_DEFAULT

#define OPT_HEIGHT_DEFAULT   70

#include <include/ascii-chat/options/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 419 of file options.h.

Referenced by options_t_new(), and terminal_get_effective_height().

◆ OPT_HELP_DEFAULT

#define OPT_HELP_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default help flag (false = don't show help).

Definition at line 312 of file options.h.

Referenced by options_t_new().

◆ OPT_JSON_DEFAULT

#define OPT_JSON_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default JSON logging flag (false = text output).

Definition at line 362 of file options.h.

Referenced by options_t_new().

◆ OPT_LAN_DISCOVERY_DEFAULT

#define OPT_LAN_DISCOVERY_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default LAN discovery flag (false = discovery disabled).

Definition at line 611 of file options.h.

Referenced by options_t_new().

◆ OPT_LIST_MICROPHONES_DEFAULT

#define OPT_LIST_MICROPHONES_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default list microphones flag (false = don't list and exit).

Definition at line 434 of file options.h.

◆ OPT_LIST_SPEAKERS_DEFAULT

#define OPT_LIST_SPEAKERS_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default list speakers flag (false = don't list and exit).

Definition at line 437 of file options.h.

◆ OPT_LIST_WEBCAMS_DEFAULT

#define OPT_LIST_WEBCAMS_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default list webcams flag (false = don't list and exit).

Definition at line 431 of file options.h.

◆ OPT_LOG_FORMAT_CONSOLE_DEFAULT

#define OPT_LOG_FORMAT_CONSOLE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default log format console only flag (false = use default format everywhere).

Definition at line 393 of file options.h.

◆ OPT_LOG_FORMAT_OUTPUT_DEFAULT

#define OPT_LOG_FORMAT_OUTPUT_DEFAULT   LOG_OUTPUT_TEXT

#include <include/ascii-chat/options/options.h>

Default log format output type (TEXT = human-readable, JSON = structured).

Definition at line 390 of file options.h.

◆ OPT_LOG_LEVEL_DEFAULT

#define OPT_LOG_LEVEL_DEFAULT   LOG_INFO

#include <include/ascii-chat/options/options.h>

Default log level (LOG_INFO).

Definition at line 356 of file options.h.

Referenced by options_t_new().

◆ OPT_LOG_TEMPLATE_DEFAULT

#define OPT_LOG_TEMPLATE_DEFAULT   OPT_LOG_TEMPLATE_DEFAULT_DEBUG

#include <include/ascii-chat/options/options.h>

Default log template string (selected based on build mode).

Release builds use simple format. Debug builds use verbose format with thread ID, file path, line, and function. The get_default_log_template() function returns this value via the options system.

Definition at line 386 of file options.h.

Referenced by log_set_format().

◆ OPT_LOG_TEMPLATE_DEFAULT_DEBUG

#define OPT_LOG_TEMPLATE_DEFAULT_DEBUG

#include <include/ascii-chat/options/options.h>

Value:
"[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
"[thread/%color(GREY, %tname)] %color(DEBUG, %file_relative):%color(GREY, %line)@%color(DEV, %func)(): " \
"%colored_message"

Default log format string - debug mode (verbose with thread name, file relative path, line, and function).

Definition at line 373 of file options.h.

373#define OPT_LOG_TEMPLATE_DEFAULT_DEBUG \
374 "[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
375 "[thread/%color(GREY, %tname)] %color(DEBUG, %file_relative):%color(GREY, %line)@%color(DEV, %func)(): " \
376 "%colored_message"

Referenced by browser_client_init(), client_init(), and mirror_init().

◆ OPT_LOG_TEMPLATE_DEFAULT_RELEASE

#define OPT_LOG_TEMPLATE_DEFAULT_RELEASE

#include <include/ascii-chat/options/options.h>

Value:
"[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
"%colored_message"

Default log format string - release mode (simple format with timestamp, level, and message).

Definition at line 368 of file options.h.

368#define OPT_LOG_TEMPLATE_DEFAULT_RELEASE \
369 "[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
370 "%colored_message"

◆ OPT_MATRIX_RAIN_DEFAULT

#define OPT_MATRIX_RAIN_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default Matrix rain effect flag (false = disabled).

Definition at line 491 of file options.h.

Referenced by options_t_new().

◆ OPT_MAX_CLIENTS_DEFAULT

#define OPT_MAX_CLIENTS_DEFAULT   9

#include <include/ascii-chat/options/options.h>

Default maximum concurrent clients (server only).

Definition at line 578 of file options.h.

Referenced by options_t_new().

◆ OPT_MCP_PORT_DEFAULT

#define OPT_MCP_PORT_DEFAULT   27228

#include <include/ascii-chat/options/options.h>

MCP HTTP listener port.

Definition at line 575 of file options.h.

Referenced by get_default_port().

◆ OPT_MEDIA_FROM_STDIN_DEFAULT

#define OPT_MEDIA_FROM_STDIN_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default media from stdin flag (false = not reading from stdin).

Definition at line 523 of file options.h.

Referenced by options_t_new().

◆ OPT_MEDIA_LOOP_DEFAULT

#define OPT_MEDIA_LOOP_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default loop media flag (false = play once).

Definition at line 520 of file options.h.

Referenced by options_t_new().

◆ OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT

#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT   0.0

#include <include/ascii-chat/options/options.h>

Default media seek timestamp (start from beginning).

Definition at line 526 of file options.h.

Referenced by options_t_new().

◆ OPT_MICROPHONE_INDEX_DEFAULT

#define OPT_MICROPHONE_INDEX_DEFAULT   (-1)

#include <include/ascii-chat/options/options.h>

Default microphone device index (-1 means system default).

Definition at line 710 of file options.h.

Referenced by options_t_new().

◆ OPT_MICROPHONE_SENSITIVITY_DEFAULT

#define OPT_MICROPHONE_SENSITIVITY_DEFAULT   1.0

#include <include/ascii-chat/options/options.h>

Default microphone sensitivity (1.0 = normal volume).

Definition at line 716 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_AUDIO_MIXER_DEFAULT

#define OPT_NO_AUDIO_MIXER_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no audio mixer flag (false = enable mixer).

Definition at line 513 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_AUTH_DEFAULT

#define OPT_NO_AUTH_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no auth flag (false = allow authentication).

Definition at line 741 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_CHECK_UPDATE_DEFAULT

#define OPT_NO_CHECK_UPDATE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no-check-update flag (false = check for updates enabled).

Definition at line 336 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_COMPRESS_DEFAULT

#define OPT_NO_COMPRESS_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no compression flag (false = enable compression).

Definition at line 587 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_ENCRYPT_DEFAULT

#define OPT_NO_ENCRYPT_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no encrypt flag (false = allow encryption).

Definition at line 738 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_MDNS_ADVERTISE_DEFAULT

#define OPT_NO_MDNS_ADVERTISE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no mDNS advertise flag (false = advertise enabled).

Definition at line 614 of file options.h.

Referenced by options_t_new().

◆ OPT_NO_WEBRTC_DEFAULT

#define OPT_NO_WEBRTC_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default no WebRTC flag (false = WebRTC enabled).

Definition at line 674 of file options.h.

Referenced by options_t_new().

◆ OPT_OTEL_ENDPOINT_DEFAULT

#define OPT_OTEL_ENDPOINT_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Debug and Dev builds export to the local Spaniel Compose collector.

Definition at line 349 of file options.h.

Referenced by ascii_otel_init(), and options_t_new().

◆ OPT_PALETTE_CUSTOM_SET_DEFAULT

#define OPT_PALETTE_CUSTOM_SET_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default custom palette set flag (false = not set).

Definition at line 465 of file options.h.

Referenced by options_t_new().

◆ OPT_PALETTE_TYPE_DEFAULT

#define OPT_PALETTE_TYPE_DEFAULT   PALETTE_STANDARD

#include <include/ascii-chat/options/options.h>

Default palette type (standard ASCII art).

Definition at line 462 of file options.h.

Referenced by options_t_new().

◆ OPT_PAUSE_DEFAULT

#define OPT_PAUSE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default pause media flag (false = play immediately).

Definition at line 529 of file options.h.

Referenced by options_t_new().

◆ OPT_PORT_DEFAULT

#define OPT_PORT_DEFAULT   "27224"

#include <include/ascii-chat/options/options.h>

Default TCP port for client/server communication (string).

Definition at line 559 of file options.h.

◆ OPT_PORT_INT_DEFAULT

#define OPT_PORT_INT_DEFAULT   27224

#include <include/ascii-chat/options/options.h>

Default TCP port for client/server communication (integer).

Definition at line 562 of file options.h.

Referenced by apply_mode_specific_defaults(), options_t_new(), session_host_create(), and session_participant_create().

◆ OPT_PREFER_WEBRTC_DEFAULT

#define OPT_PREFER_WEBRTC_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default prefer WebRTC flag (false = try direct TCP first).

Definition at line 671 of file options.h.

Referenced by options_t_new().

◆ OPT_QUIET_DEFAULT

#define OPT_QUIET_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default quiet mode flag (false = logging enabled).

Definition at line 343 of file options.h.

Referenced by options_t_new().

◆ OPT_RECONNECT_ATTEMPTS_DEFAULT

#define OPT_RECONNECT_ATTEMPTS_DEFAULT   (-1)

#include <include/ascii-chat/options/options.h>

Default reconnect attempts (-1 means auto/infinite).

Definition at line 581 of file options.h.

Referenced by options_t_new().

◆ OPT_RENDER_FILE_DEFAULT

#define OPT_RENDER_FILE_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Definition at line 771 of file options.h.

◆ OPT_RENDER_FONT_DEFAULT

#define OPT_RENDER_FONT_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Definition at line 773 of file options.h.

◆ OPT_RENDER_FONT_SIZE_DEFAULT

#define OPT_RENDER_FONT_SIZE_DEFAULT   0.0

#include <include/ascii-chat/options/options.h>

Definition at line 774 of file options.h.

Referenced by options_t_new().

◆ OPT_RENDER_MODE_DEFAULT

#define OPT_RENDER_MODE_DEFAULT   RENDER_MODE_FOREGROUND

#include <include/ascii-chat/options/options.h>

Default render mode (foreground characters only).

Definition at line 459 of file options.h.

Referenced by options_t_new().

◆ OPT_RENDER_THEME_DEFAULT

#define OPT_RENDER_THEME_DEFAULT   0

#include <include/ascii-chat/options/options.h>

Definition at line 772 of file options.h.

Referenced by options_t_new().

◆ OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT

#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default require-client-identity setting for ACDS.

Definition at line 608 of file options.h.

Referenced by options_t_new().

◆ OPT_REQUIRE_CLIENT_VERIFY_DEFAULT

#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default require client verify flag (false = not required).

Definition at line 747 of file options.h.

Referenced by options_t_new().

◆ OPT_REQUIRE_SERVER_IDENTITY_DEFAULT

#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default require-server-identity setting for ACDS.

Definition at line 605 of file options.h.

Referenced by options_t_new().

◆ OPT_REQUIRE_SERVER_VERIFY_DEFAULT

#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default require server verify flag (false = not required).

Definition at line 744 of file options.h.

Referenced by options_t_new().

◆ OPT_SHOW_CAPABILITIES_DEFAULT

#define OPT_SHOW_CAPABILITIES_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default show terminal capabilities flag.

Definition at line 440 of file options.h.

Referenced by options_t_new().

◆ OPT_SNAPSHOT_DELAY_DEFAULT

#define OPT_SNAPSHOT_DELAY_DEFAULT   3.0f

#include <include/ascii-chat/options/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 487 of file options.h.

Referenced by options_t_new().

◆ OPT_SNAPSHOT_MODE_DEFAULT

#define OPT_SNAPSHOT_MODE_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default snapshot mode flag (false = continuous).

Definition at line 474 of file options.h.

Referenced by options_t_new().

◆ OPT_SPEAKERS_INDEX_DEFAULT

#define OPT_SPEAKERS_INDEX_DEFAULT   (-1)

#include <include/ascii-chat/options/options.h>

Default speakers device index (-1 means system default).

Definition at line 713 of file options.h.

Referenced by options_t_new().

◆ OPT_SPEAKERS_VOLUME_DEFAULT

#define OPT_SPEAKERS_VOLUME_DEFAULT   1.0

#include <include/ascii-chat/options/options.h>

Default speakers volume (1.0 = normal volume).

Definition at line 719 of file options.h.

Referenced by options_t_new().

◆ OPT_SPLASH_DEFAULT

#define OPT_SPLASH_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default splash screen flag (true = show splash, false = hide splash).

Definition at line 318 of file options.h.

Referenced by options_t_new().

◆ OPT_SPLASH_SCREEN_EXPLICITLY_SET_DEFAULT

#define OPT_SPLASH_SCREEN_EXPLICITLY_SET_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default splash screen explicitly set flag (false = use default splash setting).

Definition at line 321 of file options.h.

◆ OPT_STATUS_SCREEN_DEFAULT

#define OPT_STATUS_SCREEN_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default status screen flag (true = show status, false = hide status).

Definition at line 324 of file options.h.

Referenced by options_t_new().

◆ OPT_STATUS_SCREEN_EXPLICITLY_SET_DEFAULT

#define OPT_STATUS_SCREEN_EXPLICITLY_SET_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default status screen explicitly set flag (false = use default status screen setting).

Definition at line 327 of file options.h.

◆ OPT_STRETCH_DEFAULT

#define OPT_STRETCH_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default allow aspect ratio distortion flag.

Definition at line 468 of file options.h.

Referenced by options_t_new().

◆ OPT_STRING_EMPTY_DEFAULT

#define OPT_STRING_EMPTY_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Default empty string for string option fields that have no configured value.

Definition at line 766 of file options.h.

◆ OPT_STRIP_ANSI_DEFAULT

#define OPT_STRIP_ANSI_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default strip ANSI escape sequences flag.

Definition at line 446 of file options.h.

Referenced by options_t_new().

◆ OPT_STUN_SERVER_HOST_FALLBACK

#define OPT_STUN_SERVER_HOST_FALLBACK   "stun.l.google.com"

#include <include/ascii-chat/options/options.h>

Fallback STUN server hostname only.

Definition at line 648 of file options.h.

◆ OPT_STUN_SERVER_HOST_PRIMARY

#define OPT_STUN_SERVER_HOST_PRIMARY   "stun.ascii-chat.com"

#include <include/ascii-chat/options/options.h>

STUN server hostname only (without protocol/port).

Definition at line 642 of file options.h.

◆ OPT_STUN_SERVER_PORT_FALLBACK

#define OPT_STUN_SERVER_PORT_FALLBACK   19302

#include <include/ascii-chat/options/options.h>

Fallback STUN server port.

Definition at line 651 of file options.h.

◆ OPT_STUN_SERVER_PORT_PRIMARY

#define OPT_STUN_SERVER_PORT_PRIMARY   3478

#include <include/ascii-chat/options/options.h>

STUN server port for primary server.

Definition at line 645 of file options.h.

◆ OPT_STUN_SERVERS_DEFAULT

#define OPT_STUN_SERVERS_DEFAULT   OPT_ENDPOINT_STUN_SERVERS_DEFAULT

#include <include/ascii-chat/options/options.h>

Default STUN server URLs (comma-separated).

Definition at line 660 of file options.h.

Referenced by options_t_new().

◆ OPT_TEST_PATTERN_DEFAULT

#define OPT_TEST_PATTERN_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default test pattern mode (false = use actual webcam).

Definition at line 510 of file options.h.

Referenced by options_t_new().

◆ OPT_TURN_CREDENTIAL_DEFAULT

#define OPT_TURN_CREDENTIAL_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Default TURN credential (empty = use ACDS credentials).

Definition at line 695 of file options.h.

Referenced by options_t_new().

◆ OPT_TURN_SERVER_HOST

#define OPT_TURN_SERVER_HOST   "turn.ascii-chat.com"

#include <include/ascii-chat/options/options.h>

TURN server hostname only.

Definition at line 654 of file options.h.

◆ OPT_TURN_SERVER_PORT

#define OPT_TURN_SERVER_PORT   3478

#include <include/ascii-chat/options/options.h>

TURN server port.

Definition at line 657 of file options.h.

◆ OPT_TURN_SERVERS_DEFAULT

#define OPT_TURN_SERVERS_DEFAULT   OPT_ENDPOINT_TURN_SERVERS_DEFAULT

#include <include/ascii-chat/options/options.h>

Default TURN server URLs (comma-separated).

Definition at line 663 of file options.h.

Referenced by options_t_new().

◆ OPT_TURN_USERNAME_DEFAULT

#define OPT_TURN_USERNAME_DEFAULT   ""

#include <include/ascii-chat/options/options.h>

Default TURN username (empty = use ACDS credentials).

Definition at line 692 of file options.h.

Referenced by options_t_new().

◆ OPT_VERBOSE_LEVEL_DEFAULT

#define OPT_VERBOSE_LEVEL_DEFAULT   0

#include <include/ascii-chat/options/options.h>

Default verbose level (0 = not verbose).

Definition at line 353 of file options.h.

Referenced by options_t_new().

◆ OPT_VERSION_DEFAULT

#define OPT_VERSION_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default version flag (false = don't show version).

Definition at line 315 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBCAM_INDEX_DEFAULT

#define OPT_WEBCAM_INDEX_DEFAULT   0

#include <include/ascii-chat/options/options.h>

Default webcam device index.

Definition at line 507 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBRTC_DEFAULT

#define OPT_WEBRTC_DEFAULT   true

#include <include/ascii-chat/options/options.h>

Default WebRTC mode flag (true = P2P WebRTC, false = direct TCP).

Definition at line 668 of file options.h.

◆ OPT_WEBRTC_DISABLE_TURN_DEFAULT

#define OPT_WEBRTC_DISABLE_TURN_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default WebRTC disable TURN flag (false = use TURN).

Definition at line 680 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT

#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT   10000

#include <include/ascii-chat/options/options.h>

Default WebRTC ICE gathering timeout in milliseconds (10 seconds).

Definition at line 686 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBRTC_RECONNECT_ATTEMPTS_DEFAULT

#define OPT_WEBRTC_RECONNECT_ATTEMPTS_DEFAULT   3

#include <include/ascii-chat/options/options.h>

Default WebRTC reconnection attempts (3 = try initial + 3 retries).

Definition at line 689 of file options.h.

◆ OPT_WEBRTC_SKIP_HOST_DEFAULT

#define OPT_WEBRTC_SKIP_HOST_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default WebRTC skip host candidates flag (false = use host candidates).

Definition at line 683 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBRTC_SKIP_STUN_DEFAULT

#define OPT_WEBRTC_SKIP_STUN_DEFAULT   false

#include <include/ascii-chat/options/options.h>

Default WebRTC skip STUN flag (false = use STUN).

Definition at line 677 of file options.h.

Referenced by options_t_new().

◆ OPT_WEBSOCKET_PORT_ACDS_DEFAULT

#define OPT_WEBSOCKET_PORT_ACDS_DEFAULT   27227

#include <include/ascii-chat/options/options.h>

Default WebSocket port for discovery-service mode (integer).

Definition at line 572 of file options.h.

Referenced by apply_mode_specific_defaults().

◆ OPT_WEBSOCKET_PORT_SERVER_DEFAULT

#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT   27226

#include <include/ascii-chat/options/options.h>

Default WebSocket port for server mode (integer).

Definition at line 565 of file options.h.

Referenced by apply_mode_specific_defaults(), and options_t_new().

◆ OPT_WIDTH_DEFAULT

#define OPT_WIDTH_DEFAULT   110

#include <include/ascii-chat/options/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 408 of file options.h.

Referenced by options_t_new(), and terminal_get_effective_width().

◆ OPTION_MODE_CLIENT_LIKE

#define OPTION_MODE_CLIENT_LIKE   (OPTION_MODE_CLIENT | OPTION_MODE_MIRROR | OPTION_MODE_DISCOVERY)

#include <include/ascii-chat/options/options.h>

Definition at line 953 of file options.h.

Referenced by options_preset_unified().

◆ OPTION_MODE_NETWORKED

#include <include/ascii-chat/options/options.h>

Definition at line 954 of file options.h.

◆ OPTION_MODE_SERVER_LIKE

#define OPTION_MODE_SERVER_LIKE   (OPTION_MODE_SERVER | OPTION_MODE_DISCOVERY_SVC)

#include <include/ascii-chat/options/options.h>

Mode group macros for examples.

These macros combine multiple mode bits to allow examples to apply to logical groups of modes (e.g., server-like modes, client-like modes).

Definition at line 952 of file options.h.

Referenced by options_preset_unified().

◆ OPTIONS_BUFF_SIZE

#define OPTIONS_BUFF_SIZE   256

#include <include/ascii-chat/options/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 305 of file options.h.

Referenced by ascii_otel_init(), config_create_default(), options_collect_identity_keys(), parse_client_address(), parse_mirror_media(), parse_server_bind_address(), registry_add_all_to_flags_builder(), validate_opt_ip_address(), and webrtc_turn_servers_parse().

◆ OPTIONS_COLOR_SCHEME_NAME_BUFFER_SIZE

#define OPTIONS_COLOR_SCHEME_NAME_BUFFER_SIZE   64

#include <include/ascii-chat/options/options.h>

Definition at line 209 of file options.h.

◆ OPTIONS_PALETTE_CUSTOM_BUFFER_SIZE

#define OPTIONS_PALETTE_CUSTOM_BUFFER_SIZE   256

#include <include/ascii-chat/options/options.h>

Definition at line 211 of file options.h.

Referenced by parse_palette_chars().

◆ options_terminal_settings

◆ OPTIONS_VIDEO_CODEC_BUFFER_SIZE

#define OPTIONS_VIDEO_CODEC_BUFFER_SIZE   64

#include <include/ascii-chat/options/options.h>

Definition at line 210 of file options.h.

◆ OPTIONS_YT_DLP_OPTIONS_BUFFER_SIZE

#define OPTIONS_YT_DLP_OPTIONS_BUFFER_SIZE   512

#include <include/ascii-chat/options/options.h>

Definition at line 208 of file options.h.

Typedef Documentation

◆ options_t

typedef struct options_state options_t

#include <include/ascii-chat/options/options.h>

Immutable, RCU-published snapshot of the application's runtime configuration.

The fields cover mode selection, terminal and media rendering, audio, network and discovery endpoints, authentication and encryption policy, logging, and the explicit-value markers used while merging defaults. Readers borrow the current snapshot through options_get(); updates allocate and publish a replacement instead of mutating a snapshot that another thread may still be using.

Examples
/home/runner/work/ascii-chat/ascii-chat/include/ascii-chat/options/explicit.h.

Enumeration Type Documentation

◆ asciichat_mode_t

#include <include/ascii-chat/options/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_DISCOVERY_SERVICE 

Discovery server mode - session management and WebRTC signaling.

MODE_DISCOVERY 

Discovery mode - participant that can dynamically become host.

MODE_MCP_SERVER 

Model Context Protocol rendering server.

MODE_API_SERVER 

Image-to-ASCII HTTP API server.

MODE_INVALID 

Invalid mode.

Definition at line 916 of file options.h.

916 {
@ MODE_MCP_SERVER
Model Context Protocol rendering server.
Definition options.h:922
@ MODE_DISCOVERY_SERVICE
Discovery server mode - session management and WebRTC signaling.
Definition options.h:920
@ MODE_API_SERVER
Image-to-ASCII HTTP API server.
Definition options.h:923
@ MODE_INVALID
Invalid mode.
Definition options.h:924
@ MODE_MIRROR
Mirror mode - local webcam viewing (no network).
Definition options.h:919
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921

◆ audio_capture_source_t

#include <include/ascii-chat/options/options.h>

Audio source policy for local capture and media playback.

Enumerator
AUDIO_CAPTURE_SOURCE_AUTO 
AUDIO_CAPTURE_SOURCE_MIC 
AUDIO_CAPTURE_SOURCE_MEDIA 
AUDIO_CAPTURE_SOURCE_BOTH 
AUDIO_CAPTURE_SOURCE_REMOTE 

Definition at line 291 of file options.h.

audio_capture_source_t
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_BOTH
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_REMOTE
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_MEDIA
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_MIC
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_AUTO
Definition options.h:291

◆ audio_source_t

#include <include/ascii-chat/options/options.h>

Audio source selected for visualization.

Enumerator
AUDIO_SOURCE_ALL 

Combine local microphone, local media, and audio received from other participants

AUDIO_SOURCE_CALL 

Audio received from other participants in the call

AUDIO_SOURCE_MIC 

Local microphone input

AUDIO_SOURCE_MEDIA 

Local media playback

AUDIO_SOURCE_AUTO 

Backward-compatible spelling for all available visualization sources

Definition at line 277 of file options.h.

277 {
audio_source_t
Audio source selected for visualization.
Definition options.h:277
@ AUDIO_SOURCE_MIC
Definition options.h:283
@ AUDIO_SOURCE_CALL
Definition options.h:281
@ AUDIO_SOURCE_MEDIA
Definition options.h:285
@ AUDIO_SOURCE_ALL
Definition options.h:279
@ AUDIO_SOURCE_AUTO
Definition options.h:287

◆ color_setting_t

#include <include/ascii-chat/options/options.h>

For options state, this is the live record that ties detected_mode, mode_arg_index, help, version together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.

Color output setting (–color flag values)

Enumeration for the –color option which controls color output behavior:

  • COLOR_SETTING_AUTO: Smart detection (default) - colors if TTY, not piping, not CLAUDECODE
  • COLOR_SETTING_TRUE: Force colors ON - always colorize regardless of TTY/piping/CLAUDECODE
  • COLOR_SETTING_FALSE: Force colors OFF - disable all colors and logging colors
Enumerator
COLOR_SETTING_AUTO 

Smart detection (default): colors if TTY and not CLAUDECODE and not piping.

COLOR_SETTING_TRUE 

Force colors ON: always colorize regardless of TTY/piping/CLAUDECODE.

COLOR_SETTING_FALSE 

Force colors OFF: disable all colors and logging colors.

Definition at line 244 of file options.h.

244 {
color_setting_t
For options state, this is the live record that ties detected_mode, mode_arg_index,...
Definition options.h:244
@ COLOR_SETTING_TRUE
Force colors ON: always colorize regardless of TTY/piping/CLAUDECODE.
Definition options.h:248
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.
Definition options.h:250
@ COLOR_SETTING_AUTO
Smart detection (default): colors if TTY and not CLAUDECODE and not piping.
Definition options.h:246

◆ option_group_t

#include <include/ascii-chat/options/groups.h>

Option group identifiers.

Bit flags that identify groups of related options. These can be combined to specify which option groups a mode supports.

Enumerator
OPT_GROUP_NONE 

No groups.

OPT_GROUP_BINARY 

Binary-level options (help, version, logging).

OPT_GROUP_TERMINAL 

Terminal dimension options (width, height).

OPT_GROUP_NETWORK 

Network options (address, port, reconnect).

OPT_GROUP_WEBCAM 

Webcam options (device, flip, test pattern).

OPT_GROUP_DISPLAY 

Display options (color mode, palette, render mode).

OPT_GROUP_AUDIO 

Audio options (enable, devices, volume).

OPT_GROUP_SNAPSHOT 

Snapshot mode options.

OPT_GROUP_CRYPTO 

Encryption and authentication options.

OPT_GROUP_COMPRESSION 

Compression options.

OPT_GROUP_ACDS 

ACDS discovery service options.

OPT_GROUP_MEDIA 

Media file streaming options.

OPT_GROUP_SERVER 

Server-specific options (max_clients, client-keys).

OPT_GROUP_CLIENT 

Client-specific options (reconnect, server-key).

OPT_GROUP_WEBRTC 

WebRTC connectivity options (STUN/TURN).

Definition at line 56 of file groups.h.

56 {
57 OPT_GROUP_NONE = 0,
59 (1 << 0),
60 OPT_GROUP_TERMINAL = (1 << 1),
61 OPT_GROUP_NETWORK = (1 << 2),
62 OPT_GROUP_WEBCAM = (1 << 3),
64 (1 << 4),
65 OPT_GROUP_AUDIO = (1 << 5),
66 OPT_GROUP_SNAPSHOT = (1 << 6),
67 OPT_GROUP_CRYPTO = (1 << 7),
68 OPT_GROUP_COMPRESSION = (1 << 8),
69 OPT_GROUP_ACDS = (1 << 9),
70 OPT_GROUP_MEDIA = (1 << 10),
72 (1 << 11),
74 (1 << 12),
75 OPT_GROUP_WEBRTC = (1 << 13),
option_group_t
Option group identifiers.
Definition groups.h:56
@ OPT_GROUP_DISPLAY
Display options (color mode, palette, render mode).
Definition groups.h:63
@ OPT_GROUP_CLIENT
Client-specific options (reconnect, server-key).
Definition groups.h:73
@ OPT_GROUP_AUDIO
Audio options (enable, devices, volume).
Definition groups.h:65
@ OPT_GROUP_SNAPSHOT
Snapshot mode options.
Definition groups.h:66
@ OPT_GROUP_TERMINAL
Terminal dimension options (width, height).
Definition groups.h:60
@ OPT_GROUP_NONE
No groups.
Definition groups.h:57
@ OPT_GROUP_WEBCAM
Webcam options (device, flip, test pattern).
Definition groups.h:62
@ OPT_GROUP_MEDIA
Media file streaming options.
Definition groups.h:70

◆ option_mode_bitmask_t

#include <include/ascii-chat/options/options.h>

Option mode bitmask.

Indicates which modes an option applies to. Options can apply to multiple modes by combining bitmasks with bitwise OR.

Enumerator
OPTION_MODE_NONE 

No modes (invalid).

OPTION_MODE_SERVER 

Server mode (bit 0).

OPTION_MODE_CLIENT 

Client mode (bit 1).

OPTION_MODE_MIRROR 

Mirror mode (bit 2).

OPTION_MODE_DISCOVERY_SVC 

Discovery server mode (bit 3).

OPTION_MODE_DISCOVERY 

Discovery mode (bit 4).

OPTION_MODE_MCP_SERVER 
OPTION_MODE_API_SERVER 
OPTION_MODE_BINARY 

Binary-level options (parsed before mode detection).

OPTION_MODE_ALL 

All modes + binary.

Definition at line 933 of file options.h.

933 {
934 OPTION_MODE_NONE = 0,
942 OPTION_MODE_BINARY = 0x100,
943 OPTION_MODE_ALL = 0x7F | 0x100
@ OPTION_MODE_API_SERVER
Definition options.h:941
@ OPTION_MODE_DISCOVERY
Discovery mode (bit 4).
Definition options.h:939
@ OPTION_MODE_NONE
No modes (invalid).
Definition options.h:934
@ OPTION_MODE_MCP_SERVER
Definition options.h:940

◆ utf8_setting_t

#include <include/ascii-chat/options/options.h>

UTF-8 support setting (–utf8 flag values).

Enumeration for the –utf8 option which controls UTF-8 support behavior:

  • UTF8_SETTING_AUTO: Smart detection (default) - UTF-8 if terminal supports it
  • UTF8_SETTING_TRUE: Force UTF-8 ON - always use UTF-8 regardless of terminal capability
  • UTF8_SETTING_FALSE: Force UTF-8 OFF - disable UTF-8 support
Enumerator
UTF8_SETTING_AUTO 

Smart detection (default): UTF-8 if terminal supports it.

UTF8_SETTING_TRUE 

Force UTF-8 ON: always use UTF-8 regardless of terminal capability.

UTF8_SETTING_FALSE 

Force UTF-8 OFF: disable UTF-8 support.

Definition at line 263 of file options.h.

263 {
utf8_setting_t
UTF-8 support setting (–utf8 flag values).
Definition options.h:263
@ UTF8_SETTING_AUTO
Smart detection (default): UTF-8 if terminal supports it.
Definition options.h:265
@ UTF8_SETTING_FALSE
Force UTF-8 OFF: disable UTF-8 support.
Definition options.h:269
@ UTF8_SETTING_TRUE
Force UTF-8 ON: always use UTF-8 regardless of terminal capability.
Definition options.h:267

Function Documentation

◆ escape_groff_special()

const char * escape_groff_special ( const char * str)

#include <include/ascii-chat/options/manpage.h>

Escape special groff/troff characters in text.

Converts special characters (-, \, etc.) to groff escape sequences so they display correctly in man pages.

Parameters
strInput string to escape
Returns
Escaped string (static buffer, valid until next call)
Note
Result is stored in static buffer, do not free

Definition at line 46 of file manpage.c.

46{ return str ? str : ""; }

Referenced by manpage_content_generate_examples(), manpage_content_generate_options(), manpage_content_generate_positional(), and manpage_content_generate_usage().

◆ find_section()

const parsed_section_t * find_section ( const parsed_section_t * sections,
size_t num_sections,
const char * section_name )

#include <include/ascii-chat/options/manpage.h>

Find section by name.

Parameters
sectionsArray of parsed sections
num_sectionsNumber of sections
section_nameSection name to find (case-sensitive)
Returns
Pointer to section, or NULL if not found

Definition at line 836 of file manpage.c.

838 {
839 return manpage_parser_find_section(sections, num_sections, section_name);
840}
const parsed_section_t * manpage_parser_find_section(const parsed_section_t *sections, size_t count, const char *section_name)
Find section by name.
Definition parser.c:404

References manpage_parser_find_section().

◆ format_mode_names()

const char * format_mode_names ( option_mode_bitmask_t bitmask)

#include <include/ascii-chat/options/manpage.h>

Format option mode names as human-readable string.

Converts bitmask of modes into a readable format for man pages. For example: MODE_BINARY | MODE_SERVER -> "binary, server"

Parameters
bitmaskBitmask of option_mode_t values
Returns
Formatted string (static buffer, valid until next call)
Note
Result is stored in static buffer, do not free

Definition at line 48 of file manpage.c.

48 {
49 if (mode_bitmask == 0) {
50 return NULL;
51 }
52
53 option_mode_bitmask_t user_modes_mask =
54 (1 << MODE_SERVER) | (1 << MODE_CLIENT) | (1 << MODE_MIRROR) |
56 (1 << MODE_MCP_SERVER);
57 if ((mode_bitmask & OPTION_MODE_BINARY) &&
58 !(mode_bitmask & user_modes_mask)) {
59 return "global";
60 }
61 if ((mode_bitmask & user_modes_mask) == user_modes_mask) {
62 // If all user modes are set, check if binary-level is also set
63 if (mode_bitmask & OPTION_MODE_BINARY) {
64 return "global, client, server, mirror, discovery-service, mcp-server";
65 }
66 return "all modes";
67 }
68
69 static char mode_str[OPTIONS_MANPAGE_MODE_BUFFER_SIZE];
70 mode_str[0] = '\0';
71 int pos = 0;
72
73 // Add global if binary-level is set
74 if (mode_bitmask & OPTION_MODE_BINARY) {
75 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "global");
76 }
77
78 // List modes in order: default, client, server, mirror, discovery-service
79 if (mode_bitmask & (1 << MODE_DISCOVERY)) {
80 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sdefault",
81 pos > 0 ? ", " : "");
82 }
83 if (mode_bitmask & (1 << MODE_CLIENT)) {
84 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sclient",
85 pos > 0 ? ", " : "");
86 }
87 if (mode_bitmask & (1 << MODE_SERVER)) {
88 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sserver",
89 pos > 0 ? ", " : "");
90 }
91 if (mode_bitmask & (1 << MODE_MIRROR)) {
92 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%smirror",
93 pos > 0 ? ", " : "");
94 }
95 if (mode_bitmask & (1 << MODE_DISCOVERY_SERVICE)) {
96 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos,
97 "%sdiscovery-service", pos > 0 ? ", " : "");
98 }
99
100 if (mode_bitmask & (1 << MODE_MCP_SERVER)) {
101 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%smcp-server",
102 pos > 0 ? ", " : "");
103 }
104
105 return pos > 0 ? mode_str : NULL;
106}
#define OPTIONS_MANPAGE_MODE_BUFFER_SIZE
Definition manpage.c:15

References MODE_CLIENT, MODE_DISCOVERY, MODE_DISCOVERY_SERVICE, MODE_MCP_SERVER, MODE_MIRROR, MODE_SERVER, OPTION_MODE_BINARY, and OPTIONS_MANPAGE_MODE_BUFFER_SIZE.

Referenced by manpage_content_generate_options().

◆ free_parsed_sections()

void free_parsed_sections ( parsed_section_t * sections,
size_t num_sections )

#include <include/ascii-chat/options/manpage.h>

Free parsed sections array.

Parameters
sectionsArray of parsed sections (can be NULL)
num_sectionsNumber of sections

Definition at line 832 of file manpage.c.

832 {
833 manpage_parser_free_sections(sections, num_sections);
834}
void manpage_parser_free_sections(parsed_section_t *sections, size_t count)
Free parsed sections array.
Definition parser.c:387

References manpage_parser_free_sections().

◆ has_action_flag()

bool has_action_flag ( void )

#include <include/ascii-chat/options/options.h>

Check if an action flag was detected.

Returns
true if an action flag was passed (–show-capabilities, –list-webcams, etc.)

Used by action implementations to enable output logging temporarily. When an action is passed, the logging system is disabled before the action runs to keep output clean. Actions can use this to re-enable logging if needed.

Returns
true if an action flag was passed

Definition at line 280 of file options.c.

280{ return g_action_flag; }

◆ is_remote_key_path()

bool is_remote_key_path ( const char * key_path)

#include <include/ascii-chat/options/validation.h>

Check if a key path is a remote/virtual key (not a local file).

Parameters
key_pathKey path to check
Returns
true if the key is remote (github:, gitlab:, gpg:, http://, https://), false otherwise

Remote keys are fetched at runtime and don't need file existence validation.

Definition at line 597 of file validation.c.

597 {
598 if (!key_path || key_path[0] == '\0') {
599 return false;
600 }
601 return (strncmp(key_path, "github:", 7) == 0 || strncmp(key_path, "gitlab:", 7) == 0 || strncmp(key_path, "gpg:", 4) == 0 || strncmp(key_path, "http://", 7) == 0 ||
602 strncmp(key_path, "https://", 8) == 0);
603}

Referenced by options_collect_identity_keys().

◆ levenshtein()

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

#include <include/ascii-chat/options/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 79 of file levenshtein.c.

79 {
80 if (!a || !b) {
81 return SIZE_MAX;
82 }
83
84 // Count UTF-8 characters instead of bytes
85 size_t char_count_a = utf8_char_count(a);
86 size_t char_count_b = utf8_char_count(b);
87
88 if (char_count_a == SIZE_MAX || char_count_b == SIZE_MAX) {
89 return SIZE_MAX; // Invalid UTF-8 in one of the strings
90 }
91
92 // Convert strings to codepoint arrays for UTF-8-aware comparison
93 if (char_count_a == 0) {
94 return char_count_b;
95 }
96 if (char_count_b == 0) {
97 return char_count_a;
98 }
99
100 SAFE_MALLOC_DEFER_FREE(codepoints_a, char_count_a * sizeof(uint32_t),
101 uint32_t *);
102 SAFE_MALLOC_DEFER_FREE(codepoints_b, char_count_b * sizeof(uint32_t),
103 uint32_t *);
104
105 if (!codepoints_a || !codepoints_b) {
106 return SIZE_MAX;
107 }
108
109 size_t decoded_a = utf8_to_codepoints(a, codepoints_a, char_count_a);
110 size_t decoded_b = utf8_to_codepoints(b, codepoints_b, char_count_b);
111
112 if (decoded_a == SIZE_MAX || decoded_b == SIZE_MAX) {
113 return SIZE_MAX;
114 }
115
116 // Compute Levenshtein distance on codepoint arrays
117 SAFE_CALLOC_DEFER_FREE(cache, char_count_a * sizeof(size_t), 1, size_t *);
118 if (!cache) {
119 return SIZE_MAX;
120 }
121
122 // Initialize cache
123 for (size_t i = 0; i < char_count_a; i++) {
124 cache[i] = i + 1;
125 }
126
127 size_t distance = 0;
128 size_t result = 0;
129 for (size_t b_idx = 0; b_idx < char_count_b; b_idx++) {
130 uint32_t b_code = codepoints_b[b_idx];
131 result = distance = b_idx;
132
133 for (size_t a_idx = 0; a_idx < char_count_a; a_idx++) {
134 uint32_t a_code = codepoints_a[a_idx];
135 size_t b_distance = (a_code == b_code) ? distance : distance + 1;
136 distance = cache[a_idx];
137
138 cache[a_idx] = result =
139 (distance > result)
140 ? ((b_distance > result) ? result + 1 : b_distance)
141 : ((b_distance > distance) ? distance + 1 : b_distance);
142 }
143 }
144
145 return result;
146}
unsigned int uint32_t
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
size_t utf8_to_codepoints(const char *str, uint32_t *out_codepoints, size_t max_codepoints)
Convert UTF-8 string to array of Unicode codepoints.
Definition utf8.c:161
size_t utf8_char_count(const char *str)
Count UTF-8 characters (not bytes).
Definition utf8.c:112

References SAFE_CALLOC_DEFER_FREE, SAFE_MALLOC_DEFER_FREE, utf8_char_count(), and utf8_to_codepoints().

Referenced by find_similar_option_with_mode(), and levenshtein_find_similar().

◆ levenshtein_find_similar()

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

#include <include/ascii-chat/options/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 148 of file levenshtein.c.

149 {
150 if (!unknown || !candidates) {
151 return NULL;
152 }
153
154 const char *best_match = NULL;
155 size_t best_distance = SIZE_MAX;
156
157 for (int i = 0; candidates[i] != NULL; i++) {
158 size_t dist = levenshtein(unknown, candidates[i]);
159 if (dist < best_distance) {
160 best_distance = dist;
161 best_match = candidates[i];
162 }
163 }
164
165 // Only suggest if the distance is within our threshold
166 if (best_distance <= LEVENSHTEIN_SUGGESTION_THRESHOLD) {
167 return best_match;
168 }
169
170 return NULL;
171}
size_t levenshtein(const char *a, const char *b)
Calculate Levenshtein distance between two strings.
Definition levenshtein.c:79
#define LEVENSHTEIN_SUGGESTION_THRESHOLD
Maximum edit distance to suggest an option.
Definition levenshtein.h:32

References levenshtein(), and LEVENSHTEIN_SUGGESTION_THRESHOLD.

Referenced by asciichat_suggest_enum_value(), and asciichat_suggest_mode().

◆ levenshtein_n()

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

#include <include/ascii-chat/options/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 25 of file levenshtein.c.

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

References index, SAFE_CALLOC, and SAFE_FREE.

◆ options_builder_generate_manpage_template()

asciichat_error_t options_builder_generate_manpage_template ( options_builder_t * builder,
const char * program_name,
const char * mode_name,
const char * output_path,
const char * brief_description )

#include <include/ascii-chat/options/manpage.h>

Generate man page template from builder (before build()).

Convenience wrapper that builds the config from the builder, generates the template, and cleans up.

Parameters
builderOptions builder
program_nameProgram name
mode_nameMode name (or NULL)
output_pathOutput file path
brief_descriptionBrief description
Returns
ASCIICHAT_OK on success, error code otherwise

Definition at line 244 of file manpage.c.

246 {
247 if (!builder || !program_name || !brief_description) {
248 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing required parameters");
249 }
250
251 const options_config_t *config = options_builder_build(builder);
252 if (!config) {
253 return SET_ERRNO(ERROR_CONFIG, "Failed to build options configuration");
254 }
255
257 config, program_name, mode_name, output_path, brief_description);
258}
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
asciichat_error_t options_config_generate_manpage_template(const options_config_t *config, const char *program_name, const char *mode_name, const char *output_path, const char *brief_description)
Generate a man page template from options builder configuration.
Definition manpage.c:112

References ERROR_CONFIG, ERROR_INVALID_PARAM, options_builder_build(), options_config_generate_manpage_template(), and SET_ERRNO.

◆ options_collect_identity_keys()

int options_collect_identity_keys ( options_t * opts,
int argc,
char * argv[] )

#include <include/ascii-chat/options/validation.h>

Collect multiple –key flags into identity_keys array.

Parameters
optsOptions structure to populate
argcArgument count from main()
argvArgument vector from main()
Returns
Number of keys collected on success, -1 on error

Scans command-line arguments for all –key/-K flags and populates both opts->encrypt_key (first key, for compatibility) and opts->identity_keys[] array with all keys. Also sets opts->num_identity_keys.

This enables multi-key support: servers can load multiple identity keys (e.g., both SSH and GPG) and select the appropriate one during handshake based on what the client expects.

Note
Must be called after options_parse() but before key loading
Supports up to MAX_SESSION_KEYS (32) keys

Collect multiple –key flags into identity_keys array

Scans argv for all –key or -K flags and populates:

  • opts->encrypt_key with the first key (backward compatibility)
  • opts->identity_keys[] with all keys
  • opts->num_identity_keys with count

This enables multi-key support for servers/ACDS that need to present different identity keys (SSH, GPG) based on client expectations.

Definition at line 525 of file validation.c.

525 {
526 if (!opts || !argv) {
527 log_error("Invalid arguments");
528 return -1;
529 }
530
531 size_t key_count = 0;
532
533 // Scan argv for all --key or -K flags
534 for (int i = 1; i < argc; i++) {
535 const char *arg = argv[i];
536
537 // Check if this is a --key or -K flag
538 bool is_key_flag = false;
539 const char *key_value = NULL;
540
541 if (strcmp(arg, "--key") == 0 || strcmp(arg, "-K") == 0) {
542 // Next argument is the key path
543 if (i + 1 < argc) {
544 key_value = argv[i + 1];
545 is_key_flag = true;
546 i++; // Skip the value argument
547 }
548 } else if (strncmp(arg, "--key=", 6) == 0) {
549 // --key=value format
550 key_value = arg + 6;
551 is_key_flag = true;
552 }
553
554 if (is_key_flag && key_value && strlen(key_value) > 0) {
555 if (key_count >= MAX_SESSION_KEYS || strlen(key_value) >= sizeof(opts->identity_keys[0])) {
556 SET_ERRNO(ERROR_INVALID_PARAM, "Too many identity keys or key path exceeds storage capacity");
557 return -1;
558 }
559 // Validate that local key files exist (skip for remote/virtual keys)
560 if (!is_remote_key_path(key_value)) {
561 struct stat st;
562 if (stat(key_value, &st) != 0) {
563 log_error("Key file not found: %s", key_value);
564 SET_ERRNO(ERROR_CRYPTO_KEY, "Key file not found: %s", key_value);
565 return -1;
566 }
567 // Check if it's a regular file (S_IFREG) - works on both Windows and Unix
568 if ((st.st_mode & S_IFMT) != S_IFREG) {
569 log_error("Key path is not a regular file: %s", key_value);
570 SET_ERRNO(ERROR_CRYPTO_KEY, "Key path is not a regular file: %s", key_value);
571 return -1;
572 }
573 }
574
575 // Store in identity_keys array
576 SAFE_STRNCPY(opts->identity_keys[key_count], key_value, OPTIONS_BUFF_SIZE);
577
578 // First key also goes into encrypt_key for backward compatibility
579 if (key_count == 0) {
580 SAFE_STRNCPY(opts->encrypt_key, key_value, OPTIONS_BUFF_SIZE);
581 }
582
583 key_count++;
584 log_debug("Collected identity key #%zu: %s", key_count, key_value);
585 }
586 }
587
588 opts->num_identity_keys = key_count;
589
590 if (key_count > 0) {
591 log_info("Collected %zu identity key(s) for multi-key support", key_count);
592 }
593
594 return (int)key_count;
595}
#define SAFE_STRNCPY(dst, src, size)
@ ERROR_CRYPTO_KEY
#define MAX_SESSION_KEYS
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
bool is_remote_key_path(const char *key_path)
Check if a key path is a remote/virtual key (not a local file).
Definition validation.c:597
size_t num_identity_keys
Number of identity keys loaded (0 means single-key mode using encrypt_key).
Definition options.h:1183
char identity_keys[32][256]
All identity keys (populated when –key is used multiple times).
Definition options.h:1182
char encrypt_key[256]
SSH/GPG key file path (first –key flag, kept for compatibility).
Definition options.h:1172

References options_state::encrypt_key, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, options_state::identity_keys, is_remote_key_path(), log_debug, log_error, log_info, MAX_SESSION_KEYS, options_state::num_identity_keys, OPTIONS_BUFF_SIZE, SAFE_STRNCPY, and SET_ERRNO.

◆ options_config_generate_final_manpage()

asciichat_error_t options_config_generate_final_manpage ( const char * template_path,
const char * output_path,
const char * version_string,
const char * content_file_path )

#include <include/ascii-chat/options/manpage.h>

Generate final man page (.1) from template (.1.in) with version substitution and optional content file.

Parameters
template_pathPath to input template (.1.in file)
output_pathPath to output man page (.1 file)
version_stringVersion string to substitute for @PROJECT_VERSION@
content_file_pathOptional path to file containing additional content to insert (NULL if none)
Returns
ASCIICHAT_OK on success, error code on failure
Note
This performs the same substitution as ConfigureManPage.cmake
If content_file_path is provided, its content is parsed and merged into appropriate sections
Only available in debug builds (when NDEBUG is not defined)

Definition at line 843 of file manpage.c.

845 {
846 (void)template_path;
847 (void)output_path;
848 (void)version_string;
849 (void)content_file_path;
850 return SET_ERRNO(ERROR_CONFIG, "Not implemented in refactored version");
851}

References ERROR_CONFIG, and SET_ERRNO.

◆ options_config_generate_manpage_merged()

asciichat_error_t options_config_generate_manpage_merged ( const options_config_t * config,
const char * program_name,
const char * mode_name,
const char * output_path,
const char * brief_description )

#include <include/ascii-chat/options/manpage.h>

Generate merged man page template preserving manual content.

Parses existing template (if exists) and merges auto-generated content with manual content based on section markers:

  • AUTO sections: Fully regenerated from builder
  • MANUAL sections: Preserved exactly as-is
  • MERGE sections: Intelligently merged (e.g., ENVIRONMENT vars)
Parameters
configFinalized options configuration
program_nameProgram name (e.g., "ascii-chat")
mode_nameMode name (e.g., "server", "client", or NULL)
output_pathFile path to write merged template to
brief_descriptionOne-line program description
existing_template_pathPath to existing template (NULL if none)
Returns
ASCIICHAT_OK on success, error code on failure
Note
If existing_template_path is NULL, generates fresh template
Unmarked sections default to MANUAL (preserved)

Generate merged man page from options builder and embedded resources

Generates a merged man page by combining auto-generated content from the options builder with manual sections from embedded resources. Automatically selects between embedded resources (production builds) and filesystem resources (development builds).

Resource Loading:

  • Template: Loads ascii-chat.1.in template from embedded resources or filesystem
  • Content: Loads ascii-chat.1.content sections from embedded resources or filesystem
  • Merging: Intelligently merges AUTO, MANUAL, and MERGE-marked sections
Parameters
configFinalized options configuration
program_nameProgram name (e.g., "ascii-chat")
mode_nameMode name (e.g., "server", "client", or NULL for binary-level)
output_pathOutput file path, or NULL to write to stdout
brief_descriptionOne-line program description
Returns
ASCIICHAT_OK on success, error code on failure
Note
If output_path is NULL, writes to stdout
Resources are loaded automatically from embedded or filesystem based on build type
Deprecated
The old signature with explicit file paths is no longer supported. Resources are now loaded automatically from embedded resources.

Definition at line 756 of file manpage.c.

759 {
760 (void)mode_name; // Not used
761 (void)program_name; // Not used
762 (void)brief_description; // Not used
763
764 if (!config) {
766 "config is required for man page generation");
767 }
768
769 FILE *f = NULL;
770 bool should_close = false;
772 manpage_open_merged_output(output_path, &f, &should_close);
773 if (err != ASCIICHAT_OK) {
774 return err;
775 }
776
777 // Load template resources
778 manpage_resources_t resources;
779 memset(&resources, 0, sizeof(resources));
780 err = manpage_resources_load(&resources);
781 if (err != ASCIICHAT_OK) {
782 if (should_close)
783 fclose(f);
784 return err;
785 }
786
787 if (!manpage_resources_is_valid(&resources)) {
788 if (should_close)
789 fclose(f);
790 manpage_resources_destroy(&resources);
791 return SET_ERRNO(ERROR_CONFIG, "Man page resources are not valid");
792 }
793
794 manpage_merge_template(f, config, resources.template_content);
795
796 manpage_resources_destroy(&resources);
797
798 fflush(f);
799 if (should_close) {
800 fclose(f);
801 }
802
803 log_debug("Generated merged man page to %s",
804 output_path ? output_path : "stdout");
805 return ASCIICHAT_OK;
806}
void manpage_resources_destroy(manpage_resources_t *resources)
Cleanup allocated man page resources.
Definition resources.c:143
asciichat_error_t manpage_resources_load(manpage_resources_t *resources)
Load man page resources from embedded or filesystem sources.
Definition resources.c:100
bool manpage_resources_is_valid(const manpage_resources_t *resources)
Check if resources are available.
Definition resources.c:172
Man page resource container.
Definition resources.h:27
const char * template_content
Template file content (.1.in).
Definition resources.h:28

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, log_debug, manpage_resources_destroy(), manpage_resources_is_valid(), manpage_resources_load(), SET_ERRNO, and manpage_resources_t::template_content.

◆ options_config_generate_manpage_template()

asciichat_error_t options_config_generate_manpage_template ( const options_config_t * config,
const char * program_name,
const char * mode_name,
const char * output_path,
const char * brief_description )

#include <include/ascii-chat/options/manpage.h>

Generate a man page template from options builder configuration.

Creates a man page template at the specified path with auto-generated sections:

  • .TH (title/header)
  • NAME (auto: program-name — brief description)
  • SYNOPSIS (auto: generated from usage descriptors)
  • USAGE (auto: generated from usage descriptors with descriptions)
  • OPTIONS (auto: generated from option descriptors, grouped by category)
  • EXAMPLES (auto: generated from example descriptors)
  • POSITIONAL ARGUMENTS (auto: generated from positional arg descriptors)
  • ENVIRONMENT VARIABLES (auto: extracted from options with env_var_name set)

Manual sections provided as placeholders:

  • DESCRIPTION (manual: add program overview)
  • FILES (manual: add configuration files)
  • NOTES (manual: add additional notes)
  • BUGS (manual: add known bugs)
  • AUTHOR (manual: add author information)
  • SEE ALSO (manual: add related commands)

Format Notes:

  • Output is in groff/troff format suitable for man command
  • Section headers use .SH directive
  • Bold/italic/constant formatting uses .B, .I, .C directives
  • Options are formatted with short form (-x) and long form (–long-name)

Example Usage:

options_builder_create(sizeof(server_options_t));
// ... add options ...
builder,
"ascii-chat",
"server",
"ascii-chat-server.1",
"Interactive terminal-based video chat"
);
if (err != ASCIICHAT_OK) {
fprintf(stderr, "Failed to generate man page\n");
}
asciichat_error_t options_builder_generate_manpage_template(options_builder_t *builder, const char *program_name, const char *mode_name, const char *output_path, const char *brief_description)
Generate man page template from builder (before build()).
Definition manpage.c:244
Parameters
configFinalized options configuration (from options_builder_build)
program_nameProgram name (e.g., "ascii-chat")
mode_nameMode name (e.g., "server", "client", or NULL for binary-level)
output_pathFile path to write man page template to
brief_descriptionOne-line program description
Returns
ASCIICHAT_OK on success, ERROR_USAGE or ERROR_FILE on failure
Note
Creates or overwrites the file at output_path
Brief description should be short and start with lowercase
Man section number is auto-determined (1 for user commands, 5 for files)

Definition at line 112 of file manpage.c.

115 {
116 if (!config || !program_name || !brief_description) {
118 "Missing required parameters for man page generation");
119 }
120
121 FILE *f = NULL;
122 bool should_close = false;
123
124 if (output_path) {
125 f = platform_fopen("file_stream", output_path, "w");
126 if (!f) {
127 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open output file: %s",
128 output_path);
129 }
130 should_close = true;
131 } else {
132 f = stdout;
133 }
134
135 // Write title/header
136 manpage_fmt_write_title(f, program_name, mode_name, brief_description);
137
138 // Write SYNOPSIS
139 char *synopsis_content = NULL;
140 size_t synopsis_len = 0;
142 mode_name, &synopsis_content, &synopsis_len);
143 if (err == ASCIICHAT_OK && synopsis_content && synopsis_len > 0) {
144 fprintf(f, "%s", synopsis_content);
145 manpage_merger_free_content(synopsis_content);
146 }
147
148 // Write POSITIONAL ARGUMENTS if present
149 if (config->num_positional_args > 0) {
150 char *pos_content = manpage_content_generate_positional(config);
151 if (pos_content && *pos_content != '\0') {
152 fprintf(f, "%s", pos_content);
153 }
155 }
156
157 // Write DESCRIPTION
158 manpage_fmt_write_section(f, "DESCRIPTION");
159 fprintf(f, ".B ascii-chat\nis a terminal-based video chat application that "
160 "converts webcam video to ASCII\n");
161 fprintf(f, "art in real-time. It enables video chat directly in your "
162 "terminal, whether you're\n");
163 fprintf(f, "using a local console, a remote SSH session, or any terminal "
164 "emulator.\n");
166
167 // Write USAGE
168 char *usage_content = NULL;
169 size_t usage_len = 0;
170 err = manpage_merger_generate_usage(config, &usage_content, &usage_len);
171 if (err == ASCIICHAT_OK && usage_content && usage_len > 0) {
172 fprintf(f, ".SH USAGE\n%s", usage_content);
173 manpage_merger_free_content(usage_content);
174 }
175
176 // Write OPTIONS
177 if (config->num_descriptors > 0) {
178 char *options_content = manpage_content_generate_options(config);
179 if (options_content && *options_content != '\0') {
180 fprintf(f, "%s", options_content);
181 }
182 manpage_content_free_options(options_content);
183 }
184
185 // Write EXAMPLES if present
186 if (config->num_examples > 0) {
187 char *examples_content = manpage_content_generate_examples(config);
188 if (examples_content && *examples_content != '\0') {
189 fprintf(f, "%s", examples_content);
190 }
191 manpage_content_free_examples(examples_content);
192 }
193
194 // Write ENVIRONMENT if present
195 bool has_env_vars = false;
196 for (size_t i = 0; i < config->num_descriptors; i++) {
197 if (config->descriptors[i].env_var_name) {
198 has_env_vars = true;
199 break;
200 }
201 }
202
203 if (has_env_vars) {
204 char *env_content = manpage_content_generate_environment(config);
205 if (env_content && *env_content != '\0') {
206 fprintf(f, "%s", env_content);
207 }
209 }
210
211 // Write placeholder manual sections
212 manpage_fmt_write_section(f, "FILES");
213 fprintf(f, ".I ~/.ascii-chat/config.toml\n");
214 fprintf(f, "User configuration file\n");
216
217 manpage_fmt_write_section(f, "NOTES");
218 fprintf(f,
219 "For more information and examples, visit the project repository.\n");
221
222 manpage_fmt_write_section(f, "BUGS");
223 fprintf(f, "Report bugs at the project issue tracker.\n");
225
226 manpage_fmt_write_section(f, "AUTHOR");
227 fprintf(f, "Contributed by the ascii-chat community.\n");
229
230 manpage_fmt_write_section(f, "SEE ALSO");
231 fprintf(f, ".B man(1),\n");
232 fprintf(f, ".B groff_man(7)\n");
234
235 if (should_close) {
236 fclose(f);
237 }
238
239 log_debug("Generated man page template to %s",
240 output_path ? output_path : "stdout");
241 return ASCIICHAT_OK;
242}
#define SET_ERRNO_SYS(code,...)
void manpage_content_free_environment(char *content)
Free generated environment content.
char * manpage_content_generate_environment(const options_config_t *config)
Generate ENVIRONMENT VARIABLES section content.
Definition environment.c:14
char * manpage_content_generate_examples(const options_config_t *config)
Generate EXAMPLES section content.
Definition examples.c:81
void manpage_content_free_examples(char *content)
Free generated examples content.
Definition examples.c:148
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
void manpage_fmt_write_title(FILE *f, const char *program_name, const char *mode_name, const char *brief_description)
Write groff title/header (.TH directive).
Definition formatter.c:79
void manpage_fmt_write_section(FILE *f, const char *section_name)
Write a section header directive.
Definition formatter.c:32
void manpage_fmt_write_blank_line(FILE *f)
Write a blank line (for spacing between sections).
Definition formatter.c:39
char * manpage_content_generate_options(const options_config_t *config)
Generate OPTIONS section content.
void manpage_content_free_options(char *content)
Free generated options content.
asciichat_error_t manpage_merger_generate_usage(const options_config_t *config, char **out_content, size_t *out_len)
Get auto-generated usage content.
Definition merger.c:82
void manpage_merger_free_content(char *content)
Free merged section content.
Definition merger.c:182
asciichat_error_t manpage_merger_generate_synopsis(const char *mode_name, char **out_content, size_t *out_len)
Get auto-generated synopsis content.
Definition merger.c:140
void manpage_content_free_positional(char *content)
Free generated positional content.
Definition positional.c:72
char * manpage_content_generate_positional(const options_config_t *config)
Generate POSITIONAL ARGUMENTS section content.
Definition positional.c:15
const char * env_var_name
Environment variable fallback (or NULL).
Definition builder.h:293
option_descriptor_t * descriptors
Array of option descriptors.
Definition builder.h:457
size_t num_positional_args
Number of positional arguments.
Definition builder.h:465
size_t num_descriptors
Number of descriptors.
Definition builder.h:458
size_t num_examples
Number of examples.
Definition builder.h:476

References ASCIICHAT_OK, options_config_t::descriptors, option_descriptor_t::env_var_name, ERROR_CONFIG, ERROR_INVALID_PARAM, log_debug, manpage_content_free_environment(), manpage_content_free_examples(), manpage_content_free_options(), manpage_content_free_positional(), manpage_content_generate_environment(), manpage_content_generate_examples(), manpage_content_generate_options(), manpage_content_generate_positional(), manpage_fmt_write_blank_line(), manpage_fmt_write_section(), manpage_fmt_write_title(), manpage_merger_free_content(), manpage_merger_generate_synopsis(), manpage_merger_generate_usage(), options_config_t::num_descriptors, options_config_t::num_examples, options_config_t::num_positional_args, platform_fopen(), SET_ERRNO, and SET_ERRNO_SYS.

Referenced by options_builder_generate_manpage_template().

◆ options_get()

const options_t * options_get ( void )

#include <include/ascii-chat/options/options.h>

Get current options (lock-free read).

Get pointer to current options struct (lock-free, thread-safe).

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())

Returns a pointer to the currently published options struct or a safe static default if options haven't been initialized yet (before options_state_init()) or after options have been destroyed (options_state_destroy()).

This function is specifically designed to be safe to call:

  • Before initialization: Early startup code gets sensible defaults
  • During normal operation: Lock-free atomic load with no blocking
  • During cleanup: atexit handlers and shutdown code get fallback defaults
  • After destruction: Code after options_state_destroy() still works

Return Behavior

Returns pointer to either:

  1. Published dynamic options (after options_state_init() and before options_state_destroy())
  2. Static fallback defaults (before init or after destroy)

The static fallback ensures:

  • Never NULL: Code never crashes on NULL pointer dereference
  • Sensible defaults: All OPT_*_DEFAULT constants properly initialized
  • Static lifetime: Outlives all dynamically allocated options structs
  • No cleanup needed: Static memory never freed
  • Thread-safe: Immutable const data, safe to read from any thread

Usage Example

// Safe before options_state_init()
const options_t *opts = options_get();
printf("Default width: %d\n", opts->width);
// After initialization
options_state_set(&parsed_opts);
opts = options_get(); // Returns published struct
// Safe after options_state_destroy()
opts = options_get(); // Returns static defaults again
// Can still safely call GET_OPTION() in atexit handlers
Returns
Pointer to options_t struct (guaranteed never NULL)
Note
Thread-safe: Lock-free atomic load with acquire semantics
Lock-free: No mutexes or blocking calls
Fast: Single atomic instruction (~1-2ns latency)
Fallback support: Returns static defaults when not initialized or after destroy
See also
options_state_init() - Initializes Options Module, publishes to RCU
options_state_destroy() - Clears Options Module, returns fallback to defaults
GET_OPTION() - Convenience macro for reading single fields

Get current options (lock-free read).

Returns a pointer to the currently published options struct or a safe static default if options haven't been initialized yet (before options_state_init()) or after options have been destroyed (options_state_destroy()).

This function is specifically designed to be safe to call:

  • Before initialization: Early startup code gets sensible defaults
  • During normal operation: Lock-free atomic load with no blocking
  • During cleanup: atexit handlers and shutdown code get fallback defaults
  • After destruction: Code after options_state_destroy() still works

Return Behavior

Returns pointer to either:

  1. Published dynamic options (after options_state_init() and before options_state_destroy())
  2. Static fallback defaults (before init or after destroy)

The static fallback ensures:

  • Never NULL: Code never crashes on NULL pointer dereference
  • Sensible defaults: All OPT_*_DEFAULT constants properly initialized
  • Static lifetime: Outlives all dynamically allocated options structs
  • No cleanup needed: Static memory never freed
  • Thread-safe: Immutable const data, safe to read from any thread

Usage Example

// Safe before options_state_init()
const options_t *opts = options_get();
printf("Default width: %d\n", opts->width);
// After initialization
options_state_set(&parsed_opts);
opts = options_get(); // Returns published struct
// Safe after options_state_destroy()
opts = options_get(); // Returns static defaults again
// Can still safely call GET_OPTION() in atexit handlers
Returns
Pointer to options_t struct (guaranteed never NULL)
Note
Thread-safe: Lock-free atomic load with acquire semantics
Lock-free: No mutexes or blocking calls
Fast: Single atomic instruction (~1-2ns latency)
Fallback support: Returns static defaults when not initialized or after destroy
See also
options_state_init() - Initializes Options Module, publishes to RCU
options_state_destroy() - Clears Options Module, returns fallback to defaults
GET_OPTION() - Convenience macro for reading single fields

Definition at line 513 of file rcu.c.

513 {
514 // Lock-free read with acquire semantics
515 // Guarantees we see all writes made before the pointer was published
516 options_t *current = atomic_ptr_load(&g_options);
517
518 // If options not yet published or after destruction, return safe static
519 // default. This is a critical fallback that:
520 // 1. Allows early startup code (before options_state_init) to work safely
521 // 2. Allows atexit handlers and cleanup code to call GET_OPTION() safely
522 // 3. Never crashes due to NULL pointer access
523 // 4. Provides sensible defaults for all option fields
524 //
525 // The static default options are:
526 // - Allocated once at startup (static storage)
527 // - Never freed (outlives all dynamically allocated options)
528 // - Thread-safe to read (immutable const data)
529 // - Complete with all OPT_*_DEFAULT values matching options_t_new()
530 if (!current) {
531 return (const options_t *)&g_default_options;
532 }
533
534 return current;
535}
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.

References atomic_ptr_load().

Referenced by acip_security_init_options(), ascii_otel_init(), client_audio_pipeline_config_for_source(), client_main(), debug_errno_start_thread(), debug_stats_start_thread(), discovery_session_create(), log_set_terminal_output(), nat_detect_quality(), options_terminal_settings_ptr(), session_protocol_build_capabilities(), and session_settings_init().

◆ options_get_help_text()

const char * options_get_help_text ( asciichat_mode_t mode,
const char * option_name )

#include <include/ascii-chat/options/options.h>

Get help text for an option in a specific mode.

Parameters
modeThe mode context (MODE_SERVER, MODE_CLIENT, MODE_MIRROR, etc.)
option_nameThe long name of the option (e.g., "color-mode", "fps")
Returns
Help text string (const, do not modify), or NULL if option doesn't apply to mode

Searches the options registry for the given option name and mode combination. Returns the help text if the option applies to the mode, or NULL otherwise.

Example:

const char *help = options_get_help_text(MODE_CLIENT, "color-mode");
if (help) {
printf("Help: %s\n", help);
} else {
printf("Option not applicable to client mode\n");
}
const char * options_get_help_text(asciichat_mode_t mode, const char *option_name)
Get help text for an option in a specific mode.
Definition help_api.c:27
Note
Returned pointer is valid for the lifetime of the program (points to static data)
Thread-safe: reads only static registry data
Parameters
modeThe mode context (MODE_SERVER, MODE_CLIENT, MODE_MIRROR, etc.)
option_nameThe long name of the option (e.g., "color-mode", "fps")
Returns
Help text string, or NULL if option doesn't apply to this mode

Searches the options registry for the given option name and checks if it applies to the requested mode. If it does, returns the help text. If the option doesn't exist or doesn't apply to the mode, returns NULL.

Definition at line 27 of file help_api.c.

28 {
29 if (!option_name || !option_name[0]) {
30 return NULL;
31 }
32
33 // Get the registry (initializes size if needed)
35
36 // Search through all registered options
37 for (size_t i = 0; i < g_registry_size; i++) {
38 const registry_entry_t *entry = &g_options_registry[i];
39
40 // Skip empty entries or entries without a long name
41 if (!entry->long_name || !entry->long_name[0]) {
42 continue;
43 }
44
45 // Check if this is the option we're looking for
46 if (strcmp(entry->long_name, option_name) != 0) {
47 continue;
48 }
49
50 // Check if this option applies to the requested mode
51 // Convert mode to bitmask for comparison
52 // Validate mode is in valid range (0-4) to avoid undefined behavior in bit
53 // shift
54 if (mode < 0 || mode >= MODE_INVALID) {
55 continue; // Skip invalid mode
56 }
57 uint32_t mode_bitmask = (1 << mode) | OPTION_MODE_BINARY;
58
59 if ((entry->mode_bitmask & mode_bitmask) == 0) {
60 // Option doesn't apply to this mode
61 return NULL;
62 }
63
64 // Return the help text (or empty string if not set)
65 return entry->help_text ? entry->help_text : "";
66 }
67
68 // Option not found
69 return NULL;
70}
void registry_init_size(void)
Initialize registry size and metadata.
Definition core.c:117
registry_entry_t g_options_registry[2048]
Definition registry.c:41
size_t g_registry_size
Definition registry.c:43
Registry entry - stores option definition with mode bitmask and metadata.
const char * long_name
option_mode_bitmask_t mode_bitmask
const char * help_text

References g_options_registry, g_registry_size, registry_entry_t::help_text, registry_entry_t::long_name, registry_entry_t::mode_bitmask, MODE_INVALID, OPTION_MODE_BINARY, and registry_init_size().

◆ options_init()

asciichat_error_t options_init ( int argc,
char ** argv )

#include <include/ascii-chat/options/options.h>

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

Main Entry Point for the options system. This function:

  1. Mode Detection: Analyzes argv to detect requested mode:
    • Looks for mode keywords: "server", "client", "mirror", "acds", etc.
    • Checks for session string pattern (word-word-word) → client mode
    • Falls back to showing help if no mode specified
  2. Binary-Level Parsing: Processes global options before mode detection:
    • --help / -h → prints help and exits
    • --version / -v → prints version and exits
    • --verbose / -V → sets verbose level (stackable)
    • --quiet / -q → sets quiet mode
    • --log-file / -L → redirects logs to file
    • --log-level → sets log verbosity level
  3. Mode-Specific Parsing: Uses mode-specific parser for detected mode:
    • Parses mode-specific options (server, client, mirror, acds)
    • Each mode has different set of supported options
    • Options are validated with mode bitmasks
  4. Configuration File Loading (if –config specified):
    • Loads TOML config file
    • Merges config file settings with command-line options
    • Command-line takes precedence over config file
  5. Validation and Defaults:
    • Applies default values to unspecified options
    • Validates numeric ranges, file existence, formats
    • Performs cross-field validation (dependencies, conflicts)
    • Checks mode-specific constraints
  6. RCU Publishing:
    • Initializes RCU state if not already done
    • Publishes options struct for lock-free thread-safe access
    • After this point, GET_OPTION() and options_get() are valid

Detected Mode Storage: The detected mode is stored in options_t->detected_mode and accessible via:

asciichat_mode_t mode = GET_OPTION(detected_mode);

Mode Detection Examples:

# Mode keywords (explicit)
./ascii-chat server --port 8080 # MODE_SERVER
./ascii-chat client example.com:9000 # MODE_CLIENT
./ascii-chat mirror --color # MODE_MIRROR
./ascii-chat acds --port 27225 # MODE_DISCOVERY_SERVICE
# Session strings (implicit client mode)
./ascii-chat word-word-word # MODE_CLIENT (session string)
# Help/version (special handling)
./ascii-chat --help # Shows help, may exit(0)
./ascii-chat --version # Shows version, may exit(0)

Return Values:

  • ASCIICHAT_OK: Parsing succeeded normally
  • ERROR_USAGE: Parse error occurred (usage info printed to stderr)
  • Other error codes: Unexpected errors during initialization

Special Handling for –help and –version: These flags are handled specially and may cause early exit via exit(0). The function will still return ASCIICHAT_OK in these cases for compatibility.

Environment Variables: Some options can fall back to environment variables:

  • WEBCAM_DISABLED: Enable test pattern when set to "1", "true", etc.
  • ASCII_CHAT_KEY_PASSWORD: Fallback for encrypted key passphrases
  • SSH_AUTH_SOCK: For SSH agent key access

Typical Usage:

int main(int argc, char **argv) {
asciichat_error_t err = options_init(argc, argv);
if (err != ASCIICHAT_OK) {
// Could be ERROR_USAGE (invalid options) or other errors
// usage() already printed to stderr for ERROR_USAGE
return 1;
}
// Options now available via GET_OPTION() and options_get()
asciichat_mode_t mode = GET_OPTION(detected_mode);
const char *addr = GET_OPTION(address);
// ... application code ...
return 0;
}
Note
Must be called once at program startup before accessing options
Should be called before creating worker threads
Global option variables initialized by this function
Returns ERROR_USAGE for invalid options (usage already printed)
–help and –version may exit directly via exit(0)
After return, options accessible via GET_OPTION() macro

Initialize all command-line options from argv and environment variables

Main entry point for the options parsing system. This function:

  • Detects the mode from the first positional argument (server, client, mirror, etc.)
  • Parses binary-level options (–help, –version, –log-file, etc.)
  • Parses mode-specific options
  • Validates cross-field option dependencies
  • Initializes defaults from OPT_*_DEFAULT defines
  • Publishes options via RCU for thread-safe lock-free access

Option Processing Order:

  1. Binary-level options (parsed from all args regardless of mode)
  2. Mode detection (from first positional argument)
  3. Mode-specific options (from remaining args filtered by mode)
  4. Defaults initialization (for unspecified options)
  5. Cross-field validation (dependencies between options)
  6. RCU publication (make available to all threads)

Return Values:

  • ASCIICHAT_OK - Initialization successful
  • ERROR_USAGE - Invalid usage (help/usage already printed to stdout)
  • Other errors - Check errno context via HAS_ERRNO()

Special Behavior:

  • –help causes help text to print and exit(0) (never returns)
  • –version causes version to print and exit(0) (never returns)
Parameters
argcArgument count from main()
argvArgument vector from main()
Returns
ASCIICHAT_OK on success, ERROR_USAGE on parse error, other on fatal error
Note
Global option variables initialized by this function
Returns ERROR_USAGE for invalid options (usage already printed)
–help and –version may exit directly via exit(0)
After return, options accessible via GET_OPTION() macro

Definition at line 2541 of file options.c.

2541 {
2542 log_dev("starting with argc=%d, argv[0]=%s, argv[1]=%s", argc,
2543 (argv && argc > 0 && argv[0]) ? argv[0] : "(null)",
2544 (argv && argc > 1 && argv[1]) ? argv[1] : "N/A");
2545 asciichat_error_t result = validate_options_argv(argc, argv);
2546 if (result != ASCIICHAT_OK) {
2547 return result;
2548 }
2549 result = options_state_init();
2550 if (result != ASCIICHAT_OK) {
2551 return result;
2552 }
2553 log_dev("options_init: state initialized");
2554
2555 // Discover binary actions before mode parsing so help and early exits need no
2556 // media setup.
2557 handle_help_option(argc, argv);
2558 binary_actions_t actions = {.parsed_color_setting = COLOR_SETTING_AUTO};
2559 result = scan_binary_actions(argc, argv, &actions);
2560 if (result != ASCIICHAT_OK) {
2561 return result;
2562 }
2563 log_dev("options_init: binary actions scanned");
2564 set_action_flag(actions.has_action);
2565
2566 asciichat_mode_t detected_mode = MODE_DISCOVERY;
2567 char detected_session_string[SESSION_STRING_BUFFER_SIZE] = {0};
2568 int mode_index = -1;
2569 if (actions.show_version || actions.create_config || actions.create_manpage) {
2570 // Binary actions do not have a session mode. Avoid treating an optional
2571 // output path as a positional mode before the action is dispatched.
2572 detected_mode = MODE_DISCOVERY;
2573 mode_index = -1;
2574 } else {
2575 result = options_detect_mode(argc, argv, &detected_mode,
2576 detected_session_string, &mode_index);
2577 if (result != ASCIICHAT_OK) {
2578 return result;
2579 }
2580 }
2581 result = validate_early_color_mode(argc, argv);
2582 if (result != ASCIICHAT_OK) {
2583 return result;
2584 }
2585
2586 options_t opts = options_t_new();
2587 log_dev("options_init: options constructed");
2588 initialize_binary_options(&opts, detected_mode, &actions);
2589 log_dev("options_init: binary options initialized");
2590 bool handled = false;
2591 result = handle_immediate_actions(&opts, &actions, &handled);
2592 if (result != ASCIICHAT_OK || handled) {
2593 if (result != ASCIICHAT_OK)
2594 return result;
2595 }
2596 result = parse_binary_options(&opts, argc, argv);
2597 if (result != ASCIICHAT_OK) {
2598 return result;
2599 }
2600 if (actions.show_version || actions.create_config || actions.create_manpage) {
2601 result = handle_fallback_actions(&opts, &actions);
2602 if (result != ASCIICHAT_OK) {
2603 return result;
2604 }
2605 return ASCIICHAT_OK;
2606 }
2607
2608 // Mode parsing owns the temporary argv and schema until the shared cleanup
2609 // path.
2610 mode_arguments_t mode_args = {.argc = argc, .argv = argv};
2611 result = build_mode_argv(argc, argv, mode_index, &mode_args);
2612 if (result != ASCIICHAT_OK) {
2613 goto cleanup;
2614 }
2615 initialize_mode_defaults(&opts, detected_mode, detected_session_string);
2616 build_options_schema();
2617 // Apply defaults, config, environment, then CLI values in increasing
2618 // precedence.
2619 result = load_options_config(&opts, detected_mode);
2620 if (result != ASCIICHAT_OK) {
2621 goto cleanup;
2622 }
2623 int remaining_argc = 0;
2624 char **remaining_argv = NULL;
2625 result = parse_mode_options(&opts, detected_mode, mode_args.argc,
2626 mode_args.argv, &remaining_argc, &remaining_argv);
2627 if (result != ASCIICHAT_OK) {
2628 goto cleanup;
2629 }
2630 result = validate_custom_palette(&opts);
2631 if (result != ASCIICHAT_OK) {
2632 goto cleanup;
2633 }
2634 result = validate_glyph_palette(&opts);
2635 if (result != ASCIICHAT_OK)
2636 goto cleanup;
2637 // Remaining validators consume a published snapshot.
2638 result = publish_options_for_validation(&opts);
2639 if (result != ASCIICHAT_OK) {
2640 goto cleanup;
2641 }
2642 result = validate_encryption_key(&opts);
2643 if (result != ASCIICHAT_OK) {
2644 goto cleanup;
2645 }
2646 result = validate_color_filter(&opts);
2647 if (result != ASCIICHAT_OK) {
2648 goto cleanup;
2649 }
2650 apply_screen_defaults(&opts, mode_args.argc, mode_args.argv);
2651 result = validate_option_strings(&opts);
2652 if (result != ASCIICHAT_OK) {
2653 goto cleanup;
2654 }
2655 result = validate_parsed_options(&opts, remaining_argc, remaining_argv);
2656 if (result != ASCIICHAT_OK) {
2657 goto cleanup;
2658 }
2659 result = finalize_mode_defaults(&opts, detected_mode);
2660 if (result != ASCIICHAT_OK) {
2661 goto cleanup;
2662 }
2663 log_dev("★ STAGE 7: Starting post-processing");
2664 // Resolve identity, dimensions, and media before exposing the final options
2665 // to actions.
2666 result = collect_server_identity_keys(&opts, detected_mode, argc, argv);
2667 if (result != ASCIICHAT_OK) {
2668 goto cleanup;
2669 }
2670 finalize_dimensions(&opts);
2671 result = finalize_media_options(&opts);
2672 if (result != ASCIICHAT_OK) {
2673 goto cleanup;
2674 }
2675 result = publish_final_options(&opts, detected_mode, mode_index);
2676 if (result != ASCIICHAT_OK) {
2677 goto cleanup;
2678 }
2679 apply_logging_color_scheme(&opts);
2680
2681 // Deferred actions must see the final published options and may print output.
2682 if (actions.has_action) {
2684 }
2686
2687cleanup:
2688 flags_command_free_argv(mode_args.allocated);
2689 return result;
2690}
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log/log.c:818
asciichat_error_t validate_glyph_palette(const options_t *opts)
Definition validation.c:25
void actions_execute_deferred(void)
Execute the deferred action (if any).
#define SESSION_STRING_BUFFER_SIZE
The useful part of binary actions is in show_version, create_config, create_manpage,...
Definition options.c:1104
char ** allocated
Definition options.c:1107

References actions_execute_deferred(), mode_arguments_t::allocated, mode_arguments_t::argc, mode_arguments_t::argv, ASCIICHAT_OK, COLOR_SETTING_AUTO, binary_actions_t::create_config, binary_actions_t::create_manpage, binary_actions_t::has_action, log_dev, log_set_terminal_output(), MODE_DISCOVERY, options_state_init(), options_t_new(), SESSION_STRING_BUFFER_SIZE, binary_actions_t::show_version, and validate_glyph_palette().

Referenced by browser_client_init(), client_init(), and mirror_init().

◆ options_set_bool()

asciichat_error_t options_set_bool ( const char * name,
bool value )

#include <include/ascii-chat/options/options.h>

Assign a boolean through the same transaction used by patches and toggles. Field descriptors account for both bool and integer-backed storage. Animation exclusions are applied atomically with the requested value.

Definition at line 973 of file rcu.c.

973 {
974 return apply_one((options_edit_t){
975 .name = name, .type = OPTIONS_VALUE_BOOL, .value.boolean = value});
976}
@ OPTIONS_VALUE_BOOL

References OPTIONS_VALUE_BOOL.

Referenced by session_capture_toggle_media(), and SessionUiBinding::setAudio().

◆ options_set_double()

asciichat_error_t options_set_double ( const char * field_name,
double value )

#include <include/ascii-chat/options/options.h>

Definition at line 977 of file rcu.c.

977 {
978 return apply_one((options_edit_t){
979 .name = name, .type = OPTIONS_VALUE_DOUBLE, .value.number = value});
980}
@ OPTIONS_VALUE_DOUBLE

References OPTIONS_VALUE_DOUBLE.

◆ options_set_int()

asciichat_error_t options_set_int ( const char * name,
int value )

#include <include/ascii-chat/options/options.h>

Check if an option was explicitly set via command-line.

Convenience macro for checking if a specific option was explicitly provided by the user via command-line arguments (as opposed to using a default value).

Usage Examples:

// Check if user explicitly provided --width
if (IS_OPTION_EXPLICIT("width")) {
printf("User set width explicitly\n");
}
// Use in conditional logic
if (!IS_OPTION_EXPLICIT("color") && terminal_is_dark_mode()) {
// Color not set, apply dark mode defaults
}
#define IS_OPTION_EXPLICIT(name, opts)
Definition explicit.h:63
Parameters
option_nameThe long name of the option (e.g., "width", "port", "color")
Returns
true if option was explicitly set, false otherwise
Note
Option name must be a string literal matching the long_name from registry
Case-sensitive: must match exact option name
No locks needed - lock-free read via atomic pointer

Set a single option field (thread-safe, RCU-based)

Convenience function for updating a single field in the options struct. Uses RCU (copy-on-write) internally for thread-safe updates.

Example:

options_set_int("width", 120);
options_set_int("port", 8080);
options_set_bool("audio_enabled", true);

Thread Safety: Multiple writers are serialized with a mutex. Readers are never blocked (lock-free reads via GET_OPTION).

Assign an integer through the serialized writer transaction. Resolve aliases and validate the final candidate before publishing it. A rejected edit leaves the current snapshot and revision intact.

Definition at line 964 of file rcu.c.

964 {
965 return apply_one((options_edit_t){
966 .name = name, .type = OPTIONS_VALUE_INT, .value.integer = value});
967}
@ OPTIONS_VALUE_INT

References OPTIONS_VALUE_INT.

Referenced by ui_session_key().

◆ options_set_string()

asciichat_error_t options_set_string ( const char * field_name,
const char * value )

#include <include/ascii-chat/options/options.h>

Definition at line 981 of file rcu.c.

981 {
982 return apply_one((options_edit_t){
983 .name = name, .type = OPTIONS_VALUE_STRING, .value.string = value});
984}
@ OPTIONS_VALUE_STRING

References OPTIONS_VALUE_STRING.

◆ options_t_new()

options_t options_t_new ( void )

#include <include/ascii-chat/options/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;
}
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for a specific mode.
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)

Create a new options_t struct with all defaults set

Initializes an options_t struct with all fields set to their default values from OPT_*_DEFAULT defines. This function is used internally by options_init() to ensure consistent default initialization before command-line parsing.

Behavior:

  • All numeric fields set to their OPT_*_DEFAULT values
  • All boolean fields set to their OPT_*_DEFAULT values
  • All string fields initialized with their default values
  • detected_mode set to MODE_INVALID (overwritten during parsing)

Usage: Typically called by options_init() internally. Can be used by custom code creating builder-based parsers for consistent defaults.

Returns
A new options_t struct with all defaults applied (stack-allocated)
Note
Returns a stack-allocated struct (caller should use immediately or copy)
All fields initialized to their OPT_*_DEFAULT constant values
Does not allocate memory (all fields are static arrays or primitives)

Definition at line 688 of file options.c.

688 {
689 options_t opts;
690
691 // Zero-initialize all fields first
692 memset(&opts, 0, sizeof(opts));
693 opts.mode_arg_index = -1;
694
695 // ============================================================================
696 // GENERAL CATEGORY - General-purpose options
697 // ============================================================================
698 opts.help = OPT_HELP_DEFAULT;
705
706 // ============================================================================
707 // LOGGING CATEGORY - Binary-level logging and output control options
708 // ============================================================================
709 // log_file is mode-dependent at startup and intentionally left empty here
714 sizeof(opts.otel_endpoint));
715 SAFE_STRNCPY(opts.otel_enabled_telemetry, "traces,logs,metrics",
716 sizeof(opts.otel_enabled_telemetry));
717 opts.otel_realtime_sample_rate = 0.01;
719 opts.otel_metrics_interval = 10000;
720 SAFE_STRNCPY(opts.otel_log_level, "info", sizeof(opts.otel_log_level));
721 opts.otel_timeout = 5000;
722 opts.otel_queue_capacity = 4096;
723 if (platform_systemd_is_managed()) {
724 opts.splash_screen = false;
725 opts.status_screen = false;
726 opts.no_check_update = true;
727 SAFE_STRNCPY(opts.log_file, "/dev/null", sizeof(opts.log_file));
728 opts.otel_endpoint[0] = '\0';
729 }
730 opts.grep_pattern[0] = '\0'; // Explicitly ensure grep_pattern is empty
731 opts.json = OPT_JSON_DEFAULT;
733 sizeof(opts.color_scheme_name));
734 // log_template and log_format are set by get_default_log_template()
735
736 // ============================================================================
737 // TERMINAL CATEGORY - Terminal display options
738 // ============================================================================
748 if (platform_systemd_is_managed())
750
751 // ============================================================================
752 // DISPLAY CATEGORY - Display and rendering options
753 // ============================================================================
757 opts.stabilize = true;
759 // palette_custom is already zeroed by memset
762 opts.fps = OPT_FPS_DEFAULT;
766 opts.waveform = false;
767 opts.fft = false;
768 SAFE_STRNCPY(opts.fft_scale, "-62:-6", sizeof(opts.fft_scale));
771
772 // ============================================================================
773 // WEBCAM CATEGORY - Webcam and capture device options
774 // ============================================================================
778
779 // ============================================================================
780 // MEDIA CATEGORY - Media file streaming and playback options
781 // ============================================================================
782 // media_file is already zeroed by memset
783 // media_url is already zeroed by memset
788 // yt_dlp_options is already zeroed by memset
789
790 // Render-to-file options
791 // render_file is already zeroed by memset
793 // render_font is already zeroed by memset
795
796 // ============================================================================
797 // NETWORK CATEGORY - Network connectivity and protocol options
798 // ============================================================================
799 SAFE_STRNCPY(opts.address, OPT_ADDRESS_DEFAULT, sizeof(opts.address));
807 // Discovery Service (ACDS) Options
811 sizeof(opts.discovery_server));
816 // discovery_service_key is already zeroed by memset
818 '\0'; // Explicitly ensure discovery_database_path is empty
819 // LAN Discovery & WebRTC Options
823 // WebRTC Mode & Strategy Options
827 opts.webrtc_relay_only = false;
832 sizeof(opts.stun_servers));
834 sizeof(opts.turn_servers));
836 sizeof(opts.turn_username));
838 sizeof(opts.turn_credential));
839 // turn_secret is already zeroed by memset
840
841 // ============================================================================
842 // AUDIO CATEGORY - Audio capture, playback and processing options
843 // ============================================================================
844 opts.audio_fft_size = 1024;
845 opts.test_audio = false;
846 opts.audio_spectral = true;
847 opts.audio_spectral_mixer = false;
848 opts.audio_spectral_gate = true;
849 opts.reduce_noise = true;
853 opts.microphone_channels = 1;
854 opts.microphone_channel = 0;
862
863 // ============================================================================
864 // SECURITY CATEGORY - Encryption and authentication options
865 // ============================================================================
867 // encrypt_key is already zeroed by memset
868 // password is already zeroed by memset
869 // encrypt_keyfile is already zeroed by memset
872 // server_key is already zeroed by memset
873 // client_keys is already zeroed by memset
874 // identity_keys array is already zeroed by memset
875 opts.num_identity_keys = 0;
878
879 // ============================================================================
880 // CONFIGURATION CATEGORY - Application configuration options
881 // ============================================================================
882 // config_file is already zeroed by memset
883
884 // ============================================================================
885 // DATABASE CATEGORY - Database and persistent storage options
886 // ============================================================================
887 // discovery_database_path is already zeroed by memset (set above in NETWORK)
888
889 // ============================================================================
890 // Internal/System Fields
891 // ============================================================================
892 // session_string is already zeroed by memset
893 // detected_mode is already zeroed by memset
894
895 return opts;
896}
#define OPT_STRIP_ANSI_DEFAULT
Default strip ANSI escape sequences flag.
Definition options.h:446
#define OPT_WEBRTC_SKIP_STUN_DEFAULT
Default WebRTC skip STUN flag (false = use STUN).
Definition options.h:677
#define OPT_ACDS_EXPOSE_IP_DEFAULT
Default ACDS expose IP flag (false = private by default).
Definition options.h:599
#define OPT_ENDPOINT_DISCOVERY_SERVICE
Default discovery service endpoint (what to connect to by default).
Definition options.h:555
#define OPT_COLOR_DEFAULT
Default color setting (COLOR_SETTING_AUTO = smart detection).
Definition options.h:449
#define OPT_NO_AUDIO_MIXER_DEFAULT
Default no audio mixer flag (false = enable mixer).
Definition options.h:513
#define OPT_FLIP_Y_DEFAULT
Default vertical flip state (false = no vertical flip).
Definition options.h:500
#define OPT_SHOW_CAPABILITIES_DEFAULT
Default show terminal capabilities flag.
Definition options.h:440
#define OPT_NO_ENCRYPT_DEFAULT
Default no encrypt flag (false = allow encryption).
Definition options.h:738
#define OPT_QUIET_DEFAULT
Default quiet mode flag (false = logging enabled).
Definition options.h:343
#define OPT_MICROPHONE_INDEX_DEFAULT
Default microphone device index (-1 means system default).
Definition options.h:710
#define OPT_TURN_SERVERS_DEFAULT
Default TURN server URLs (comma-separated).
Definition options.h:663
#define OPT_ENCODE_AUDIO_DEFAULT
Default audio encoding state (true = Opus encoding enabled).
Definition options.h:728
#define OPT_COLOR_MODE_DEFAULT
Default color mode (auto-detect terminal capabilities).
Definition options.h:428
#define OPT_PALETTE_TYPE_DEFAULT
Default palette type (standard ASCII art).
Definition options.h:462
#define OPT_RECONNECT_ATTEMPTS_DEFAULT
Default reconnect attempts (-1 means auto/infinite).
Definition options.h:581
#define OPT_SPEAKERS_VOLUME_DEFAULT
Default speakers volume (1.0 = normal volume).
Definition options.h:719
#define OPT_NO_AUTH_DEFAULT
Default no auth flag (false = allow authentication).
Definition options.h:741
#define OPT_TEST_PATTERN_DEFAULT
Default test pattern mode (false = use actual webcam).
Definition options.h:510
#define OPT_OTEL_ENDPOINT_DEFAULT
Debug and Dev builds export to the local Spaniel Compose collector.
Definition options.h:349
#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT
Default WebRTC ICE gathering timeout in milliseconds (10 seconds).
Definition options.h:686
#define OPT_COMPRESSION_LEVEL_DEFAULT
Default compression level (1-9).
Definition options.h:584
#define OPT_ENCRYPT_ENABLED_DEFAULT
Default encrypt enabled flag (true = encryption required).
Definition options.h:735
#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT
Default require-server-identity setting for ACDS.
Definition options.h:605
#define OPT_ENABLE_KEEPAWAKE_DEFAULT
Default keep-awake (prevent system sleep) flag (false = normal system sleep).
Definition options.h:330
#define OPT_RENDER_MODE_DEFAULT
Default render mode (foreground characters only).
Definition options.h:459
#define OPT_ACDS_PORT_INT_DEFAULT
Default ACDS discovery service port (integer).
Definition options.h:593
#define OPT_AUDIO_ENABLED_DEFAULT
Default audio enabled flag (true = audio enabled by default).
Definition options.h:702
#define OPT_MATRIX_RAIN_DEFAULT
Default Matrix rain effect flag (false = disabled).
Definition options.h:491
#define OPT_FORCE_UTF8_DEFAULT
Default force UTF-8 support setting (auto-detect).
Definition options.h:443
#define OPT_STUN_SERVERS_DEFAULT
Default STUN server URLs (comma-separated).
Definition options.h:660
#define OPT_HELP_DEFAULT
Default help flag (false = don't show help).
Definition options.h:312
#define OPT_ADDRESS6_DEFAULT
Default IPv6 server address.
Definition options.h:539
#define OPT_RENDER_FONT_SIZE_DEFAULT
Definition options.h:774
#define OPT_SPLASH_DEFAULT
Default splash screen flag (true = show splash, false = hide splash).
Definition options.h:318
#define OPT_RENDER_THEME_DEFAULT
Definition options.h:772
#define OPT_MEDIA_FROM_STDIN_DEFAULT
Default media from stdin flag (false = not reading from stdin).
Definition options.h:523
#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT
Default audio analysis enabled flag.
Definition options.h:722
#define OPT_VERSION_DEFAULT
Default version flag (false = don't show version).
Definition options.h:315
#define OPT_ACDS_DEFAULT
Default ACDS registration flag (false = disabled).
Definition options.h:590
#define OPT_NO_COMPRESS_DEFAULT
Default no compression flag (false = enable compression).
Definition options.h:587
#define OPT_AUTO_HEIGHT_DEFAULT
Default auto-detect height flag (true = auto-detect from terminal).
Definition options.h:425
#define ASCII_RENDERER_DEFAULT
Consolidated options structure.
Definition options.h:962
#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT
Default require client verify flag (false = not required).
Definition options.h:747
#define OPT_AUDIO_NO_PLAYBACK_DEFAULT
Default audio playback flag (false = enable playback).
Definition options.h:725
#define OPT_PAUSE_DEFAULT
Default pause media flag (false = play immediately).
Definition options.h:529
#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT
Default require server verify flag (false = not required).
Definition options.h:744
#define OPT_NO_MDNS_ADVERTISE_DEFAULT
Default no mDNS advertise flag (false = advertise enabled).
Definition options.h:614
#define OPT_AUDIO_SOURCE_DEFAULT
Visualize all available sources by default.
Definition options.h:705
#define OPT_COLOR_FILTER_DEFAULT
Default color filter (none - no filtering).
Definition options.h:456
#define OPT_WEBCAM_INDEX_DEFAULT
Default webcam device index.
Definition options.h:507
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
Definition options.h:419
#define OPT_SNAPSHOT_MODE_DEFAULT
Default snapshot mode flag (false = continuous).
Definition options.h:474
#define OPT_COLOR_SCHEME_NAME_DEFAULT
Default color scheme name (pastel).
Definition options.h:365
#define OPT_MEDIA_LOOP_DEFAULT
Default loop media flag (false = play once).
Definition options.h:520
#define OPT_NO_CHECK_UPDATE_DEFAULT
Default no-check-update flag (false = check for updates enabled).
Definition options.h:336
#define OPT_STRETCH_DEFAULT
Default allow aspect ratio distortion flag.
Definition options.h:468
#define OPT_STATUS_SCREEN_DEFAULT
Default status screen flag (true = show status, false = hide status).
Definition options.h:324
#define OPT_LAN_DISCOVERY_DEFAULT
Default LAN discovery flag (false = discovery disabled).
Definition options.h:611
#define OPT_AUTO_WIDTH_DEFAULT
Default auto-detect width flag (true = auto-detect from terminal).
Definition options.h:422
#define OPT_JSON_DEFAULT
Default JSON logging flag (false = text output).
Definition options.h:362
#define OPT_ACDS_INSECURE_DEFAULT
Default ACDS insecure mode flag (false = verify server).
Definition options.h:602
#define OPT_FPS_DEFAULT
Default FPS (frames per second).
Definition options.h:471
#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT
Default require-client-identity setting for ACDS.
Definition options.h:608
#define OPT_DISABLE_KEEPAWAKE_DEFAULT
Default disable keep-awake flag (false = allow system sleep prevention).
Definition options.h:333
#define OPT_ENABLE_UPNP_DEFAULT
Default enable UPnP flag (false = UPnP disabled).
Definition options.h:617
#define OPT_TURN_CREDENTIAL_DEFAULT
Default TURN credential (empty = use ACDS credentials).
Definition options.h:695
#define OPT_WEBRTC_SKIP_HOST_DEFAULT
Default WebRTC skip host candidates flag (false = use host candidates).
Definition options.h:683
#define OPT_VERBOSE_LEVEL_DEFAULT
Default verbose level (0 = not verbose).
Definition options.h:353
#define OPT_SNAPSHOT_DELAY_DEFAULT
Default snapshot delay in seconds.
Definition options.h:487
#define OPT_LOG_LEVEL_DEFAULT
Default log level (LOG_INFO).
Definition options.h:356
#define OPT_MICROPHONE_SENSITIVITY_DEFAULT
Default microphone sensitivity (1.0 = normal volume).
Definition options.h:716
#define OPT_FLIP_X_DEFAULT
Webcam input is mirrored unless an orientation is explicitly selected.
Definition options.h:497
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
#define OPT_MAX_CLIENTS_DEFAULT
Default maximum concurrent clients (server only).
Definition options.h:578
#define OPT_PREFER_WEBRTC_DEFAULT
Default prefer WebRTC flag (false = try direct TCP first).
Definition options.h:671
#define OPT_WEBRTC_DISABLE_TURN_DEFAULT
Default WebRTC disable TURN flag (false = use TURN).
Definition options.h:680
#define OPT_NO_WEBRTC_DEFAULT
Default no WebRTC flag (false = WebRTC enabled).
Definition options.h:674
#define OPT_ADDRESS_DEFAULT
Default server address for client connections.
Definition options.h:536
#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT
Preserve automatic local audio capture selection by default.
Definition options.h:707
#define OPT_PALETTE_CUSTOM_SET_DEFAULT
Default custom palette set flag (false = not set).
Definition options.h:465
#define OPT_TURN_USERNAME_DEFAULT
Default TURN username (empty = use ACDS credentials).
Definition options.h:692
#define OPT_SPEAKERS_INDEX_DEFAULT
Default speakers device index (-1 means system default).
Definition options.h:713
#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT
Default WebSocket port for server mode (integer).
Definition options.h:565
#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT
Default media seek timestamp (start from beginning).
Definition options.h:526
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
Definition options.h:408
bool snapshot_mode
Snapshot mode (one frame and exit).
Definition options.h:1142
int otel_realtime_max_per_second
Definition options.h:1155
float speakers_volume
Speaker volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1124
int discovery_port
discovery server port (default: 27225)
Definition options.h:1035
double otel_realtime_sample_rate
Definition options.h:1154
audio_capture_source_t audio_capture_source
Local capture/media selection policy.
Definition options.h:1115
bool encrypt_enabled
Enable encryption.
Definition options.h:1171
int otel_metrics_interval
Definition options.h:1156
bool audio_spectral_gate
Definition options.h:1108
bool discovery_expose_ip
ACDS: explicitly allow public IP disclosure without verification (opt-in).
Definition options.h:1192
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:1212
int force_utf8
UTF-8 support setting (auto/true/false).
Definition options.h:1089
int webrtc_ice_timeout_ms
–webrtc-ice-timeout: ICE gathering timeout in milliseconds (default: 10000)
Definition options.h:1205
bool discovery
Enable discovery session registration (default: false).
Definition options.h:1027
bool webrtc_relay_only
–webrtc-relay-only: Require TURN relay candidates
Definition options.h:1202
bool disable_keepawake
Explicitly disable system sleep prevention (allow OS to sleep).
Definition options.h:1166
int otel_queue_capacity
Definition options.h:1158
bool test_audio
Replace microphone capture with a repeating audible test signal.
Definition options.h:1104
int microphone_channel
First zero-based input channel; -1 downmixes all inputs.
Definition options.h:1120
float microphone_sensitivity
Microphone volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1123
int microphone_channels
Selected microphone channels: 1 (speech) or 2 (stereo).
Definition options.h:1119
int compression_level
zstd compression level (1-9)
Definition options.h:1050
bool fft
Replace the video image with a live audio frequency spectrogram.
Definition options.h:1117
bool enable_keepawake
Explicitly enable system sleep prevention.
Definition options.h:1165
char otel_endpoint[256]
Definition options.h:1151
bool show_capabilities
Show terminal capabilities and exit.
Definition options.h:1088
bool no_mdns_advertise
Disable mDNS service advertisement (server only).
Definition options.h:1045
int microphone_index
Microphone device index (-1 = default).
Definition options.h:1121
bool strip_ansi
Strip ANSI escape sequences.
Definition options.h:1147
bool audio_analysis_enabled
Enable audio analysis (debug).
Definition options.h:1125
int websocket_port
WebSocket server port (server/discovery-service only).
Definition options.h:1005
bool pause
Start playback paused (toggle with spacebar).
Definition options.h:1076
audio_source_t audio_source
Visualization source (all/call/mic/media).
Definition options.h:1114
bool json
Enable JSON logging (–json flag).
Definition options.h:1162
char stun_servers[256]
ACDS: Comma-separated list of STUN server URLs.
Definition options.h:1211
bool enable_upnp
Opt-in TCP/WebSocket and WebRTC UDP mapping via –port-forwarding.
Definition options.h:1210
bool webrtc_skip_stun
–webrtc-skip-stun: Skip Stage 2 (STUN), go to TURN
Definition options.h:1201
bool lan_discovery
Enable LAN service discovery via mDNS (client only).
Definition options.h:1044
bool audio_enabled
Enable audio streaming.
Definition options.h:1113
bool no_encrypt
Disable encryption (opt-out).
Definition options.h:1175
bool no_webrtc
–no-webrtc: Disable WebRTC, use Direct TCP only
Definition options.h:1199
bool matrix_rain
Matrix digital rain effect (false = disabled).
Definition options.h:1145
bool webrtc_disable_turn
–webrtc-disable-turn: Disable Stage 3 (TURN), use STUN only
Definition options.h:1203
bool audio_no_playback
Disable speaker playback (debug).
Definition options.h:1126
bool auto_height
Auto-detect height from terminal.
Definition options.h:994
log_level_t log_level
Log level threshold.
Definition options.h:1160
char turn_credential[256]
ACDS: Credential/password for TURN authentication.
Definition options.h:1214
bool require_server_identity
ACDS: require servers to provide signed Ed25519 identity.
Definition options.h:1188
int audio_fft_size
Definition options.h:1112
bool status_screen
Show status screen (default: true = show, use –no-status-screen to hide).
Definition options.h:1230
char otel_log_level[256]
Definition options.h:1150
int max_clients
Maximum concurrent clients (server only).
Definition options.h:1020
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
bool no_auth
Disable authentication layer (–no-auth).
Definition options.h:1176
terminal_render_mode_t render_mode
Render mode (foreground/background/half-block).
Definition options.h:1087
bool splash_screen
Show splash screen (default: true = show, use –no-splash-screen to hide).
Definition options.h:1228
char discovery_database_path[256]
~/.ascii-chat/discovery.db)
Definition options.h:1038
bool no_audio_mixer
Disable audio mixer (debug).
Definition options.h:1065
bool audio_spectral_mixer
Explicit post-mix processing; disabled by default.
Definition options.h:1107
bool webrtc_skip_host
–webrtc-skip-host: Skip host candidates, force STUN/TURN only
Definition options.h:1204
bool version
Show version information.
Definition options.h:985
int webcam_index
Webcam device index (0 = first).
Definition options.h:1062
bool stabilize
Reduce frame-to-frame character flicker.
Definition options.h:1131
bool no_compress
Disable compression entirely.
Definition options.h:1051
char address6[256]
IPv6 bind address (server only).
Definition options.h:1003
int speakers_index
Speakers device index (-1 = default).
Definition options.h:1122
color_filter_t color_filter
Monochromatic color filter (none/black/white/green/etc).
Definition options.h:1085
bool help
Show help message.
Definition options.h:984
bool prefer_webrtc
–prefer-webrtc: Try WebRTC before Direct TCP
Definition options.h:1198
bool quiet
Quiet mode (suppress logs).
Definition options.h:1140
double snapshot_delay
Snapshot delay in seconds.
Definition options.h:1143
bool audio_spectral
Definition options.h:1106
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
bool stretch
Allow aspect ratio distortion.
Definition options.h:1134
ascii_renderer_t renderer
Character selection algorithm.
Definition options.h:1133
bool waveform
Replace the video image with a live audio waveform.
Definition options.h:1116
int reconnect_attempts
Number of reconnection attempts (-1=infinite, 0=none).
Definition options.h:1057
bool test_pattern
Use test pattern instead of webcam.
Definition options.h:1063
char fft_scale[32]
Amplitude scale for the FFT visualization.
Definition options.h:1118
bool media_from_stdin
Reading from stdin (detected from "--file -").
Definition options.h:1074
bool require_client_verify
Client: only connect to servers whose identity was verified by ACDS.
Definition options.h:1191
char discovery_server[256]
discovery server address (default: 127.0.0.1)
Definition options.h:1028
int mode_arg_index
Explicit mode token in original argv, or -1 for implicit discovery/session strings.
Definition options.h:979
bool require_server_verify
Server: only accept clients who verified via ACDS.
Definition options.h:1190
palette_type_t palette_type
Selected palette type.
Definition options.h:1220
bool flip_y
Flip video vertically (Y-axis).
Definition options.h:1098
char color_scheme_name[64]
Color scheme name (e.g., "pastel", "nord").
Definition options.h:1086
bool media_loop
Loop media file playback.
Definition options.h:1073
bool require_client_identity
ACDS: require clients to provide signed Ed25519 identity.
Definition options.h:1189
bool discovery_insecure
ACDS: skip server key verification (MITM-vulnerable, requires explicit opt-in).
Definition options.h:1193
bool no_check_update
Disable automatic update checks (default: false = checks enabled).
Definition options.h:1232
bool encode_audio
Enable Opus audio encoding.
Definition options.h:1052
int render_theme
0=dark 1=light 2=auto
Definition options.h:1253
char otel_enabled_telemetry[256]
Definition options.h:1153
int color
Color setting (COLOR_SETTING_AUTO/TRUE/FALSE).
Definition options.h:1083
char turn_username[256]
ACDS: Username for TURN authentication.
Definition options.h:1213
char log_file[256]
Log file path.
Definition options.h:1159
unsigned short int verbose_level
Verbosity level (stackable -V).
Definition options.h:1141
char address[256]
Server address (client) or bind address (server).
Definition options.h:1002
bool reduce_noise
Apply neural microphone noise reduction in client-like modes.
Definition options.h:1109
bool flip_x
Effective horizontal orientation.
Definition options.h:1095
char grep_pattern[256]
PCRE2 regex for log filtering.
Definition options.h:1161
bool auto_width
Auto-detect width from terminal.
Definition options.h:993
double render_font_size
Font size in points (0 selects an automatic size).
Definition options.h:1255
double media_seek_timestamp
Seek to timestamp in seconds before playback.
Definition options.h:1075

References options_state::address, options_state::address6, ASCII_RENDERER_DEFAULT, options_state::audio_analysis_enabled, options_state::audio_capture_source, options_state::audio_enabled, options_state::audio_fft_size, options_state::audio_no_playback, options_state::audio_source, options_state::audio_spectral, options_state::audio_spectral_gate, options_state::audio_spectral_mixer, options_state::auto_height, options_state::auto_width, options_state::color, options_state::color_filter, options_state::color_mode, options_state::color_scheme_name, COLOR_SETTING_FALSE, options_state::compression_level, options_state::disable_keepawake, options_state::discovery, options_state::discovery_database_path, options_state::discovery_expose_ip, options_state::discovery_insecure, options_state::discovery_port, options_state::discovery_server, options_state::enable_keepawake, options_state::enable_upnp, options_state::encode_audio, options_state::encrypt_enabled, options_state::fft, options_state::fft_scale, options_state::flip_x, options_state::flip_y, options_state::force_utf8, options_state::fps, options_state::grep_pattern, options_state::height, options_state::help, options_state::json, options_state::lan_discovery, options_state::log_file, options_state::log_level, options_state::matrix_rain, options_state::max_clients, options_state::media_from_stdin, options_state::media_loop, options_state::media_seek_timestamp, options_state::microphone_channel, options_state::microphone_channels, options_state::microphone_index, options_state::microphone_sensitivity, options_state::mode_arg_index, options_state::no_audio_mixer, options_state::no_auth, options_state::no_check_update, options_state::no_compress, options_state::no_encrypt, options_state::no_mdns_advertise, options_state::no_webrtc, options_state::num_identity_keys, OPT_ACDS_DEFAULT, OPT_ACDS_EXPOSE_IP_DEFAULT, OPT_ACDS_INSECURE_DEFAULT, OPT_ACDS_PORT_INT_DEFAULT, OPT_ADDRESS6_DEFAULT, OPT_ADDRESS_DEFAULT, OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT, OPT_AUDIO_CAPTURE_SOURCE_DEFAULT, OPT_AUDIO_ENABLED_DEFAULT, OPT_AUDIO_NO_PLAYBACK_DEFAULT, OPT_AUDIO_SOURCE_DEFAULT, OPT_AUTO_HEIGHT_DEFAULT, OPT_AUTO_WIDTH_DEFAULT, OPT_COLOR_DEFAULT, OPT_COLOR_FILTER_DEFAULT, OPT_COLOR_MODE_DEFAULT, OPT_COLOR_SCHEME_NAME_DEFAULT, OPT_COMPRESSION_LEVEL_DEFAULT, OPT_DISABLE_KEEPAWAKE_DEFAULT, OPT_ENABLE_KEEPAWAKE_DEFAULT, OPT_ENABLE_UPNP_DEFAULT, OPT_ENCODE_AUDIO_DEFAULT, OPT_ENCRYPT_ENABLED_DEFAULT, OPT_ENDPOINT_DISCOVERY_SERVICE, OPT_FLIP_X_DEFAULT, OPT_FLIP_Y_DEFAULT, OPT_FORCE_UTF8_DEFAULT, OPT_FPS_DEFAULT, OPT_HEIGHT_DEFAULT, OPT_HELP_DEFAULT, OPT_JSON_DEFAULT, OPT_LAN_DISCOVERY_DEFAULT, OPT_LOG_LEVEL_DEFAULT, OPT_MATRIX_RAIN_DEFAULT, OPT_MAX_CLIENTS_DEFAULT, OPT_MEDIA_FROM_STDIN_DEFAULT, OPT_MEDIA_LOOP_DEFAULT, OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT, OPT_MICROPHONE_INDEX_DEFAULT, OPT_MICROPHONE_SENSITIVITY_DEFAULT, OPT_NO_AUDIO_MIXER_DEFAULT, OPT_NO_AUTH_DEFAULT, OPT_NO_CHECK_UPDATE_DEFAULT, OPT_NO_COMPRESS_DEFAULT, OPT_NO_ENCRYPT_DEFAULT, OPT_NO_MDNS_ADVERTISE_DEFAULT, OPT_NO_WEBRTC_DEFAULT, OPT_OTEL_ENDPOINT_DEFAULT, OPT_PALETTE_CUSTOM_SET_DEFAULT, OPT_PALETTE_TYPE_DEFAULT, OPT_PAUSE_DEFAULT, OPT_PORT_INT_DEFAULT, OPT_PREFER_WEBRTC_DEFAULT, OPT_QUIET_DEFAULT, OPT_RECONNECT_ATTEMPTS_DEFAULT, OPT_RENDER_FONT_SIZE_DEFAULT, OPT_RENDER_MODE_DEFAULT, OPT_RENDER_THEME_DEFAULT, OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT, OPT_REQUIRE_CLIENT_VERIFY_DEFAULT, OPT_REQUIRE_SERVER_IDENTITY_DEFAULT, OPT_REQUIRE_SERVER_VERIFY_DEFAULT, OPT_SHOW_CAPABILITIES_DEFAULT, OPT_SNAPSHOT_DELAY_DEFAULT, OPT_SNAPSHOT_MODE_DEFAULT, OPT_SPEAKERS_INDEX_DEFAULT, OPT_SPEAKERS_VOLUME_DEFAULT, OPT_SPLASH_DEFAULT, OPT_STATUS_SCREEN_DEFAULT, OPT_STRETCH_DEFAULT, OPT_STRIP_ANSI_DEFAULT, OPT_STUN_SERVERS_DEFAULT, OPT_TEST_PATTERN_DEFAULT, OPT_TURN_CREDENTIAL_DEFAULT, OPT_TURN_SERVERS_DEFAULT, OPT_TURN_USERNAME_DEFAULT, OPT_VERBOSE_LEVEL_DEFAULT, OPT_VERSION_DEFAULT, OPT_WEBCAM_INDEX_DEFAULT, OPT_WEBRTC_DISABLE_TURN_DEFAULT, OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT, OPT_WEBRTC_SKIP_HOST_DEFAULT, OPT_WEBRTC_SKIP_STUN_DEFAULT, OPT_WEBSOCKET_PORT_SERVER_DEFAULT, OPT_WIDTH_DEFAULT, options_state::otel_enabled_telemetry, options_state::otel_endpoint, options_state::otel_log_level, options_state::otel_metrics_interval, options_state::otel_queue_capacity, options_state::otel_realtime_max_per_second, options_state::otel_realtime_sample_rate, options_state::otel_timeout, options_state::palette_custom_set, options_state::palette_type, options_state::pause, options_state::port, options_state::prefer_webrtc, options_state::quiet, options_state::reconnect_attempts, options_state::reduce_noise, options_state::render_font_size, options_state::render_mode, options_state::render_theme, options_state::renderer, options_state::require_client_identity, options_state::require_client_verify, options_state::require_server_identity, options_state::require_server_verify, SAFE_STRNCPY, options_state::show_capabilities, options_state::snapshot_delay, options_state::snapshot_mode, options_state::speakers_index, options_state::speakers_volume, options_state::splash_screen, options_state::stabilize, options_state::status_screen, options_state::stretch, options_state::strip_ansi, options_state::stun_servers, options_state::test_audio, options_state::test_pattern, options_state::turn_credential, options_state::turn_servers, options_state::turn_username, options_state::verbose_level, options_state::version, options_state::waveform, options_state::webcam_index, options_state::webrtc_disable_turn, options_state::webrtc_ice_timeout_ms, options_state::webrtc_relay_only, options_state::webrtc_skip_host, options_state::webrtc_skip_stun, options_state::websocket_port, and options_state::width.

Referenced by acip_render_settings_options(), config_create_default(), options_init(), options_state_init(), options_t_new_preserve_binary(), and session_settings_to_options().

◆ options_terminal_settings_ptr()

const terminal_options_t * options_terminal_settings_ptr ( void )

#include <include/ascii-chat/options/options.h>

Definition at line 541 of file rcu.c.

541 {
542 static terminal_options_t settings;
543 const options_t *options = options_get();
544 if (!options)
545 return NULL;
546 settings = (terminal_options_t){
547 .color = (terminal_color_setting_t)options->color,
548 .color_mode = options->color_mode,
549 .force_utf8 = (terminal_utf8_setting_t)options->force_utf8,
550 .render_mode = options->render_mode,
551 .width = options->width,
552 .height = options->height,
553 .fps = options->fps,
554 .snapshot_mode = options->snapshot_mode,
555 };
556 return &settings;
557}

References options_state::color, options_state::color_mode, options_state::force_utf8, options_state::fps, options_state::height, options_get(), options_state::render_mode, options_state::snapshot_mode, and options_state::width.

◆ parse_manpage_sections()

parsed_section_t * parse_manpage_sections ( const char * filepath,
size_t * num_sections )

#include <include/ascii-chat/options/manpage.h>

Parse existing man page template to extract sections.

Parameters
filepathPath to existing man page template (.1.in file)
num_sectionsOutput: number of sections found
Returns
Array of parsed sections (caller must free with free_parsed_sections)
NULL on error

Definition at line 808 of file manpage.c.

809 {
810 if (!filepath || !num_sections) {
811 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
812 return NULL;
813 }
814
815 FILE *f = platform_fopen("file_stream", filepath, "r");
816 if (!f) {
817 SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open file: %s", filepath);
818 return NULL;
819 }
820
821 parsed_section_t *sections = NULL;
822 asciichat_error_t err = manpage_parser_parse_file(f, &sections, num_sections);
823 fclose(f);
824
825 if (err != ASCIICHAT_OK) {
826 return NULL;
827 }
828
829 return sections;
830}
asciichat_error_t manpage_parser_parse_file(FILE *f, parsed_section_t **out_sections, size_t *out_count)
Parse man page sections from a FILE handle.
Definition parser.c:345
Owned slice of a parsed roff man-page section.
Definition manpage.h:49

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, manpage_parser_parse_file(), platform_fopen(), SET_ERRNO, and SET_ERRNO_SYS.

◆ strtoint_safe()

int strtoint_safe ( const char * str)

#include <include/ascii-chat/options/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.

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

31 {
32 if (!str || !*str)
33 return INT_MIN;
34 errno = 0;
35 char *end = NULL;
36 long value = strtol(str, &end, 10);
37 if (errno == ERANGE || end == str || *end != '\0' || value < INT_MIN ||
38 value > INT_MAX)
39 return INT_MIN;
40 return (int)value;
41}

Referenced by validate_opt_device_index(), and validate_opt_reconnect().

◆ update_dimensions_for_full_height()

void update_dimensions_for_full_height ( options_t * opts)

#include <include/ascii-chat/options/options.h>

Update dimensions to use full terminal height while maintaining aspect ratio.

Adjusts width and height to use the full terminal height while preserving the aspect ratio of the current dimensions. Useful for maximizing vertical space utilization.

Calculation:

  • Gets full terminal height via update_dimensions_to_terminal_size()
  • Calculates aspect ratio from current dimensions
  • Adjusts width to match new height while preserving ratio
  • Updates opts->width and opts->height

Example:

  • Current dimensions: 80×30 (aspect ratio 2.67)
  • Terminal size: 120×40
  • Result: 107×40 (maintains 2.67 ratio, uses full 40 height)

Usage:

// User presses key to maximize vertical space
// Redraw video feed with new dimensions
void update_dimensions_for_full_height(options_t *opts)
Update dimensions to use full terminal height while maintaining aspect ratio.
Parameters
optsPointer to options_t struct to update (must not be NULL)
Note
Updates opts->width and opts->height
Queries terminal size internally
Preserves aspect ratio of original dimensions
Useful for dynamic terminal resizing

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

553 {
554 if (!opts) {
555 return;
556 }
557
558 unsigned short int term_width, term_height;
559
560 // Note: Logging is not available during options_init, so we can't use
561 // log_debug here
562 asciichat_error_t result = get_terminal_size(&term_width, &term_height);
563
564 if (result == ASCIICHAT_OK) {
565 // If both dimensions are auto, set height to terminal height and let
566 // aspect_ratio calculate width
567 if (opts->auto_height && opts->auto_width) {
568 opts->height = term_height;
569 opts->width = term_width; // Also set width when both are auto
570 }
571 // If only height is auto, use full terminal height
572 else if (opts->auto_height) {
573 opts->height = term_height;
574 }
575 // If only width is auto, use full terminal width
576 else if (opts->auto_width) {
577 opts->width = term_width;
578 }
579 } else {
580 // Terminal size detection failed, but we can still continue with defaults
581 }
582}
int get_terminal_size(unsigned short int *width, unsigned short int *height)

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

◆ update_dimensions_to_terminal_size()

void update_dimensions_to_terminal_size ( options_t * opts)

#include <include/ascii-chat/options/options.h>

Update dimensions to match current terminal size.

Queries the current terminal for its size and updates width/height in the options struct. Uses platform-specific terminal size detection APIs.

Platform Implementations:

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

Usage:

  • Call during terminal resize (e.g., POSIX SIGWINCH handler)
  • Call to refresh dimensions when window size changes
  • Call when auto-detect is enabled and dimensions need updating

Example:

void handle_sigwinch(int sig) {
// Redraw UI with new dimensions
}
void update_dimensions_to_terminal_size(options_t *opts)
Update dimensions to match current terminal size.
Parameters
optsPointer to options_t struct to update (must not be NULL)
Note
Updates opts->width and opts->height directly
Uses platform-specific APIs for accuracy
Handles all failure modes with sensible fallbacks
Safe to call from signal handlers (POSIX)

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

584 {
585 if (!opts) {
586 return;
587 }
588
589 unsigned short int term_width, term_height;
590 // Get current terminal size (get_terminal_size already handles ioctl first,
591 // then $COLUMNS/$LINES fallback)
592 asciichat_error_t terminal_result =
593 get_terminal_size(&term_width, &term_height);
594 if (terminal_result == ASCIICHAT_OK) {
595 // Use INFO level so this is visible without -v flag (important for
596 // debugging dimension issues)
597 log_dev("Terminal size detected: %ux%u (auto_width=%d, auto_height=%d)",
598 term_width, term_height, opts->auto_width, opts->auto_height);
599 if (opts->auto_width) {
600 opts->width = term_width;
601 log_dev("Auto-width: set width to %u", opts->width);
602 }
603 if (opts->auto_height) {
604 opts->height = term_height;
605 log_dev("Auto-height: set height to %u", opts->height);
606 }
607 log_dev("Final dimensions: %ux%u", opts->width, opts->height);
608 } else {
609 // Terminal detection failed - keep the default values set in options_init()
610 log_warn("TERMINAL_DETECT_FAIL: Could not detect terminal size, using "
611 "defaults: %ux%u",
612 opts->width, opts->height);
613 }
614}
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591

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

◆ usage()

void usage ( FILE * stream,
asciichat_mode_t mode )

#include <include/ascii-chat/options/options.h>

Print usage information for a specific mode.

Parameters
streamFile stream to write to (typically stdout or stderr)
modeMode to show usage for (MODE_SERVER, MODE_CLIENT, MODE_MIRROR, etc.)

Generates and prints comprehensive help text for the requested mode.

Output Sections:

  • Program synopsis and description
  • Mode-specific usage syntax
  • All available options with descriptions
  • Options grouped by category (Network, Display, Encryption, etc.)
  • Option defaults and possible values
  • Common usage examples

Options Displayed:

  • Shows only options applicable to the requested mode
  • Includes both short and long forms (e.g., -p, --port)
  • Shows mode bitmask to indicate applicability to other modes
  • Marks required options where applicable
  • Shows default values where available

Typical Usage:

// In error handling
if (options_init(argc, argv) == ERROR_USAGE) {
asciichat_mode_t mode = GET_OPTION(detected_mode);
usage(stderr, mode);
return 1;
}
// For manual help display
usage(stdout, MODE_SERVER);
Note
Called automatically by options_init() for –help
Mode must be valid (MODE_SERVER, MODE_CLIENT, etc.)
Output formatted for 80-column terminals
Options grouped by functionality for readability

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

644 {
645 if (!desc) {
646 return;
647 }
648
649 // Find mode metadata
650 const mode_metadata_t *metadata = NULL;
651 for (size_t i = 0; i < sizeof(mode_info) / sizeof(mode_info[0]); i++) {
652 if (mode_info[i].mode == mode) {
653 metadata = &mode_info[i];
654 break;
655 }
656 }
657
658 if (!metadata) {
659 (void)fprintf(desc, "error: Unknown mode\n");
660 return;
661 }
662
663 flags_schema_builder_t *builder = flags_schema_builder_create();
664 if (!builder) {
665 (void)fprintf(desc, "Error: Failed to create libflags schema\n");
666 return;
667 }
668 const option_mode_bitmask_t mode_mask =
669 mode == MODE_DISCOVERY
671 : (option_mode_bitmask_t)(OPTION_MODE_BINARY | (1U << mode));
672 if (registry_add_all_to_flags_builder(builder, mode_mask) != ASCIICHAT_OK ||
673 !flags_help_write_options(flags_schema_builder_schema(builder),
674 metadata->program_name, metadata->description,
675 desc)) {
676 (void)fprintf(desc, "Error: Failed to render options\n");
677 }
678 flags_schema_builder_destroy(builder);
679}
struct flags_schema_builder flags_schema_builder_t
asciichat_error_t registry_add_all_to_flags_builder(flags_schema_builder_t *builder, option_mode_bitmask_t mode_mask)
Definition public_api.c:84
Mode metadata for usage display.
const char * program_name
Program name shown in usage.
const char * description
One-line description of mode.

References ASCIICHAT_OK, mode_metadata_t::description, MODE_DISCOVERY, OPTION_MODE_ALL, OPTION_MODE_BINARY, mode_metadata_t::program_name, and registry_add_all_to_flags_builder().

Referenced by action_help_acds(), action_help_client(), action_help_discovery(), action_help_mirror(), action_help_server(), manpage_content_generate_usage(), and manpage_merger_generate_usage().

◆ validate_glyph_palette()

asciichat_error_t validate_glyph_palette ( const options_t * opts)

#include <include/ascii-chat/options/validation.h>

Validate the selected glyph palette after options have been normalized.

Definition at line 25 of file validation.c.

25 {
26 if (!opts)
27 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing options for glyph palette validation");
28 if (opts->renderer != ASCII_RENDERER_GLYPH || !opts->palette_explicit)
29 return ASCIICHAT_OK;
30 const palette_def_t *builtin = get_builtin_palette(opts->palette_type);
31 const char *palette = opts->palette_type == PALETTE_CUSTOM ? opts->palette_custom : builtin ? builtin->chars : NULL;
33 return SET_ERRNO(ERROR_INVALID_PARAM, "Glyph palette contains characters without glyph masks");
34 return ASCIICHAT_OK;
35}
const palette_def_t * get_builtin_palette(palette_type_t type)
Get built-in palette definition.
Definition palette.c:45
const char * chars
Character sequence (ordered from dark to light).
Definition palette.h:134
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:110
bool ascii_render_palette_supported(ascii_renderer_t kind, const char *palette)
bool palette_explicit
Palette explicitly selected.
Definition options.h:1223
char palette_custom[256]
Custom palette characters.
Definition options.h:1221
Validated luminance palette used to turn brightness into characters.
Definition palette.h:130
@ ASCII_RENDERER_GLYPH

References ascii_render_palette_supported(), ASCII_RENDERER_GLYPH, ASCIICHAT_OK, palette_def_t::chars, ERROR_INVALID_PARAM, get_builtin_palette(), PALETTE_CUSTOM, options_state::palette_custom, options_state::palette_explicit, options_state::palette_type, options_state::renderer, and SET_ERRNO.

Referenced by options_init(), and options_prepare_patch().

◆ validate_opt_color_mode()

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

#include <include/ascii-chat/options/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 147 of file validation.c.

147 {
148 if (!value_str) {
149 if (error_msg) {
150 SAFE_SNPRINTF(error_msg, error_msg_size, "Color mode value is required");
151 }
152 return -1;
153 }
154
155 if (strcmp(value_str, OPT_VALUE_AUTO) == 0) {
156 return COLOR_MODE_AUTO;
157 }
158 if (strcmp(value_str, OPT_COLOR_MODE_NONE) == 0 || strcmp(value_str, OPT_COLOR_MODE_MONO) == 0) {
159 return COLOR_MODE_NONE;
160 }
161 if (strcmp(value_str, OPT_COLOR_MODE_16) == 0 || strcmp(value_str, "16color") == 0) {
162 return COLOR_MODE_16_COLOR;
163 }
164 if (strcmp(value_str, OPT_COLOR_MODE_256) == 0 || strcmp(value_str, "256color") == 0) {
166 }
167 if (strcmp(value_str, OPT_COLOR_MODE_TRUECOLOR) == 0 || strcmp(value_str, "24bit") == 0) {
169 }
170 if (error_msg) {
171 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid color mode '%s'. Valid modes: auto, none, mono, 16, 256, truecolor", value_str);
172 }
173 return -1;
174}
#define OPT_COLOR_MODE_256
Definition enums.h:106
#define OPT_COLOR_MODE_NONE
Definition enums.h:103
#define OPT_VALUE_AUTO
Definition enums.h:82
#define OPT_COLOR_MODE_TRUECOLOR
Definition enums.h:107
#define OPT_COLOR_MODE_MONO
Definition enums.h:104
#define OPT_COLOR_MODE_16
Definition enums.h:105
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define COLOR_MODE_16_COLOR
16-color mode (full name)
Definition options.h:226
#define COLOR_MODE_256_COLOR
256-color mode (full name)
Definition options.h:228
#define COLOR_MODE_TRUECOLOR
24-bit truecolor mode
Definition options.h:229
#define COLOR_MODE_AUTO
Backward compatibility aliases for color mode enum values.
Definition options.h:223
#define COLOR_MODE_NONE
Monochrome mode.
Definition options.h:224

References COLOR_MODE_16_COLOR, COLOR_MODE_256_COLOR, COLOR_MODE_AUTO, COLOR_MODE_NONE, COLOR_MODE_TRUECOLOR, OPT_COLOR_MODE_16, OPT_COLOR_MODE_256, OPT_COLOR_MODE_MONO, OPT_COLOR_MODE_NONE, OPT_COLOR_MODE_TRUECOLOR, OPT_VALUE_AUTO, and SAFE_SNPRINTF.

◆ validate_opt_compression_level()

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

#include <include/ascii-chat/options/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 389 of file validation.c.

389 {
390 int result = validate_int_range(value_str, 1, 9, "Compression level", error_msg, error_msg_size);
391 return (result == INT_MIN) ? -1 : result;
392}

◆ validate_opt_device_index()

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

#include <include/ascii-chat/options/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 456 of file validation.c.

456 {
457 if (!value_str || strlen(value_str) == 0) {
458 if (error_msg) {
459 SAFE_SNPRINTF(error_msg, error_msg_size, "Device index value is required");
460 }
461 return INT_MIN;
462 }
463
464 int index = strtoint_safe(value_str);
465 if (index == INT_MIN) {
466 if (error_msg) {
467 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid device index '%s'. Must be -1 (default) or a non-negative integer.", value_str);
468 }
469 return INT_MIN;
470 }
471
472 // -1 is valid (system default), otherwise must be >= 0
473 if (index < -1) {
474 if (error_msg) {
475 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid device index '%d'. Must be -1 (default) or a non-negative integer.", index);
476 }
477 return INT_MIN;
478 }
479 return index;
480}

References index, SAFE_SNPRINTF, and strtoint_safe().

◆ validate_opt_float_non_negative()

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

#include <include/ascii-chat/options/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 322 of file validation.c.

322 {
323 if (!value_str || strlen(value_str) == 0) {
324 if (error_msg) {
325 SAFE_SNPRINTF(error_msg, error_msg_size, "Value is required");
326 }
327 return -1.0f;
328 }
329
330 char *endptr;
331 float val = strtof(value_str, &endptr);
332 if (*endptr != '\0' || value_str == endptr || !isfinite(val)) {
333 if (error_msg) {
334 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid float value '%s'. Must be a number.", value_str);
335 }
336 return -1.0f;
337 }
338 if (val < 0.0f) {
339 if (error_msg) {
340 SAFE_SNPRINTF(error_msg, error_msg_size, "Value must be non-negative (got %.2f)", val);
341 }
342 return -1.0f;
343 }
344 return val;
345}

References SAFE_SNPRINTF.

◆ validate_opt_fps()

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

#include <include/ascii-chat/options/validation.h>

Validate FPS value (0 for auto, otherwise 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 0-144.

Validate FPS value (0 for auto, otherwise 1-144) Returns parsed value on success, -1 on error

Definition at line 398 of file validation.c.

398 {
399 int result = validate_int_range(value_str, 0, 144, "FPS", error_msg, error_msg_size);
400 return (result == INT_MIN) ? -1 : result;
401}

◆ validate_opt_ip_address()

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 <include/ascii-chat/options/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 272 of file validation.c.

272 {
273 (void)is_client; // Parameter not used but kept for API consistency
274 if (!value_str || strlen(value_str) == 0) {
275 if (error_msg) {
276 SAFE_SNPRINTF(error_msg, error_msg_size, "Address value is required");
277 }
278 return -1;
279 }
280
281 // Parse IPv6 address (remove brackets if present)
282 char parsed_addr[OPTIONS_BUFF_SIZE];
283 if (parse_ipv6_address(value_str, parsed_addr, sizeof(parsed_addr)) == 0) {
284 value_str = parsed_addr;
285 }
286
287 // Check if it's a valid IPv4 address
288 if (is_valid_ipv4(value_str)) {
289 SAFE_SNPRINTF(parsed_address, address_size, "%s", value_str);
290 return 0;
291 }
292 // Check if it's a valid IPv6 address
293 if (is_valid_ipv6(value_str)) {
294 SAFE_SNPRINTF(parsed_address, address_size, "%s", value_str);
295 return 0;
296 }
297 // Check if it looks like an invalid IP (has dots but not valid IPv4 format)
298 if (strchr(value_str, '.') != NULL) {
299 if (error_msg) {
300 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid IP address format '%s'. IPv4 addresses must have exactly 4 octets.", value_str);
301 }
302 return -1;
303 }
304
305 // Otherwise, try to resolve as hostname
306 char resolved_ip[OPTIONS_BUFF_SIZE];
307 if (platform_resolve_hostname_to_ipv4(value_str, resolved_ip, sizeof(resolved_ip)) == 0) {
308 SAFE_SNPRINTF(parsed_address, address_size, "%s", resolved_ip);
309 return 0;
310 } else {
311 if (error_msg) {
312 SAFE_SNPRINTF(error_msg, error_msg_size, "Failed to resolve hostname '%s' to IP address.", value_str);
313 }
314 return -1;
315 }
316}
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:32
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:64
int parse_ipv6_address(const char *input, char *output, size_t output_size)
Parse IPv6 address, removing brackets if present.
Definition ip.c:117

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

◆ validate_opt_log_level()

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

#include <include/ascii-chat/options/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 239 of file validation.c.

239 {
240 if (!value_str) {
241 if (error_msg) {
242 SAFE_SNPRINTF(error_msg, error_msg_size, "Log level value is required");
243 }
244 return -1;
245 }
246
247 if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_DEV) == 0) {
248 return LOG_DEV;
249 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_DEBUG) == 0) {
250 return LOG_DEBUG;
251 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_INFO) == 0) {
252 return LOG_INFO;
253 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_WARN) == 0) {
254 return LOG_WARN;
255 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_ERROR) == 0) {
256 return LOG_ERROR;
257 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_FATAL) == 0) {
258 return LOG_FATAL;
259 } else {
260 if (error_msg) {
261 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid log level '%s'. Valid levels: dev, debug, info, warn, error, fatal", value_str);
262 }
263 return -1;
264 }
265}
#define OPT_LOG_LEVEL_DEV
Definition enums.h:94
#define OPT_LOG_LEVEL_FATAL
Definition enums.h:99
#define OPT_LOG_LEVEL_ERROR
Definition enums.h:98
#define OPT_LOG_LEVEL_INFO
Definition enums.h:96
#define OPT_LOG_LEVEL_DEBUG
Definition enums.h:95
#define OPT_LOG_LEVEL_WARN
Definition enums.h:97
#define LOG_DEV
Definition log/types.h:42
#define LOG_DEBUG
Definition log/types.h:43
#define LOG_FATAL
Definition log/types.h:47
#define LOG_ERROR
Definition log/types.h:46
#define LOG_WARN
Definition log/types.h:45
#define LOG_INFO
Definition log/types.h:44
int platform_strcasecmp(const char *s1, const char *s2)

References LOG_DEBUG, LOG_DEV, LOG_ERROR, LOG_FATAL, LOG_INFO, LOG_WARN, OPT_LOG_LEVEL_DEBUG, OPT_LOG_LEVEL_DEV, OPT_LOG_LEVEL_ERROR, OPT_LOG_LEVEL_FATAL, OPT_LOG_LEVEL_INFO, OPT_LOG_LEVEL_WARN, platform_strcasecmp(), and SAFE_SNPRINTF.

Referenced by parse_log_level_option().

◆ validate_opt_max_clients()

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

#include <include/ascii-chat/options/validation.h>

Validate max clients value (1-128).

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-128.

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

Definition at line 380 of file validation.c.

380 {
381 int result = validate_int_range(value_str, 1, MAX_SESSION_PARTICIPANTS, "Max clients", error_msg, error_msg_size);
382 return (result == INT_MIN) ? -1 : result;
383}
#define MAX_SESSION_PARTICIPANTS

References MAX_SESSION_PARTICIPANTS.

◆ validate_opt_non_negative_int()

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

#include <include/ascii-chat/options/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 138 of file validation.c.

138 {
139 int result = validate_int_range(value_str, 0, INT_MAX, "Value", error_msg, error_msg_size);
140 return (result == INT_MIN) ? -1 : result;
141}

◆ validate_opt_palette()

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

#include <include/ascii-chat/options/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 207 of file validation.c.

207 {
208 if (!value_str) {
209 if (error_msg) {
210 SAFE_SNPRINTF(error_msg, error_msg_size, "Palette value is required");
211 }
212 return -1;
213 }
214
215 if (strcmp(value_str, OPT_PALETTE_STANDARD) == 0) {
216 return PALETTE_STANDARD;
217 } else if (strcmp(value_str, OPT_PALETTE_BLOCKS) == 0) {
218 return PALETTE_BLOCKS;
219 } else if (strcmp(value_str, OPT_PALETTE_DIGITAL) == 0) {
220 return PALETTE_DIGITAL;
221 } else if (strcmp(value_str, OPT_PALETTE_MINIMAL) == 0) {
222 return PALETTE_MINIMAL;
223 } else if (strcmp(value_str, OPT_PALETTE_COOL) == 0) {
224 return PALETTE_COOL;
225 } else if (strcmp(value_str, OPT_PALETTE_CUSTOM) == 0) {
226 return PALETTE_CUSTOM;
227 } else {
228 if (error_msg) {
229 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid palette '%s'. Valid palettes: standard, blocks, digital, minimal, cool, custom", value_str);
230 }
231 return -1;
232 }
233}
#define OPT_PALETTE_CUSTOM
Definition enums.h:130
#define OPT_PALETTE_COOL
Definition enums.h:129
#define OPT_PALETTE_MINIMAL
Definition enums.h:128
#define OPT_PALETTE_BLOCKS
Definition enums.h:126
#define OPT_PALETTE_STANDARD
Definition enums.h:125
#define OPT_PALETTE_DIGITAL
Definition enums.h:127
@ PALETTE_BLOCKS
Unicode block characters: " ░░▒▒▓▓██".
Definition palette.h:102
@ PALETTE_COOL
Ascending blocks: " ▁▂▃▄▅▆▇█".
Definition palette.h:108
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:100
@ PALETTE_DIGITAL
Digital/glitch aesthetic: " -=≡≣▰▱◼".
Definition palette.h:104
@ PALETTE_MINIMAL
Simple ASCII: " .-+*#".
Definition palette.h:106

References OPT_PALETTE_BLOCKS, OPT_PALETTE_COOL, OPT_PALETTE_CUSTOM, OPT_PALETTE_DIGITAL, OPT_PALETTE_MINIMAL, OPT_PALETTE_STANDARD, PALETTE_BLOCKS, PALETTE_COOL, PALETTE_CUSTOM, PALETTE_DIGITAL, PALETTE_MINIMAL, PALETTE_STANDARD, and SAFE_SNPRINTF.

◆ validate_opt_password()

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

#include <include/ascii-chat/options/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 486 of file validation.c.

486 {
487 if (!value_str) {
488 if (error_msg) {
489 SAFE_SNPRINTF(error_msg, error_msg_size, "Password value is required");
490 }
491 return -1;
492 }
493
494 size_t len = strlen(value_str);
495 if (len < 8) {
496 if (error_msg) {
497 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too short (%zu chars). Must be at least 8 characters.", len);
498 }
499 return -1;
500 }
501 if (len > 256) {
502 if (error_msg) {
503 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too long (%zu chars). Must be at most 256 characters.", len);
504 }
505 return -1;
506 }
507
508 // Note: No need to check for embedded null bytes - strlen() already stopped at the first null,
509 // so by definition there are no null bytes within [0, len).
510
511 return 0;
512}

References SAFE_SNPRINTF.

◆ validate_opt_port()

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

#include <include/ascii-chat/options/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 85 of file validation.c.

85 {
86 if (!value_str || strlen(value_str) == 0) {
87 if (error_msg) {
88 SAFE_SNPRINTF(error_msg, error_msg_size, "Port value is required");
89 }
90 return -1;
91 }
92
93 // Use safe integer parsing with range validation
94 uint16_t port_num;
95 if (parse_port(value_str, &port_num) != ASCIICHAT_OK) {
96 if (error_msg) {
97 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid port value '%s'. Port must be a number between 1 and 65535.", value_str);
98 }
99 return -1;
100 }
101 return 0;
102}
unsigned short uint16_t
asciichat_error_t parse_port(const char *str, uint16_t *out_port)
Parse port number (1-65535) from string.

References ASCIICHAT_OK, parse_port(), and SAFE_SNPRINTF.

◆ validate_opt_positive_int()

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

#include <include/ascii-chat/options/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 129 of file validation.c.

129 {
130 int result = validate_int_range(value_str, 1, INT_MAX, "Value", error_msg, error_msg_size);
131 return (result == INT_MIN) ? -1 : result;
132}

◆ validate_opt_reconnect()

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

#include <include/ascii-chat/options/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 OPT_VALUE_AUTO (unlimited retries) 1-999 for specific retry count INT_MIN on parse error

Definition at line 411 of file validation.c.

411 {
412 if (!value_str || strlen(value_str) == 0) {
413 if (error_msg) {
414 SAFE_SNPRINTF(error_msg, error_msg_size, "Reconnect value is required");
415 }
416 return INT_MIN;
417 }
418
419 // Check for string values first
420 if (platform_strcasecmp(value_str, "off") == 0) {
421 return 0; // No retries
422 }
423 if (platform_strcasecmp(value_str, OPT_VALUE_AUTO) == 0) {
424 return -1; // Unlimited retries
425 }
426
427 // Parse as integer
428 int val = strtoint_safe(value_str);
429 if (val == INT_MIN) {
430 if (error_msg) {
431 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect value '%s'. Use 'off', 'auto', or a number 0-999.", value_str);
432 }
433 return INT_MIN;
434 }
435
436 // 0 means off, -1 means auto, 1-999 is valid range
437 if (val == 0) {
438 return 0; // No retries
439 }
440 if (val == -1) {
441 return -1; // Unlimited retries
442 }
443 if (val < 1 || val > 999) {
444 if (error_msg) {
445 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect count '%s'. Must be 'off', 'auto', or 1-999.", value_str);
446 }
447 return INT_MIN;
448 }
449 return val;
450}

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

◆ validate_opt_render_mode()

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

#include <include/ascii-chat/options/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 180 of file validation.c.

180 {
181 if (!value_str) {
182 if (error_msg) {
183 SAFE_SNPRINTF(error_msg, error_msg_size, "Render mode value is required");
184 }
185 return -1;
186 }
187
188 if (strcmp(value_str, OPT_RENDER_MODE_FOREGROUND) == 0 || strcmp(value_str, OPT_RENDER_MODE_FG) == 0) {
189 return RENDER_MODE_FOREGROUND;
190 }
191 if (strcmp(value_str, OPT_RENDER_MODE_BACKGROUND) == 0 || strcmp(value_str, OPT_RENDER_MODE_BG) == 0) {
192 return RENDER_MODE_BACKGROUND;
193 }
194 if (strcmp(value_str, OPT_RENDER_MODE_HALF_BLOCK) == 0 || strcmp(value_str, "halfblock") == 0) {
195 return RENDER_MODE_HALF_BLOCK;
196 }
197 if (error_msg) {
198 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid render mode '%s'. Valid modes: foreground, background, half-block", value_str);
199 }
200 return -1;
201}
#define OPT_RENDER_MODE_BG
Definition enums.h:136
#define OPT_RENDER_MODE_FOREGROUND
Definition enums.h:133
#define OPT_RENDER_MODE_HALF_BLOCK
Definition enums.h:137
#define OPT_RENDER_MODE_FG
Definition enums.h:134
#define OPT_RENDER_MODE_BACKGROUND
Definition enums.h:135

References OPT_RENDER_MODE_BACKGROUND, OPT_RENDER_MODE_BG, OPT_RENDER_MODE_FG, OPT_RENDER_MODE_FOREGROUND, OPT_RENDER_MODE_HALF_BLOCK, and SAFE_SNPRINTF.

◆ validate_opt_volume()

float validate_opt_volume ( const char * value_str,
char * error_msg,
size_t error_msg_size )

#include <include/ascii-chat/options/validation.h>

Validate volume value (0.0-1.0).

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

Validates that the string is a valid volume in the range 0.0 to 1.0. Used for –volume, –microphone-volume, and similar audio options.

Validate volume value (0.0-1.0) Returns parsed value on success, -1.0f on error

Definition at line 351 of file validation.c.

351 {
352 if (!value_str || strlen(value_str) == 0) {
353 if (error_msg) {
354 SAFE_SNPRINTF(error_msg, error_msg_size, "Volume value is required");
355 }
356 return -1.0f;
357 }
358
359 char *endptr;
360 float val = strtof(value_str, &endptr);
361 if (*endptr != '\0' || value_str == endptr || !isfinite(val)) {
362 if (error_msg) {
363 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid volume value '%s'. Must be a number.", value_str);
364 }
365 return -1.0f;
366 }
367 if (val < 0.0f || val > 1.0f) {
368 if (error_msg) {
369 SAFE_SNPRINTF(error_msg, error_msg_size, "Volume must be between 0.0 and 1.0 (got %.2f)", val);
370 }
371 return -1.0f;
372 }
373 return val;
374}

References SAFE_SNPRINTF.

Variable Documentation

◆ BLUE

unsigned short int BLUE[]
extern

#include <include/ascii-chat/options/options.h>

Blue channel lookup table.

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

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

Referenced by precalc_rgb_palettes().

◆ GRAY

unsigned short int GRAY[]
extern

#include <include/ascii-chat/options/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 339 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ GREEN

unsigned short int GREEN[]
extern

#include <include/ascii-chat/options/options.h>

Green channel lookup table.

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

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

Referenced by precalc_rgb_palettes().

◆ RED

unsigned short int RED[]
extern

#include <include/ascii-chat/options/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 336 of file options/common.c.

Referenced by precalc_rgb_palettes().

◆ weight_blue

const float weight_blue
extern

#include <include/ascii-chat/options/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 332 of file options/common.c.

Referenced by server_main().

◆ weight_green

const float weight_green
extern

#include <include/ascii-chat/options/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 331 of file options/common.c.

Referenced by server_main().

◆ weight_red

const float weight_red
extern

#include <include/ascii-chat/options/options.h>

Red weight for luminance calculation.

Weight for red channel in luminance calculation.

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

Referenced by server_main().