ascii-chat
Binary v0.15.83-53-gb711d8720
Library lib/v0.3.2-701-gb711d8720
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  options.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  configuration.c
 Configuration file options.
file  core.c
 Internal helper functions 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  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  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
#define options_terminal_settings()
#define GET_OPTION(field)
 Safely get a specific option field (lock-free read).

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 = (1 << 0) , OPT_GROUP_TERMINAL = (1 << 1) , OPT_GROUP_NETWORK = (1 << 2) ,
  OPT_GROUP_WEBCAM = (1 << 3) , OPT_GROUP_DISPLAY = (1 << 4) , 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 = (1 << 11) , OPT_GROUP_CLIENT = (1 << 12) , 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...
enum  ascii_renderer_t { ASCII_RENDERER_LUMINANCE = 0 , ASCII_RENDERER_GLYPH = 1 }
 Consolidated options structure. 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:44
@ ASCIICHAT_OK
Definition error_codes.h:46
#define GET_OPTION(field)
Safely get a specific option field (lock-free read).
Definition options.h:1336
asciichat_mode_t
Mode type for options parsing.
Definition options.h:919
asciichat_error_t options_set_int(const char *name, int value)
Check if an option was explicitly set via command-line.
Definition rcu.c:894
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:511
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2417
asciichat_error_t options_set_bool(const char *name, bool value)
Definition rcu.c:902
int main(int argc, char *argv[])
Definition main.c:514
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:983
int height
Terminal height in characters (int for OPTION_TYPE_INT compat).
Definition options.h:997
int width
Terminal width in characters (int for OPTION_TYPE_INT compat).
Definition options.h:996

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:169
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:547
@ OPTION_MODE_CLIENT
Client mode (bit 1).
Definition options.h:939
asciichat_error_t options_registry_add_all_to_builder(options_builder_t *builder)
Add all options from registry to builder.
Definition public_api.c:20
asciichat_error_t options_state_init(void)
Initialize RCU options system.
Definition rcu.c:380
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:450
The complete registry entry for one command-line/configuration option.
Definition builder.h:249
Immutable parsing tables produced from an options builder.
Definition builder.h:457
Immutable parsing tables produced from an options builder.
Definition builder.h:414

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:25
unsigned int height
Definition fft.c:23
unsigned int width
Definition fft.c:23
@ MODE_SERVER
Server mode - network server options.
Definition options.h:920
return true
Definition queries.h:13

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:166
option_mode_bitmask_t
Option mode bitmask.
Definition options.h:936
Completion metadata attached to one option descriptor.
Definition builder.h:197

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:184
@ OPTION_TYPE_INT
Integer value (–count 42).
Definition builder.h:168
@ OPTION_MODE_SERVER
Server mode (bit 0).
Definition options.h:938

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:342

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:476

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:946
@ OPTION_MODE_BINARY
Binary-level options (parsed before mode detection).
Definition options.h:945
@ OPTION_MODE_MIRROR
Mirror mode (bit 2).
Definition options.h:940
@ OPTION_MODE_DISCOVERY_SVC
Discovery server mode (bit 3).
Definition options.h:941

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:921

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)
Definition common.h:377
#define log_error(...)
Log an ERROR message.
Definition log/log.h:634

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:449
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor).
Definition options.h:1092

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:170

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:48
int port
Server port number.
Definition options.h:1009

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>

Definition at line 967 of file options.h.

Referenced by options_t_new().

◆ COLOR_MODE_16

#define COLOR_MODE_16   TERM_COLOR_16

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

16-color mode (alias)

Definition at line 224 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 225 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 226 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 227 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 222 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 typeof(((options_t *)0)->field) _default = {0}; \
(_opts ? (_opts->field) : _default); \
})

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

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

Usage Examples:

// Simple field access
const char *addr = GET_OPTION(address6);
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 1336 of file options.h.

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

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(), capture_init(), client_connection_start(), client_crypto_init(), client_init(), client_main(), client_protocol_start(), colored_string(), debug_stats_poll(), discovery_main(), display_init(), EMSCRIPTEN_BINDINGS(), ffmpeg_decoder_create_stdin(), ffmpeg_encoder_write_frame(), 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(), main(), 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(), tui_stats_render(), ui_buttons_render(), ui_controller_show_volume(), ui_controller_title_start(), ui_controller_toggle_logs(), 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_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_display(), ui_status_display_interactive(), ui_status_render_header(), ui_status_update(), ui_sync_render(), ui_table_row(), update_banner_print_instructions(), update_banner_show_prompt(), utf8_output_enabled(), and visualization_encode().

◆ 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(), 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:59
@ OPT_GROUP_ACDS
ACDS discovery service options.
Definition groups.h:61
@ OPT_GROUP_BINARY
Binary-level options (help, version, logging).
Definition groups.h:52
@ OPT_GROUP_COMPRESSION
Compression options.
Definition groups.h:60
@ OPT_GROUP_NETWORK
Network options (address, port, reconnect).
Definition groups.h:54
@ OPT_GROUP_SERVER
Server-specific options (max_clients, client-keys).
Definition groups.h:63
@ OPT_GROUP_WEBRTC
WebRTC connectivity options (STUN/TURN).
Definition groups.h:65

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 78 of file groups.h.

78#define MODE_SERVER_GROUPS \
79 (OPT_GROUP_BINARY | OPT_GROUP_NETWORK | OPT_GROUP_CRYPTO | OPT_GROUP_COMPRESSION | OPT_GROUP_ACDS | \
80 OPT_GROUP_SERVER | 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 591 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 600 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 603 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 597 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 594 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 544 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 541 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 723 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 708 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 703 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 726 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 706 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 430 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 427 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 454 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 461 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 433 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 370 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 585 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 338 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 335 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 618 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 729 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 736 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 560 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 631 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 628 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 634 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 637 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 640 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 502 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 505 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 448 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 499 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 476 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 364 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 424 of file options.h.

Referenced by options_t_new().

◆ 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 317 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 367 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 612 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 439 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 442 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 436 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 398 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 395 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 361 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 391 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 378 of file options.h.

378#define OPT_LOG_TEMPLATE_DEFAULT_DEBUG \
379 "[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
380 "[thread/%color(GREY, %tname)] %color(DEBUG, %file_relative):%color(GREY, %line)@%color(DEV, %func)(): " \
381 "%colored_message"

Referenced by 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 373 of file options.h.

373#define OPT_LOG_TEMPLATE_DEFAULT_RELEASE \
374 "[%color(*, %H):%color(*, %M):%color(*, %S).%color(*, %ms)] [%color(*, %level_aligned)] " \
375 "%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 496 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 579 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 576 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 528 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 525 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 531 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 711 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 717 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 518 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 742 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 341 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 588 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 739 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 615 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 675 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 354 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 470 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 467 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 534 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 564 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 567 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 672 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 348 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 582 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 772 of file options.h.

◆ OPT_RENDER_FONT_DEFAULT

#define OPT_RENDER_FONT_DEFAULT   ""

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

Definition at line 774 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 775 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 464 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 773 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 609 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 748 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 606 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 745 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 445 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 492 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 479 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 714 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 720 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 323 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 326 of file options.h.

Referenced by options_t_new().

◆ 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 329 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 332 of file options.h.

Referenced by options_t_new().

◆ OPT_STRETCH_DEFAULT

#define OPT_STRETCH_DEFAULT   false

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

Default allow aspect ratio distortion flag.

Definition at line 473 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 767 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 451 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 649 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 643 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 652 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 646 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 661 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 515 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 696 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 655 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 658 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 664 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 693 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 358 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 320 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 512 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 669 of file options.h.

Referenced by options_t_new().

◆ 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 681 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 687 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 690 of file options.h.

Referenced by options_t_new().

◆ 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 684 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 678 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 573 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 570 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 413 of file options.h.

Referenced by options_t_new().

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

Referenced by options_preset_unified().

◆ OPTION_MODE_NETWORKED

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

Definition at line 957 of file options.h.

957#define OPTION_MODE_NETWORKED \
958 (OPTION_MODE_SERVER | OPTION_MODE_CLIENT | OPTION_MODE_DISCOVERY_SVC | OPTION_MODE_DISCOVERY)

◆ 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 955 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 310 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(), 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

◆ ascii_renderer_t

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

Enumerator
ASCII_RENDERER_LUMINANCE 
ASCII_RENDERER_GLYPH 

Definition at line 966 of file options.h.

ascii_renderer_t
Consolidated options structure.
Definition options.h:966
@ ASCII_RENDERER_GLYPH
Definition options.h:966
@ ASCII_RENDERER_LUMINANCE
Definition options.h:966

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

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

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

290 {
audio_capture_source_t
Definition options.h:290
@ AUDIO_CAPTURE_SOURCE_BOTH
Definition options.h:294
@ AUDIO_CAPTURE_SOURCE_REMOTE
Definition options.h:295
@ AUDIO_CAPTURE_SOURCE_MEDIA
Definition options.h:293
@ AUDIO_CAPTURE_SOURCE_MIC
Definition options.h:292
@ 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 276 of file options.h.

276 {
audio_source_t
Audio source selected for visualization.
Definition options.h:276
@ AUDIO_SOURCE_MIC
Definition options.h:282
@ AUDIO_SOURCE_CALL
Definition options.h:280
@ AUDIO_SOURCE_MEDIA
Definition options.h:284
@ AUDIO_SOURCE_ALL
Definition options.h:278
@ AUDIO_SOURCE_AUTO
Definition options.h:286

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

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

◆ 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 50 of file groups.h.

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

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

936 {
937 OPTION_MODE_NONE = 0,
945 OPTION_MODE_BINARY = 0x100,
946 OPTION_MODE_ALL = 0x7F | 0x100
@ OPTION_MODE_API_SERVER
Definition options.h:944
@ OPTION_MODE_DISCOVERY
Discovery mode (bit 4).
Definition options.h:942
@ OPTION_MODE_NONE
No modes (invalid).
Definition options.h:937
@ OPTION_MODE_MCP_SERVER
Definition options.h:943

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

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

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 {
47 return str ? str : "";
48}

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 763 of file manpage.c.

763 {
764 return manpage_parser_find_section(sections, num_sections, section_name);
765}
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:405

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 50 of file manpage.c.

50 {
51 if (mode_bitmask == 0) {
52 return NULL;
53 }
54
55 option_mode_bitmask_t user_modes_mask = (1 << MODE_SERVER) | (1 << MODE_CLIENT) | (1 << MODE_MIRROR) |
57 (1 << MODE_MCP_SERVER);
58 if ((mode_bitmask & OPTION_MODE_BINARY) && !(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", pos > 0 ? ", " : "");
81 }
82 if (mode_bitmask & (1 << MODE_CLIENT)) {
83 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sclient", pos > 0 ? ", " : "");
84 }
85 if (mode_bitmask & (1 << MODE_SERVER)) {
86 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sserver", pos > 0 ? ", " : "");
87 }
88 if (mode_bitmask & (1 << MODE_MIRROR)) {
89 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%smirror", pos > 0 ? ", " : "");
90 }
91 if (mode_bitmask & (1 << MODE_DISCOVERY_SERVICE)) {
92 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%sdiscovery-service", pos > 0 ? ", " : "");
93 }
94
95 if (mode_bitmask & (1 << MODE_MCP_SERVER)) {
96 pos += safe_snprintf(mode_str + pos, sizeof(mode_str) - pos, "%smcp-server", pos > 0 ? ", " : "");
97 }
98
99 return pos > 0 ? mode_str : NULL;
100}
int safe_snprintf(char *buffer, size_t buffer_size, const char *format,...)
Platform-safe snprintf wrapper.
#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, OPTIONS_MANPAGE_MODE_BUFFER_SIZE, and safe_snprintf().

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 759 of file manpage.c.

759 {
760 manpage_parser_free_sections(sections, num_sections);
761}
void manpage_parser_free_sections(parsed_section_t *sections, size_t count)
Free parsed sections array.
Definition parser.c:388

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 122 of file options.c.

122 {
123 return g_action_flag;
124}

◆ 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 612 of file validation.c.

612 {
613 if (!key_path || key_path[0] == '\0') {
614 return false;
615 }
616 return (strncmp(key_path, "github:", 7) == 0 || strncmp(key_path, "gitlab:", 7) == 0 ||
617 strncmp(key_path, "gpg:", 4) == 0 || strncmp(key_path, "http://", 7) == 0 ||
618 strncmp(key_path, "https://", 8) == 0);
619}

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 75 of file levenshtein.c.

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

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

Referenced by find_similar_option(), 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 140 of file levenshtein.c.

140 {
141 if (!unknown || !candidates) {
142 return NULL;
143 }
144
145 const char *best_match = NULL;
146 size_t best_distance = SIZE_MAX;
147
148 for (int i = 0; candidates[i] != NULL; i++) {
149 size_t dist = levenshtein(unknown, candidates[i]);
150 if (dist < best_distance) {
151 best_distance = dist;
152 best_match = candidates[i];
153 }
154 }
155
156 // Only suggest if the distance is within our threshold
157 if (best_distance <= LEVENSHTEIN_SUGGESTION_THRESHOLD) {
158 return best_match;
159 }
160
161 return NULL;
162}
size_t levenshtein(const char *a, const char *b)
Calculate Levenshtein distance between two strings.
Definition levenshtein.c:75
#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 23 of file levenshtein.c.

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

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 229 of file manpage.c.

231 {
232 if (!builder || !program_name || !brief_description) {
233 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing required parameters");
234 }
235
236 const options_config_t *config = options_builder_build(builder);
237 if (!config) {
238 return SET_ERRNO(ERROR_CONFIG, "Failed to build options configuration");
239 }
240
241 return options_config_generate_manpage_template(config, program_name, mode_name, output_path, brief_description);
242}
@ ERROR_CONFIG
Definition error_codes.h:52
@ 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:106

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 540 of file validation.c.

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

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 768 of file manpage.c.

769 {
770 (void)template_path;
771 (void)output_path;
772 (void)version_string;
773 (void)content_file_path;
774 return SET_ERRNO(ERROR_CONFIG, "Not implemented in refactored version");
775}

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 688 of file manpage.c.

690 {
691 (void)mode_name; // Not used
692 (void)program_name; // Not used
693 (void)brief_description; // Not used
694
695 if (!config) {
696 return SET_ERRNO(ERROR_INVALID_PARAM, "config is required for man page generation");
697 }
698
699 FILE *f = NULL;
700 bool should_close = false;
701 asciichat_error_t err = manpage_open_merged_output(output_path, &f, &should_close);
702 if (err != ASCIICHAT_OK) {
703 return err;
704 }
705
706 // Load template resources
707 manpage_resources_t resources;
708 memset(&resources, 0, sizeof(resources));
709 err = manpage_resources_load(&resources);
710 if (err != ASCIICHAT_OK) {
711 if (should_close)
712 fclose(f);
713 return err;
714 }
715
716 if (!manpage_resources_is_valid(&resources)) {
717 if (should_close)
718 fclose(f);
719 manpage_resources_destroy(&resources);
720 return SET_ERRNO(ERROR_CONFIG, "Man page resources are not valid");
721 }
722
723 manpage_merge_template(f, config, resources.template_content);
724
725 manpage_resources_destroy(&resources);
726
727 fflush(f);
728 if (should_close) {
729 fclose(f);
730 }
731
732 log_debug("Generated merged man page to %s", output_path ? output_path : "stdout");
733 return ASCIICHAT_OK;
734}
void manpage_resources_destroy(manpage_resources_t *resources)
Cleanup allocated man page resources.
Definition resources.c:147
asciichat_error_t manpage_resources_load(manpage_resources_t *resources)
Load man page resources from embedded or filesystem sources.
Definition resources.c:103
bool manpage_resources_is_valid(const manpage_resources_t *resources)
Check if resources are available.
Definition resources.c:176
Man page resource container.
Definition resources.h:23
const char * template_content
Template file content (.1.in).
Definition resources.h:24

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.

Referenced by action_create_manpage().

◆ 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_t *builder = 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:229
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 106 of file manpage.c.

108 {
109 if (!config || !program_name || !brief_description) {
110 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing required parameters for man page generation");
111 }
112
113 FILE *f = NULL;
114 bool should_close = false;
115
116 if (output_path) {
117 f = platform_fopen("file_stream", output_path, "w");
118 if (!f) {
119 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open output file: %s", output_path);
120 }
121 should_close = true;
122 } else {
123 f = stdout;
124 }
125
126 // Write title/header
127 manpage_fmt_write_title(f, program_name, mode_name, brief_description);
128
129 // Write SYNOPSIS
130 char *synopsis_content = NULL;
131 size_t synopsis_len = 0;
132 asciichat_error_t err = manpage_merger_generate_synopsis(mode_name, &synopsis_content, &synopsis_len);
133 if (err == ASCIICHAT_OK && synopsis_content && synopsis_len > 0) {
134 fprintf(f, "%s", synopsis_content);
135 manpage_merger_free_content(synopsis_content);
136 }
137
138 // Write POSITIONAL ARGUMENTS if present
139 if (config->num_positional_args > 0) {
140 char *pos_content = manpage_content_generate_positional(config);
141 if (pos_content && *pos_content != '\0') {
142 fprintf(f, "%s", pos_content);
143 }
145 }
146
147 // Write DESCRIPTION
148 manpage_fmt_write_section(f, "DESCRIPTION");
149 fprintf(f, ".B ascii-chat\nis a terminal-based video chat application that converts webcam video to ASCII\n");
150 fprintf(f, "art in real-time. It enables video chat directly in your terminal, whether you're\n");
151 fprintf(f, "using a local console, a remote SSH session, or any terminal emulator.\n");
153
154 // Write USAGE
155 char *usage_content = NULL;
156 size_t usage_len = 0;
157 err = manpage_merger_generate_usage(config, &usage_content, &usage_len);
158 if (err == ASCIICHAT_OK && usage_content && usage_len > 0) {
159 fprintf(f, ".SH USAGE\n%s", usage_content);
160 manpage_merger_free_content(usage_content);
161 }
162
163 // Write OPTIONS
164 if (config->num_descriptors > 0) {
165 char *options_content = manpage_content_generate_options(config);
166 if (options_content && *options_content != '\0') {
167 fprintf(f, "%s", options_content);
168 }
169 manpage_content_free_options(options_content);
170 }
171
172 // Write EXAMPLES if present
173 if (config->num_examples > 0) {
174 char *examples_content = manpage_content_generate_examples(config);
175 if (examples_content && *examples_content != '\0') {
176 fprintf(f, "%s", examples_content);
177 }
178 manpage_content_free_examples(examples_content);
179 }
180
181 // Write ENVIRONMENT if present
182 bool has_env_vars = false;
183 for (size_t i = 0; i < config->num_descriptors; i++) {
184 if (config->descriptors[i].env_var_name) {
185 has_env_vars = true;
186 break;
187 }
188 }
189
190 if (has_env_vars) {
191 char *env_content = manpage_content_generate_environment(config);
192 if (env_content && *env_content != '\0') {
193 fprintf(f, "%s", env_content);
194 }
196 }
197
198 // Write placeholder manual sections
199 manpage_fmt_write_section(f, "FILES");
200 fprintf(f, ".I ~/.ascii-chat/config.toml\n");
201 fprintf(f, "User configuration file\n");
203
204 manpage_fmt_write_section(f, "NOTES");
205 fprintf(f, "For more information and examples, visit the project repository.\n");
207
208 manpage_fmt_write_section(f, "BUGS");
209 fprintf(f, "Report bugs at the project issue tracker.\n");
211
212 manpage_fmt_write_section(f, "AUTHOR");
213 fprintf(f, "Contributed by the ascii-chat community.\n");
215
216 manpage_fmt_write_section(f, "SEE ALSO");
217 fprintf(f, ".B man(1),\n");
218 fprintf(f, ".B groff_man(7)\n");
220
221 if (should_close) {
222 fclose(f);
223 }
224
225 log_debug("Generated man page template to %s", output_path ? output_path : "stdout");
226 return ASCIICHAT_OK;
227}
#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:149
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:74
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:268
option_descriptor_t * descriptors
Array of option descriptors.
Definition builder.h:415
size_t num_positional_args
Number of positional arguments.
Definition builder.h:422
size_t num_descriptors
Number of descriptors.
Definition builder.h:416
size_t num_examples
Number of examples.
Definition builder.h:433

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, 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 511 of file rcu.c.

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

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(), main(), 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.

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

2417 {
2418 log_debug("starting with argc=%d, argv[0]=%s, argv[1]=%s", argc, (argv && argc > 0 && argv[0]) ? argv[0] : "(null)",
2419 (argv && argc > 1 && argv[1]) ? argv[1] : "N/A");
2420 asciichat_error_t result = validate_options_argv(argc, argv);
2421 if (result != ASCIICHAT_OK) {
2422 return result;
2423 }
2424 result = options_state_init();
2425 if (result != ASCIICHAT_OK) {
2426 return result;
2427 }
2428 log_debug("options_init: state initialized");
2429
2430 // Discover binary actions before mode parsing so help and early exits need no media setup.
2431 handle_help_option(argc, argv);
2432 binary_actions_t actions = {.parsed_color_setting = COLOR_SETTING_AUTO};
2433 result = scan_binary_actions(argc, argv, &actions);
2434 if (result != ASCIICHAT_OK) {
2435 return result;
2436 }
2437 log_debug("options_init: binary actions scanned");
2438 set_action_flag(actions.has_action);
2439
2440 asciichat_mode_t detected_mode = MODE_DISCOVERY;
2441 char detected_session_string[SESSION_STRING_BUFFER_SIZE] = {0};
2442 int mode_index = -1;
2443 result = options_detect_mode(argc, argv, &detected_mode, detected_session_string, &mode_index);
2444 if (result != ASCIICHAT_OK) {
2445 return result;
2446 }
2447 result = validate_binary_option_position(argc, argv, mode_index);
2448 if (result != ASCIICHAT_OK) {
2449 return result;
2450 }
2451 result = validate_early_color_mode(argc, argv);
2452 if (result != ASCIICHAT_OK) {
2453 return result;
2454 }
2455
2456 options_t opts = options_t_new();
2457 log_debug("options_init: options constructed");
2458 initialize_binary_options(&opts, detected_mode, &actions);
2459 log_debug("options_init: binary options initialized");
2460 bool handled = false;
2461 result = handle_immediate_actions(&opts, &actions, &handled);
2462 if (result != ASCIICHAT_OK || handled) {
2463 return result;
2464 }
2465 result = parse_binary_options(&opts, argc, argv);
2466 if (result != ASCIICHAT_OK) {
2467 return result;
2468 }
2469 if (actions.show_version || actions.create_config || actions.create_manpage) {
2470 result = handle_fallback_actions(&opts, &actions);
2471 if (result != ASCIICHAT_OK) {
2472 return result;
2473 }
2474 return ASCIICHAT_OK;
2475 }
2476
2477 // Mode parsing owns the temporary argv and schema until the shared cleanup path.
2478 mode_arguments_t mode_args = {.argc = argc, .argv = argv};
2479 options_config_t *config = NULL;
2480 result = build_mode_argv(argc, argv, mode_index, &mode_args);
2481 if (result != ASCIICHAT_OK) {
2482 goto cleanup;
2483 }
2484 initialize_mode_defaults(&opts, detected_mode, detected_session_string);
2485 build_options_schema();
2486 // Apply defaults, config, environment, then CLI values in increasing precedence.
2487 bool fps_set_by_config = false;
2488 result = load_options_config(&opts, detected_mode, &fps_set_by_config);
2489 if (result != ASCIICHAT_OK)
2490 goto cleanup;
2491 config = options_preset_unified(NULL, NULL);
2492 if (!config) {
2493 result = SET_ERRNO(ERROR_CONFIG, "Failed to create options configuration");
2494 goto cleanup;
2495 }
2496 int remaining_argc;
2497 char **remaining_argv;
2498 result = parse_mode_options(&opts, config, detected_mode, mode_args.argc, mode_args.argv, &remaining_argc,
2499 &remaining_argv);
2500 if (result != ASCIICHAT_OK) {
2501 goto cleanup;
2502 }
2503 record_explicit_fps(&opts, mode_args.argc, mode_args.argv, fps_set_by_config);
2504 result = validate_custom_palette(&opts);
2505 if (result != ASCIICHAT_OK) {
2506 goto cleanup;
2507 }
2508 result = validate_glyph_palette(&opts);
2509 if (result != ASCIICHAT_OK)
2510 goto cleanup;
2511 // Remaining validators consume a published snapshot.
2512 result = publish_options_for_validation(&opts);
2513 if (result != ASCIICHAT_OK) {
2514 goto cleanup;
2515 }
2516 result = validate_encryption_key(&opts);
2517 if (result != ASCIICHAT_OK) {
2518 goto cleanup;
2519 }
2520 result = validate_color_filter(&opts);
2521 if (result != ASCIICHAT_OK) {
2522 goto cleanup;
2523 }
2524 record_explicit_screen_and_debug_options(&opts, mode_args.argc, mode_args.argv);
2525 record_explicit_stabilize(&opts, mode_args.argc, mode_args.argv);
2526 apply_screen_defaults(&opts, mode_args.argc, mode_args.argv);
2527 result = validate_option_strings(&opts);
2528 if (result != ASCIICHAT_OK) {
2529 goto cleanup;
2530 }
2531 result = validate_parsed_options(&opts, config, remaining_argc, remaining_argv);
2532 if (result != ASCIICHAT_OK) {
2533 goto cleanup;
2534 }
2535 result = finalize_mode_defaults(&opts, detected_mode);
2536 if (result != ASCIICHAT_OK) {
2537 goto cleanup;
2538 }
2539 log_debug("★ OPTIONS_CONFIG_DESTROY: About to call");
2540 options_config_destroy(config);
2541 config = NULL;
2542 log_debug("★ OPTIONS_CONFIG_DESTROY: Done");
2543
2544 log_debug("★ STAGE 7: Starting post-processing");
2545 // Resolve identity, dimensions, and media before exposing the final options to actions.
2546 result = collect_server_identity_keys(&opts, detected_mode, argc, argv);
2547 if (result != ASCIICHAT_OK) {
2548 goto cleanup;
2549 }
2550 finalize_dimensions(&opts);
2551 result = finalize_media_options(&opts);
2552 if (result != ASCIICHAT_OK) {
2553 goto cleanup;
2554 }
2555 result = publish_final_options(&opts, detected_mode, mode_index);
2556 if (result != ASCIICHAT_OK) {
2557 goto cleanup;
2558 }
2559 apply_logging_color_scheme(&opts);
2560
2561 // Deferred actions must see the final published options and may print output.
2562 if (actions.has_action) {
2564 }
2566
2567cleanup:
2568 if (config) {
2569 options_config_destroy(config);
2570 }
2571 SAFE_FREE(mode_args.allocated);
2572 return result;
2573}
void actions_execute_deferred(void)
Execute the deferred action (if any).
Definition actions.c:682
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log.c:746
asciichat_error_t validate_glyph_palette(const options_t *opts)
Definition validation.c:25
#define SESSION_STRING_BUFFER_SIZE
bool create_manpage
Definition options.c:933
The useful part of binary actions is in show_version, create_config, create_manpage,...
Definition options.c:952
char ** allocated
Definition options.c:955

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, ERROR_CONFIG, binary_actions_t::has_action, log_debug, log_set_terminal_output(), MODE_DISCOVERY, options_config_destroy(), options_preset_unified(), options_state_init(), options_t_new(), SAFE_FREE, SESSION_STRING_BUFFER_SIZE, SET_ERRNO, binary_actions_t::show_version, and validate_glyph_palette().

Referenced by client_init(), main(), 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 902 of file rcu.c.

902 {
903 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_BOOL, .value.boolean = value});
904}
@ OPTIONS_VALUE_BOOL

References OPTIONS_VALUE_BOOL.

Referenced by EMSCRIPTEN_BINDINGS(), and session_capture_toggle_media().

◆ 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 905 of file rcu.c.

905 {
906 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_DOUBLE, .value.number = value});
907}
@ 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:57
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 894 of file rcu.c.

894 {
895 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_INT, .value.integer = value});
896}
@ 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 908 of file rcu.c.

908 {
909 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_STRING, .value.string = value});
910}
@ 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 547 of file options.c.

547 {
548 options_t opts;
549
550 // Zero-initialize all fields first
551 memset(&opts, 0, sizeof(opts));
552 opts.mode_arg_index = -1;
553
554 // ============================================================================
555 // GENERAL CATEGORY - General-purpose options
556 // ============================================================================
557 opts.help = OPT_HELP_DEFAULT;
563 opts.fps_explicitly_set = false;
567
568 // ============================================================================
569 // LOGGING CATEGORY - Binary-level logging and output control options
570 // ============================================================================
571 // log_file is mode-dependent at startup and intentionally left empty here
576 SAFE_STRNCPY(opts.otel_enabled_telemetry, "traces,logs,metrics", sizeof(opts.otel_enabled_telemetry));
577 opts.otel_realtime_sample_rate = 0.01;
579 opts.otel_metrics_interval = 10000;
580 SAFE_STRNCPY(opts.otel_log_level, "info", sizeof(opts.otel_log_level));
581 opts.otel_timeout = 5000;
582 opts.otel_queue_capacity = 4096;
583 if (platform_systemd_is_managed()) {
584 opts.splash_screen = false;
585 opts.status_screen = false;
586 opts.no_check_update = true;
587 SAFE_STRNCPY(opts.log_file, "/dev/null", sizeof(opts.log_file));
588 opts.otel_endpoint[0] = '\0';
589 }
590 opts.grep_pattern[0] = '\0'; // Explicitly ensure grep_pattern is empty
591 opts.json = OPT_JSON_DEFAULT;
593 // log_template and log_format are set by get_default_log_template()
594
595 // ============================================================================
596 // TERMINAL CATEGORY - Terminal display options
597 // ============================================================================
607 if (platform_systemd_is_managed())
609
610 // ============================================================================
611 // DISPLAY CATEGORY - Display and rendering options
612 // ============================================================================
616 opts.stabilize = true;
617 opts.stabilize_explicit = false;
619 // palette_custom is already zeroed by memset
622 opts.fps = OPT_FPS_DEFAULT;
626 opts.waveform = false;
627 opts.fft = false;
628 SAFE_STRNCPY(opts.fft_scale, "-62:-6", sizeof(opts.fft_scale));
631
632 // ============================================================================
633 // WEBCAM CATEGORY - Webcam and capture device options
634 // ============================================================================
638
639 // ============================================================================
640 // MEDIA CATEGORY - Media file streaming and playback options
641 // ============================================================================
642 // media_file is already zeroed by memset
643 // media_url is already zeroed by memset
648 // yt_dlp_options is already zeroed by memset
649
650 // Render-to-file options
651 // render_file is already zeroed by memset
653 // render_font is already zeroed by memset
655
656 // ============================================================================
657 // NETWORK CATEGORY - Network connectivity and protocol options
658 // ============================================================================
659 SAFE_STRNCPY(opts.address, OPT_ADDRESS_DEFAULT, sizeof(opts.address));
667 // Discovery Service (ACDS) Options
675 // discovery_service_key is already zeroed by memset
676 opts.discovery_database_path[0] = '\0'; // Explicitly ensure discovery_database_path is empty
677 // LAN Discovery & WebRTC Options
681 // WebRTC Mode & Strategy Options
686 opts.webrtc_relay_only = false;
695 // turn_secret is already zeroed by memset
696
697 // ============================================================================
698 // AUDIO CATEGORY - Audio capture, playback and processing options
699 // ============================================================================
700 opts.audio_fft_size = 1024;
701 opts.test_audio = false;
702 opts.audio_spectral = true;
703 opts.audio_spectral_mixer = false;
704 opts.audio_spectral_gate = true;
708 opts.microphone_channels = 1;
709 opts.microphone_channel = 0;
717
718 // ============================================================================
719 // SECURITY CATEGORY - Encryption and authentication options
720 // ============================================================================
722 // encrypt_key is already zeroed by memset
723 // password is already zeroed by memset
724 // encrypt_keyfile is already zeroed by memset
727 // server_key is already zeroed by memset
728 // client_keys is already zeroed by memset
729 // identity_keys array is already zeroed by memset
730 opts.num_identity_keys = 0;
733
734 // ============================================================================
735 // CONFIGURATION CATEGORY - Application configuration options
736 // ============================================================================
737 // config_file is already zeroed by memset
738
739 // ============================================================================
740 // DATABASE CATEGORY - Database and persistent storage options
741 // ============================================================================
742 // discovery_database_path is already zeroed by memset (set above in NETWORK)
743
744 // ============================================================================
745 // Internal/System Fields
746 // ============================================================================
747 // session_string is already zeroed by memset
748 // detected_mode is already zeroed by memset
749
750 return opts;
751}
#define OPT_STRIP_ANSI_DEFAULT
Default strip ANSI escape sequences flag.
Definition options.h:451
#define OPT_WEBRTC_SKIP_STUN_DEFAULT
Default WebRTC skip STUN flag (false = use STUN).
Definition options.h:678
#define OPT_ACDS_EXPOSE_IP_DEFAULT
Default ACDS expose IP flag (false = private by default).
Definition options.h:600
#define OPT_ENDPOINT_DISCOVERY_SERVICE
Default discovery service endpoint (what to connect to by default).
Definition options.h:560
#define OPT_COLOR_DEFAULT
Default color setting (COLOR_SETTING_AUTO = smart detection).
Definition options.h:454
#define OPT_NO_AUDIO_MIXER_DEFAULT
Default no audio mixer flag (false = enable mixer).
Definition options.h:518
#define OPT_FLIP_Y_DEFAULT
Default vertical flip state (false = no vertical flip).
Definition options.h:505
#define OPT_SHOW_CAPABILITIES_DEFAULT
Default show terminal capabilities flag.
Definition options.h:445
#define OPT_NO_ENCRYPT_DEFAULT
Default no encrypt flag (false = allow encryption).
Definition options.h:739
#define OPT_QUIET_DEFAULT
Default quiet mode flag (false = logging enabled).
Definition options.h:348
#define OPT_MICROPHONE_INDEX_DEFAULT
Default microphone device index (-1 means system default).
Definition options.h:711
#define OPT_TURN_SERVERS_DEFAULT
Default TURN server URLs (comma-separated).
Definition options.h:664
#define OPT_ENCODE_AUDIO_DEFAULT
Default audio encoding state (true = Opus encoding enabled).
Definition options.h:729
#define OPT_COLOR_MODE_DEFAULT
Default color mode (auto-detect terminal capabilities).
Definition options.h:433
#define OPT_PALETTE_TYPE_DEFAULT
Default palette type (standard ASCII art).
Definition options.h:467
#define OPT_RECONNECT_ATTEMPTS_DEFAULT
Default reconnect attempts (-1 means auto/infinite).
Definition options.h:582
#define OPT_SPEAKERS_VOLUME_DEFAULT
Default speakers volume (1.0 = normal volume).
Definition options.h:720
#define OPT_NO_AUTH_DEFAULT
Default no auth flag (false = allow authentication).
Definition options.h:742
#define OPT_TEST_PATTERN_DEFAULT
Default test pattern mode (false = use actual webcam).
Definition options.h:515
#define OPT_OTEL_ENDPOINT_DEFAULT
Debug and Dev builds export to the local Spaniel Compose collector.
Definition options.h:354
#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT
Default WebRTC ICE gathering timeout in milliseconds (10 seconds).
Definition options.h:687
#define OPT_COMPRESSION_LEVEL_DEFAULT
Default compression level (1-9).
Definition options.h:585
#define OPT_ENCRYPT_ENABLED_DEFAULT
Default encrypt enabled flag (true = encryption required).
Definition options.h:736
#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT
Default require-server-identity setting for ACDS.
Definition options.h:606
#define OPT_ENABLE_KEEPAWAKE_DEFAULT
Default keep-awake (prevent system sleep) flag (false = normal system sleep).
Definition options.h:335
#define OPT_RENDER_MODE_DEFAULT
Default render mode (foreground characters only).
Definition options.h:464
#define OPT_ACDS_PORT_INT_DEFAULT
Default ACDS discovery service port (integer).
Definition options.h:594
#define OPT_AUDIO_ENABLED_DEFAULT
Default audio enabled flag (true = audio enabled by default).
Definition options.h:703
#define OPT_MATRIX_RAIN_DEFAULT
Default Matrix rain effect flag (false = disabled).
Definition options.h:496
#define OPT_FORCE_UTF8_DEFAULT
Default force UTF-8 support setting (auto-detect).
Definition options.h:448
#define OPT_STUN_SERVERS_DEFAULT
Default STUN server URLs (comma-separated).
Definition options.h:661
#define OPT_HELP_DEFAULT
Default help flag (false = don't show help).
Definition options.h:317
#define OPT_ADDRESS6_DEFAULT
Default IPv6 server address.
Definition options.h:544
#define OPT_RENDER_FONT_SIZE_DEFAULT
Definition options.h:775
#define OPT_WEBRTC_RECONNECT_ATTEMPTS_DEFAULT
Default WebRTC reconnection attempts (3 = try initial + 3 retries).
Definition options.h:690
#define OPT_SPLASH_DEFAULT
Default splash screen flag (true = show splash, false = hide splash).
Definition options.h:323
#define OPT_RENDER_THEME_DEFAULT
Definition options.h:773
#define OPT_MEDIA_FROM_STDIN_DEFAULT
Default media from stdin flag (false = not reading from stdin).
Definition options.h:528
#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT
Default audio analysis enabled flag.
Definition options.h:723
#define OPT_VERSION_DEFAULT
Default version flag (false = don't show version).
Definition options.h:320
#define OPT_ACDS_DEFAULT
Default ACDS registration flag (false = disabled).
Definition options.h:591
#define OPT_NO_COMPRESS_DEFAULT
Default no compression flag (false = enable compression).
Definition options.h:588
#define OPT_AUTO_HEIGHT_DEFAULT
Default auto-detect height flag (true = auto-detect from terminal).
Definition options.h:430
#define ASCII_RENDERER_DEFAULT
Definition options.h:967
#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT
Default require client verify flag (false = not required).
Definition options.h:748
#define OPT_AUDIO_NO_PLAYBACK_DEFAULT
Default audio playback flag (false = enable playback).
Definition options.h:726
#define OPT_PAUSE_DEFAULT
Default pause media flag (false = play immediately).
Definition options.h:534
#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT
Default require server verify flag (false = not required).
Definition options.h:745
#define OPT_NO_MDNS_ADVERTISE_DEFAULT
Default no mDNS advertise flag (false = advertise enabled).
Definition options.h:615
#define OPT_AUDIO_SOURCE_DEFAULT
Visualize all available sources by default.
Definition options.h:706
#define OPT_STATUS_SCREEN_EXPLICITLY_SET_DEFAULT
Default status screen explicitly set flag (false = use default status screen setting).
Definition options.h:332
#define OPT_COLOR_FILTER_DEFAULT
Default color filter (none - no filtering).
Definition options.h:461
#define OPT_WEBCAM_INDEX_DEFAULT
Default webcam device index.
Definition options.h:512
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
Definition options.h:424
#define OPT_SNAPSHOT_MODE_DEFAULT
Default snapshot mode flag (false = continuous).
Definition options.h:479
#define OPT_COLOR_SCHEME_NAME_DEFAULT
Default color scheme name (pastel).
Definition options.h:370
#define OPT_MEDIA_LOOP_DEFAULT
Default loop media flag (false = play once).
Definition options.h:525
#define OPT_NO_CHECK_UPDATE_DEFAULT
Default no-check-update flag (false = check for updates enabled).
Definition options.h:341
#define OPT_STRETCH_DEFAULT
Default allow aspect ratio distortion flag.
Definition options.h:473
#define OPT_STATUS_SCREEN_DEFAULT
Default status screen flag (true = show status, false = hide status).
Definition options.h:329
#define OPT_LAN_DISCOVERY_DEFAULT
Default LAN discovery flag (false = discovery disabled).
Definition options.h:612
#define OPT_AUTO_WIDTH_DEFAULT
Default auto-detect width flag (true = auto-detect from terminal).
Definition options.h:427
#define OPT_JSON_DEFAULT
Default JSON logging flag (false = text output).
Definition options.h:367
#define OPT_ACDS_INSECURE_DEFAULT
Default ACDS insecure mode flag (false = verify server).
Definition options.h:603
#define OPT_FPS_DEFAULT
Default FPS (frames per second).
Definition options.h:476
#define OPT_WEBRTC_DEFAULT
Default WebRTC mode flag (true = P2P WebRTC, false = direct TCP).
Definition options.h:669
#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT
Default require-client-identity setting for ACDS.
Definition options.h:609
#define OPT_DISABLE_KEEPAWAKE_DEFAULT
Default disable keep-awake flag (false = allow system sleep prevention).
Definition options.h:338
#define OPT_ENABLE_UPNP_DEFAULT
Default enable UPnP flag (false = UPnP disabled).
Definition options.h:618
#define OPT_TURN_CREDENTIAL_DEFAULT
Default TURN credential (empty = use ACDS credentials).
Definition options.h:696
#define OPT_WEBRTC_SKIP_HOST_DEFAULT
Default WebRTC skip host candidates flag (false = use host candidates).
Definition options.h:684
#define OPT_VERBOSE_LEVEL_DEFAULT
Default verbose level (0 = not verbose).
Definition options.h:358
#define OPT_SNAPSHOT_DELAY_DEFAULT
Default snapshot delay in seconds.
Definition options.h:492
#define OPT_LOG_LEVEL_DEFAULT
Default log level (LOG_INFO).
Definition options.h:361
#define OPT_MICROPHONE_SENSITIVITY_DEFAULT
Default microphone sensitivity (1.0 = normal volume).
Definition options.h:717
#define OPT_FLIP_X_DEFAULT
Webcam input is mirrored unless an orientation is explicitly selected.
Definition options.h:502
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:567
#define OPT_SPLASH_SCREEN_EXPLICITLY_SET_DEFAULT
Default splash screen explicitly set flag (false = use default splash setting).
Definition options.h:326
#define OPT_MAX_CLIENTS_DEFAULT
Default maximum concurrent clients (server only).
Definition options.h:579
#define OPT_PREFER_WEBRTC_DEFAULT
Default prefer WebRTC flag (false = try direct TCP first).
Definition options.h:672
#define OPT_WEBRTC_DISABLE_TURN_DEFAULT
Default WebRTC disable TURN flag (false = use TURN).
Definition options.h:681
#define OPT_NO_WEBRTC_DEFAULT
Default no WebRTC flag (false = WebRTC enabled).
Definition options.h:675
#define OPT_ADDRESS_DEFAULT
Default server address for client connections.
Definition options.h:541
#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT
Preserve automatic local audio capture selection by default.
Definition options.h:708
#define OPT_PALETTE_CUSTOM_SET_DEFAULT
Default custom palette set flag (false = not set).
Definition options.h:470
#define OPT_TURN_USERNAME_DEFAULT
Default TURN username (empty = use ACDS credentials).
Definition options.h:693
#define OPT_SPEAKERS_INDEX_DEFAULT
Default speakers device index (-1 means system default).
Definition options.h:714
#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT
Default WebSocket port for server mode (integer).
Definition options.h:570
#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT
Default media seek timestamp (start from beginning).
Definition options.h:531
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
Definition options.h:413
bool snapshot_mode
Snapshot mode (one frame and exit).
Definition options.h:1149
int otel_realtime_max_per_second
Definition options.h:1162
bool splash_screen_explicitly_set
True if splash screen was explicitly set by user.
Definition options.h:1238
float speakers_volume
Speaker volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1131
int discovery_port
discovery server port (default: 27225)
Definition options.h:1040
double otel_realtime_sample_rate
Definition options.h:1161
bool webrtc
Enable WebRTC mode for discovery session (default: true, P2P WebRTC).
Definition options.h:1045
audio_capture_source_t audio_capture_source
Local capture/media selection policy.
Definition options.h:1122
bool encrypt_enabled
Enable encryption.
Definition options.h:1178
int otel_metrics_interval
Definition options.h:1163
bool audio_spectral_gate
Definition options.h:1116
bool discovery_expose_ip
ACDS: explicitly allow public IP disclosure without verification (opt-in).
Definition options.h:1200
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:1221
int force_utf8
UTF-8 support setting (auto/true/false).
Definition options.h:1097
int webrtc_ice_timeout_ms
–webrtc-ice-timeout: ICE gathering timeout in milliseconds (default: 10000)
Definition options.h:1213
bool discovery
Enable discovery session registration (default: false).
Definition options.h:1032
bool webrtc_relay_only
–webrtc-relay-only: Require TURN relay candidates
Definition options.h:1210
bool disable_keepawake
Explicitly disable system sleep prevention (allow OS to sleep).
Definition options.h:1173
int otel_queue_capacity
Definition options.h:1165
bool test_audio
Replace microphone capture with a repeating audible test signal.
Definition options.h:1112
int microphone_channel
First zero-based input channel; -1 downmixes all inputs.
Definition options.h:1127
float microphone_sensitivity
Microphone volume multiplier (0.0-1.0, default 1.0).
Definition options.h:1130
int microphone_channels
Selected microphone channels: 1 (speech) or 2 (stereo).
Definition options.h:1126
int compression_level
zstd compression level (1-9)
Definition options.h:1058
bool fps_explicitly_set
True if FPS was explicitly configured by the user.
Definition options.h:1100
bool fft
Replace the video image with a live audio frequency spectrogram.
Definition options.h:1124
bool enable_keepawake
Explicitly enable system sleep prevention.
Definition options.h:1172
char otel_endpoint[256]
Definition options.h:1158
bool show_capabilities
Show terminal capabilities and exit.
Definition options.h:1096
bool no_mdns_advertise
Disable mDNS service advertisement (server only).
Definition options.h:1053
int microphone_index
Microphone device index (-1 = default).
Definition options.h:1128
bool strip_ansi
Strip ANSI escape sequences.
Definition options.h:1154
bool audio_analysis_enabled
Enable audio analysis (debug).
Definition options.h:1132
int websocket_port
WebSocket server port (server/discovery-service only).
Definition options.h:1010
bool pause
Start playback paused (toggle with spacebar).
Definition options.h:1084
audio_source_t audio_source
Visualization source (all/call/mic/media).
Definition options.h:1121
bool json
Enable JSON logging (–json flag).
Definition options.h:1169
char stun_servers[256]
ACDS: Comma-separated list of STUN server URLs.
Definition options.h:1220
bool enable_upnp
Opt-in TCP/WebSocket and WebRTC UDP mapping via –port-forwarding.
Definition options.h:1219
bool webrtc_skip_stun
–webrtc-skip-stun: Skip Stage 2 (STUN), go to TURN
Definition options.h:1209
bool lan_discovery
Enable LAN service discovery via mDNS (client only).
Definition options.h:1052
bool audio_enabled
Enable audio streaming.
Definition options.h:1120
bool no_encrypt
Disable encryption (opt-out).
Definition options.h:1182
bool no_webrtc
–no-webrtc: Disable WebRTC, use Direct TCP only
Definition options.h:1207
bool matrix_rain
Matrix digital rain effect (false = disabled).
Definition options.h:1152
bool webrtc_disable_turn
–webrtc-disable-turn: Disable Stage 3 (TURN), use STUN only
Definition options.h:1211
bool audio_no_playback
Disable speaker playback (debug).
Definition options.h:1133
bool auto_height
Auto-detect height from terminal.
Definition options.h:999
log_level_t log_level
Log level threshold.
Definition options.h:1167
char turn_credential[256]
ACDS: Credential/password for TURN authentication.
Definition options.h:1223
bool require_server_identity
ACDS: require servers to provide signed Ed25519 identity.
Definition options.h:1196
int audio_fft_size
Definition options.h:1119
bool status_screen
Show status screen (default: true = show, use –no-status-screen to hide).
Definition options.h:1239
char otel_log_level[256]
Definition options.h:1157
int max_clients
Maximum concurrent clients (server only).
Definition options.h:1025
bool palette_custom_set
True if custom palette was set.
Definition options.h:1231
bool no_auth
Disable authentication layer (–no-auth).
Definition options.h:1183
terminal_render_mode_t render_mode
Render mode (foreground/background/half-block).
Definition options.h:1095
bool splash_screen
Show splash screen (default: true = show, use –no-splash-screen to hide).
Definition options.h:1237
char discovery_database_path[256]
~/.ascii-chat/discovery.db)
Definition options.h:1046
bool no_audio_mixer
Disable audio mixer (debug).
Definition options.h:1073
bool audio_spectral_mixer
Explicit post-mix processing; disabled by default.
Definition options.h:1115
bool webrtc_skip_host
–webrtc-skip-host: Skip host candidates, force STUN/TURN only
Definition options.h:1212
bool version
Show version information.
Definition options.h:990
int webcam_index
Webcam device index (0 = first).
Definition options.h:1070
bool status_screen_explicitly_set
True if status_screen was explicitly set by user.
Definition options.h:1240
bool stabilize
Reduce frame-to-frame character flicker.
Definition options.h:1138
bool no_compress
Disable compression entirely.
Definition options.h:1059
int webrtc_reconnect_attempts
–webrtc-reconnect-attempts: Number of retry attempts (default: 3)
Definition options.h:1214
char address6[256]
IPv6 bind address (server only).
Definition options.h:1008
int speakers_index
Speakers device index (-1 = default).
Definition options.h:1129
color_filter_t color_filter
Monochromatic color filter (none/black/white/green/etc).
Definition options.h:1093
bool help
Show help message.
Definition options.h:989
bool prefer_webrtc
–prefer-webrtc: Try WebRTC before Direct TCP
Definition options.h:1206
bool quiet
Quiet mode (suppress logs).
Definition options.h:1147
double snapshot_delay
Snapshot delay in seconds.
Definition options.h:1150
bool stabilize_explicit
Runtime preference was explicitly changed.
Definition options.h:1139
bool audio_spectral
Definition options.h:1114
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1099
bool stretch
Allow aspect ratio distortion.
Definition options.h:1141
ascii_renderer_t renderer
Character selection algorithm.
Definition options.h:1140
bool waveform
Replace the video image with a live audio waveform.
Definition options.h:1123
int reconnect_attempts
Number of reconnection attempts (-1=infinite, 0=none).
Definition options.h:1065
bool test_pattern
Use test pattern instead of webcam.
Definition options.h:1071
char fft_scale[32]
Amplitude scale for the FFT visualization.
Definition options.h:1125
bool media_from_stdin
Reading from stdin (detected from "--file -").
Definition options.h:1082
bool require_client_verify
Client: only connect to servers whose identity was verified by ACDS.
Definition options.h:1199
char discovery_server[256]
discovery server address (default: 127.0.0.1)
Definition options.h:1033
int mode_arg_index
Explicit mode token in original argv, or -1 for implicit discovery/session strings.
Definition options.h:984
bool require_server_verify
Server: only accept clients who verified via ACDS.
Definition options.h:1198
palette_type_t palette_type
Selected palette type.
Definition options.h:1229
bool flip_y
Flip video vertically (Y-axis).
Definition options.h:1106
char color_scheme_name[64]
Color scheme name (e.g., "pastel", "nord").
Definition options.h:1094
bool media_loop
Loop media file playback.
Definition options.h:1081
bool require_client_identity
ACDS: require clients to provide signed Ed25519 identity.
Definition options.h:1197
bool discovery_insecure
ACDS: skip server key verification (MITM-vulnerable, requires explicit opt-in).
Definition options.h:1201
bool no_check_update
Disable automatic update checks (default: false = checks enabled).
Definition options.h:1241
bool encode_audio
Enable Opus audio encoding.
Definition options.h:1060
int render_theme
0=dark 1=light 2=auto
Definition options.h:1262
char otel_enabled_telemetry[256]
Definition options.h:1160
int color
Color setting (COLOR_SETTING_AUTO/TRUE/FALSE).
Definition options.h:1091
char turn_username[256]
ACDS: Username for TURN authentication.
Definition options.h:1222
char log_file[256]
Log file path.
Definition options.h:1166
unsigned short int verbose_level
Verbosity level (stackable -V).
Definition options.h:1148
char address[256]
Server address (client) or bind address (server).
Definition options.h:1007
bool flip_x
Effective horizontal orientation.
Definition options.h:1103
char grep_pattern[256]
PCRE2 regex for log filtering.
Definition options.h:1168
bool auto_width
Auto-detect width from terminal.
Definition options.h:998
double render_font_size
Font size in points (0 selects an automatic size).
Definition options.h:1264
double media_seek_timestamp
Seek to timestamp in seconds before playback.
Definition options.h:1083

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::fps_explicitly_set, 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_SPLASH_SCREEN_EXPLICITLY_SET_DEFAULT, OPT_STATUS_SCREEN_DEFAULT, OPT_STATUS_SCREEN_EXPLICITLY_SET_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_DEFAULT, OPT_WEBRTC_DISABLE_TURN_DEFAULT, OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT, OPT_WEBRTC_RECONNECT_ATTEMPTS_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::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::splash_screen_explicitly_set, options_state::stabilize, options_state::stabilize_explicit, options_state::status_screen, options_state::status_screen_explicitly_set, 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, options_state::webrtc_disable_turn, options_state::webrtc_ice_timeout_ms, options_state::webrtc_reconnect_attempts, 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 535 of file rcu.c.

535 {
536 static terminal_options_t settings;
537 const options_t *options = options_get();
538 settings = (terminal_options_t){
539 .color = (terminal_color_setting_t)options->color,
540 .color_mode = options->color_mode,
541 .force_utf8 = (terminal_utf8_setting_t)options->force_utf8,
542 .render_mode = options->render_mode,
543 .width = options->width,
544 .height = options->height,
545 .fps = options->fps,
546 .snapshot_mode = options->snapshot_mode,
547 };
548 return &settings;
549}

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 736 of file manpage.c.

736 {
737 if (!filepath || !num_sections) {
738 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
739 return NULL;
740 }
741
742 FILE *f = platform_fopen("file_stream", filepath, "r");
743 if (!f) {
744 SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open file: %s", filepath);
745 return NULL;
746 }
747
748 parsed_section_t *sections = NULL;
749 asciichat_error_t err = manpage_parser_parse_file(f, &sections, num_sections);
750 fclose(f);
751
752 if (err != ASCIICHAT_OK) {
753 return NULL;
754 }
755
756 return sections;
757}
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:44

References ASCIICHAT_OK, ERROR_CONFIG, ERROR_INVALID_PARAM, manpage_parser_parse_file(), 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.

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

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

Example:

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

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

177 {
178 if (!str || *str == '\0') {
179 return INT_MIN; // Error: NULL or empty string
180 }
181
182 int32_t result = 0;
183 // Use safe parsing utility with full int32 range validation
184 if (parse_int32(str, &result, INT_MIN, INT_MAX) != ASCIICHAT_OK) {
185 return INT_MIN; // Error: invalid input or out of range
186 }
187
188 return (int)result;
189}
asciichat_error_t parse_int32(const char *str, int32_t *out_value, int32_t min_value, int32_t max_value)
Parse signed 32-bit integer with range validation.

References ASCIICHAT_OK, and parse_int32().

Referenced by validate_fps_opt(), validate_opt_device_index(), validate_opt_reconnect(), and validate_positive_int_opt().

◆ 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 for full-height mode.
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

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

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

Behavior:

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

Example:

// During options_init():
}
bool auto_height
bool auto_width

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

620 {
621 if (!opts) {
622 return;
623 }
624
625 unsigned short int term_width, term_height;
626
627 // Note: Logging is not available during options_init, so we can't use log_debug here
628 asciichat_error_t result = get_terminal_size(&term_width, &term_height);
629
630 if (result == ASCIICHAT_OK) {
631 // If both dimensions are auto, set height to terminal height and let
632 // aspect_ratio calculate width
633 if (opts->auto_height && opts->auto_width) {
634 opts->height = term_height;
635 opts->width = term_width; // Also set width when both are auto
636 }
637 // If only height is auto, use full terminal height
638 else if (opts->auto_height) {
639 opts->height = term_height;
640 }
641 // If only width is auto, use full terminal width
642 else if (opts->auto_width) {
643 opts->width = term_width;
644 }
645 } else {
646 // Terminal size detection failed, but we can still continue with defaults
647 }
648}

References ASCIICHAT_OK, options_state::auto_height, options_state::auto_width, 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 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)

Update dimensions to match current terminal size.

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

Behavior:

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

Example:

// After logging initialization:
log_info("Terminal dimensions: %dx%d", opt_width, opt_height);

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

650 {
651 if (!opts) {
652 return;
653 }
654
655 unsigned short int term_width, term_height;
656 // Get current terminal size (get_terminal_size already handles ioctl first, then $COLUMNS/$LINES fallback)
657 asciichat_error_t terminal_result = get_terminal_size(&term_width, &term_height);
658 if (terminal_result == ASCIICHAT_OK) {
659 // Use INFO level so this is visible without -v flag (important for debugging dimension issues)
660 log_dev("Terminal size detected: %ux%u (auto_width=%d, auto_height=%d)", term_width, term_height, opts->auto_width,
661 opts->auto_height);
662 if (opts->auto_width) {
663 opts->width = term_width;
664 log_debug("Auto-width: set width to %u", opts->width);
665 }
666 if (opts->auto_height) {
667 opts->height = term_height;
668 log_debug("Auto-height: set height to %u", opts->height);
669 }
670 log_debug("Final dimensions: %ux%u", opts->width, opts->height);
671 } else {
672 // Terminal detection failed - keep the default values set in options_init()
673 log_warn("TERMINAL_DETECT_FAIL: Could not detect terminal size, using defaults: %ux%u", opts->width, opts->height);
674 }
675}
#define log_warn(...)
Log a WARN message.
Definition log/log.h:621
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:581

References ASCIICHAT_OK, options_state::auto_height, options_state::auto_width, options_state::height, log_debug, 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 701 of file options/common.c.

701 {
702 if (!desc) {
703 return;
704 }
705
706 // Find mode metadata
707 const mode_metadata_t *metadata = NULL;
708 for (size_t i = 0; i < sizeof(mode_info) / sizeof(mode_info[0]); i++) {
709 if (mode_info[i].mode == mode) {
710 metadata = &mode_info[i];
711 break;
712 }
713 }
714
715 if (!metadata) {
716 (void)fprintf(desc, "error: Unknown mode\n");
717 return;
718 }
719
720 // Get unified config
721 const options_config_t *config = options_preset_unified(metadata->program_name, metadata->description);
722 if (!config) {
723 (void)fprintf(desc, "Error: Failed to create options config\n");
724 return;
725 }
726
727 options_print_help_for_mode(config, mode, metadata->program_name, metadata->description, desc);
729}
void options_print_help_for_mode(const options_config_t *config, asciichat_mode_t mode, const char *program_name, const char *description, FILE *desc)
Print help for a specific mode or binary level (unified function).
Mode metadata for usage display.
const char * program_name
Program name shown in usage.
const char * description
One-line description of mode.

References mode_metadata_t::description, options_config_destroy(), options_preset_unified(), options_print_help_for_mode(), and mode_metadata_t::program_name.

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:53
const char * chars
Character sequence (ordered from dark to light).
Definition palette.h:128
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:104
bool ascii_glyph_palette_supported(const char *palette)
bool palette_explicit
Palette explicitly selected.
Definition options.h:1232
char palette_custom[256]
Custom palette characters.
Definition options.h:1230
Validated luminance palette used to turn brightness into characters.
Definition palette.h:124

References ascii_glyph_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 151 of file validation.c.

151 {
152 if (!value_str) {
153 if (error_msg) {
154 SAFE_SNPRINTF(error_msg, error_msg_size, "Color mode value is required");
155 }
156 return -1;
157 }
158
159 if (strcmp(value_str, OPT_VALUE_AUTO) == 0) {
160 return COLOR_MODE_AUTO;
161 }
162 if (strcmp(value_str, OPT_COLOR_MODE_NONE) == 0 || strcmp(value_str, OPT_COLOR_MODE_MONO) == 0) {
163 return COLOR_MODE_NONE;
164 }
165 if (strcmp(value_str, OPT_COLOR_MODE_16) == 0 || strcmp(value_str, "16color") == 0) {
166 return COLOR_MODE_16_COLOR;
167 }
168 if (strcmp(value_str, OPT_COLOR_MODE_256) == 0 || strcmp(value_str, "256color") == 0) {
170 }
171 if (strcmp(value_str, OPT_COLOR_MODE_TRUECOLOR) == 0 || strcmp(value_str, "24bit") == 0) {
173 }
174 if (error_msg) {
175 SAFE_SNPRINTF(error_msg, error_msg_size,
176 "Invalid color mode '%s'. Valid modes: auto, none, mono, 16, 256, truecolor", value_str);
177 }
178 return -1;
179}
#define OPT_COLOR_MODE_256
Definition enums.h:101
#define OPT_COLOR_MODE_NONE
Definition enums.h:98
#define OPT_VALUE_AUTO
Definition enums.h:77
#define OPT_COLOR_MODE_TRUECOLOR
Definition enums.h:102
#define OPT_COLOR_MODE_MONO
Definition enums.h:99
#define OPT_COLOR_MODE_16
Definition enums.h:100
#define SAFE_SNPRINTF(buffer, buffer_size,...)
Definition common.h:507
#define COLOR_MODE_16_COLOR
16-color mode (full name)
Definition options.h:225
#define COLOR_MODE_256_COLOR
256-color mode (full name)
Definition options.h:227
#define COLOR_MODE_TRUECOLOR
24-bit truecolor mode
Definition options.h:228
#define COLOR_MODE_AUTO
Backward compatibility aliases for color mode enum values.
Definition options.h:222
#define COLOR_MODE_NONE
Monochrome mode.
Definition options.h:223

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 400 of file validation.c.

400 {
401 int result = validate_int_range(value_str, 1, 9, "Compression level", error_msg, error_msg_size);
402 return (result == INT_MIN) ? -1 : result;
403}

◆ 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 469 of file validation.c.

469 {
470 if (!value_str || strlen(value_str) == 0) {
471 if (error_msg) {
472 SAFE_SNPRINTF(error_msg, error_msg_size, "Device index value is required");
473 }
474 return INT_MIN;
475 }
476
477 int index = strtoint_safe(value_str);
478 if (index == INT_MIN) {
479 if (error_msg) {
480 SAFE_SNPRINTF(error_msg, error_msg_size,
481 "Invalid device index '%s'. Must be -1 (default) or a non-negative integer.", value_str);
482 }
483 return INT_MIN;
484 }
485
486 // -1 is valid (system default), otherwise must be >= 0
487 if (index < -1) {
488 if (error_msg) {
489 SAFE_SNPRINTF(error_msg, error_msg_size,
490 "Invalid device index '%d'. Must be -1 (default) or a non-negative integer.", index);
491 }
492 return INT_MIN;
493 }
494 return index;
495}

References index, SAFE_SNPRINTF, and strtoint_safe().

Referenced by validate_webcam_index().

◆ 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 333 of file validation.c.

333 {
334 if (!value_str || strlen(value_str) == 0) {
335 if (error_msg) {
336 SAFE_SNPRINTF(error_msg, error_msg_size, "Value is required");
337 }
338 return -1.0f;
339 }
340
341 char *endptr;
342 float val = strtof(value_str, &endptr);
343 if (*endptr != '\0' || value_str == endptr || !isfinite(val)) {
344 if (error_msg) {
345 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid float value '%s'. Must be a number.", value_str);
346 }
347 return -1.0f;
348 }
349 if (val < 0.0f) {
350 if (error_msg) {
351 SAFE_SNPRINTF(error_msg, error_msg_size, "Value must be non-negative (got %.2f)", val);
352 }
353 return -1.0f;
354 }
355 return val;
356}

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 409 of file validation.c.

409 {
410 int result = validate_int_range(value_str, 0, 144, "FPS", error_msg, error_msg_size);
411 return (result == INT_MIN) ? -1 : result;
412}

◆ 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 281 of file validation.c.

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

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

◆ validate_opt_log_level()

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 247 of file validation.c.

247 {
248 if (!value_str) {
249 if (error_msg) {
250 SAFE_SNPRINTF(error_msg, error_msg_size, "Log level value is required");
251 }
252 return -1;
253 }
254
255 if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_DEV) == 0) {
256 return LOG_DEV;
257 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_DEBUG) == 0) {
258 return LOG_DEBUG;
259 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_INFO) == 0) {
260 return LOG_INFO;
261 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_WARN) == 0) {
262 return LOG_WARN;
263 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_ERROR) == 0) {
264 return LOG_ERROR;
265 } else if (platform_strcasecmp(value_str, OPT_LOG_LEVEL_FATAL) == 0) {
266 return LOG_FATAL;
267 } else {
268 if (error_msg) {
269 SAFE_SNPRINTF(error_msg, error_msg_size,
270 "Invalid log level '%s'. Valid levels: dev, debug, info, warn, error, fatal", value_str);
271 }
272 return -1;
273 }
274}
#define OPT_LOG_LEVEL_DEV
Definition enums.h:89
#define OPT_LOG_LEVEL_FATAL
Definition enums.h:94
#define OPT_LOG_LEVEL_ERROR
Definition enums.h:93
#define OPT_LOG_LEVEL_INFO
Definition enums.h:91
#define OPT_LOG_LEVEL_DEBUG
Definition enums.h:90
#define OPT_LOG_LEVEL_WARN
Definition enums.h:92
#define LOG_DEV
Definition types.h:38
#define LOG_DEBUG
Definition types.h:39
#define LOG_FATAL
Definition types.h:43
#define LOG_ERROR
Definition types.h:42
#define LOG_WARN
Definition types.h:41
#define LOG_INFO
Definition types.h:40

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, 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 391 of file validation.c.

391 {
392 int result = validate_int_range(value_str, 1, MAX_SESSION_PARTICIPANTS, "Max clients", error_msg, error_msg_size);
393 return (result == INT_MIN) ? -1 : result;
394}
#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 142 of file validation.c.

142 {
143 int result = validate_int_range(value_str, 0, INT_MAX, "Value", error_msg, error_msg_size);
144 return (result == INT_MIN) ? -1 : result;
145}

◆ 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 213 of file validation.c.

213 {
214 if (!value_str) {
215 if (error_msg) {
216 SAFE_SNPRINTF(error_msg, error_msg_size, "Palette value is required");
217 }
218 return -1;
219 }
220
221 if (strcmp(value_str, OPT_PALETTE_STANDARD) == 0) {
222 return PALETTE_STANDARD;
223 } else if (strcmp(value_str, OPT_PALETTE_BLOCKS) == 0) {
224 return PALETTE_BLOCKS;
225 } else if (strcmp(value_str, OPT_PALETTE_DIGITAL) == 0) {
226 return PALETTE_DIGITAL;
227 } else if (strcmp(value_str, OPT_PALETTE_MINIMAL) == 0) {
228 return PALETTE_MINIMAL;
229 } else if (strcmp(value_str, OPT_PALETTE_COOL) == 0) {
230 return PALETTE_COOL;
231 } else if (strcmp(value_str, OPT_PALETTE_CUSTOM) == 0) {
232 return PALETTE_CUSTOM;
233 } else {
234 if (error_msg) {
235 SAFE_SNPRINTF(error_msg, error_msg_size,
236 "Invalid palette '%s'. Valid palettes: standard, blocks, digital, minimal, cool, custom",
237 value_str);
238 }
239 return -1;
240 }
241}
#define OPT_PALETTE_CUSTOM
Definition enums.h:125
#define OPT_PALETTE_COOL
Definition enums.h:124
#define OPT_PALETTE_MINIMAL
Definition enums.h:123
#define OPT_PALETTE_BLOCKS
Definition enums.h:121
#define OPT_PALETTE_STANDARD
Definition enums.h:120
#define OPT_PALETTE_DIGITAL
Definition enums.h:122
@ PALETTE_BLOCKS
Unicode block characters: " ░░▒▒▓▓██".
Definition palette.h:96
@ PALETTE_COOL
Ascending blocks: " ▁▂▃▄▅▆▇█".
Definition palette.h:102
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:94
@ PALETTE_DIGITAL
Digital/glitch aesthetic: " -=≡≣▰▱◼".
Definition palette.h:98
@ PALETTE_MINIMAL
Simple ASCII: " .-+*#".
Definition palette.h:100

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 501 of file validation.c.

501 {
502 if (!value_str) {
503 if (error_msg) {
504 SAFE_SNPRINTF(error_msg, error_msg_size, "Password value is required");
505 }
506 return -1;
507 }
508
509 size_t len = strlen(value_str);
510 if (len < 8) {
511 if (error_msg) {
512 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too short (%zu chars). Must be at least 8 characters.", len);
513 }
514 return -1;
515 }
516 if (len > 256) {
517 if (error_msg) {
518 SAFE_SNPRINTF(error_msg, error_msg_size, "Password too long (%zu chars). Must be at most 256 characters.", len);
519 }
520 return -1;
521 }
522
523 // Note: No need to check for embedded null bytes - strlen() already stopped at the first null,
524 // so by definition there are no null bytes within [0, len).
525
526 return 0;
527}

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 88 of file validation.c.

88 {
89 if (!value_str || strlen(value_str) == 0) {
90 if (error_msg) {
91 SAFE_SNPRINTF(error_msg, error_msg_size, "Port value is required");
92 }
93 return -1;
94 }
95
96 // Use safe integer parsing with range validation
97 uint16_t port_num;
98 if (parse_port(value_str, &port_num) != ASCIICHAT_OK) {
99 if (error_msg) {
100 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid port value '%s'. Port must be a number between 1 and 65535.",
101 value_str);
102 }
103 return -1;
104 }
105 return 0;
106}
unsigned short uint16_t
Definition common.h:61
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 133 of file validation.c.

133 {
134 int result = validate_int_range(value_str, 1, INT_MAX, "Value", error_msg, error_msg_size);
135 return (result == INT_MIN) ? -1 : result;
136}

◆ 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 422 of file validation.c.

422 {
423 if (!value_str || strlen(value_str) == 0) {
424 if (error_msg) {
425 SAFE_SNPRINTF(error_msg, error_msg_size, "Reconnect value is required");
426 }
427 return INT_MIN;
428 }
429
430 // Check for string values first
431 if (platform_strcasecmp(value_str, "off") == 0) {
432 return 0; // No retries
433 }
434 if (platform_strcasecmp(value_str, OPT_VALUE_AUTO) == 0) {
435 return -1; // Unlimited retries
436 }
437
438 // Parse as integer
439 int val = strtoint_safe(value_str);
440 if (val == INT_MIN) {
441 if (error_msg) {
442 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect value '%s'. Use 'off', 'auto', or a number 0-999.",
443 value_str);
444 }
445 return INT_MIN;
446 }
447
448 // 0 means off, -1 means auto, 1-999 is valid range
449 if (val == 0) {
450 return 0; // No retries
451 }
452 if (val == -1) {
453 return -1; // Unlimited retries
454 }
455 if (val < 1 || val > 999) {
456 if (error_msg) {
457 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid reconnect count '%s'. Must be 'off', 'auto', or 1-999.",
458 value_str);
459 }
460 return INT_MIN;
461 }
462 return val;
463}

References OPT_VALUE_AUTO, 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 185 of file validation.c.

185 {
186 if (!value_str) {
187 if (error_msg) {
188 SAFE_SNPRINTF(error_msg, error_msg_size, "Render mode value is required");
189 }
190 return -1;
191 }
192
193 if (strcmp(value_str, OPT_RENDER_MODE_FOREGROUND) == 0 || strcmp(value_str, OPT_RENDER_MODE_FG) == 0) {
194 return RENDER_MODE_FOREGROUND;
195 }
196 if (strcmp(value_str, OPT_RENDER_MODE_BACKGROUND) == 0 || strcmp(value_str, OPT_RENDER_MODE_BG) == 0) {
197 return RENDER_MODE_BACKGROUND;
198 }
199 if (strcmp(value_str, OPT_RENDER_MODE_HALF_BLOCK) == 0 || strcmp(value_str, "halfblock") == 0) {
200 return RENDER_MODE_HALF_BLOCK;
201 }
202 if (error_msg) {
203 SAFE_SNPRINTF(error_msg, error_msg_size,
204 "Invalid render mode '%s'. Valid modes: foreground, background, half-block", value_str);
205 }
206 return -1;
207}
#define OPT_RENDER_MODE_BG
Definition enums.h:131
#define OPT_RENDER_MODE_FOREGROUND
Definition enums.h:128
#define OPT_RENDER_MODE_HALF_BLOCK
Definition enums.h:132
#define OPT_RENDER_MODE_FG
Definition enums.h:129
#define OPT_RENDER_MODE_BACKGROUND
Definition enums.h:130

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 362 of file validation.c.

362 {
363 if (!value_str || strlen(value_str) == 0) {
364 if (error_msg) {
365 SAFE_SNPRINTF(error_msg, error_msg_size, "Volume value is required");
366 }
367 return -1.0f;
368 }
369
370 char *endptr;
371 float val = strtof(value_str, &endptr);
372 if (*endptr != '\0' || value_str == endptr || !isfinite(val)) {
373 if (error_msg) {
374 SAFE_SNPRINTF(error_msg, error_msg_size, "Invalid volume value '%s'. Must be a number.", value_str);
375 }
376 return -1.0f;
377 }
378 if (val < 0.0f || val > 1.0f) {
379 if (error_msg) {
380 SAFE_SNPRINTF(error_msg, error_msg_size, "Volume must be between 0.0 and 1.0 (got %.2f)", val);
381 }
382 return -1.0f;
383 }
384 return val;
385}

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 391 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 392 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 390 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 389 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 385 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 384 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 383 of file options/common.c.

Referenced by server_main().