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

⚙️ Code shared throughout the library More...

Files

file  common.c
 🔧 Core utilities: memory management, safe macros, and cross-platform helpers
file  fps.c
 ⏱️ FPS tracking utility implementation (nanosecond-precision)
file  common.h
 ⚙️ Common definitions, error codes, macros, and types shared throughout the application
file  embedded_resources.h
 Embedded resource management for production builds.
file  fps.h
 ⏱️ FPS tracking utility for monitoring frame throughput across all threads

Data Structures

struct  fps_t
 Counters and timestamps used to calculate and report frame rate. More...

Macros

#define ASCII_CHAT_APP_NAME   "ascii-chat"
 Application name for key comments ("ascii-chat").
#define NONSTRING   /* nothing */
#define FATAL(code, ...)
 Exit with error code and custom message, with stack trace in debug builds.
#define RUN_BURST_AND_THROTTLE(burst_ns, throttle_ns, code_block)
 Return the minimum of two values.
#define ALLOC_MALLOC(size)
#define ALLOC_CALLOC(count, size)
#define ALLOC_REALLOC(ptr, size)
#define ALLOC_FREE(ptr)
#define ASCIICHAT_CHECK_AND_LOG(expr, ok_value, msg, ...)
 Check result and log error if operation failed.

Typedefs

typedef unsigned char uint8_t
typedef unsigned short uint16_t
typedef unsigned int uint32_t
typedef unsigned long long uint64_t

Functions

_Noreturn void asciichat_fatal_with_context (asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)
asciichat_error_t asciichat_shared_init (const char *log_file, bool is_client, bool quiet_startup)
 Initialize common subsystems shared by client and server.
void asciichat_shared_destroy (void)
 Clean up shared library subsystems.
void fps_init (fps_t *tracker, int expected_fps, const char *name)
 Initialize FPS tracker.
void fps_init_with_interval (fps_t *tracker, int expected_fps, const char *name, uint64_t report_interval_ns)
 Initialize FPS tracker with custom report interval.
void fps_frame_ns (fps_t *tracker, uint64_t current_time_ns, const char *context)
 Track a frame and detect lag conditions (nanosecond version - PRIMARY).

Variables

int g_argc
 Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from libplatform's terminal implementation during early execution.
char ** g_argv
 Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from libplatform's terminal implementation during early execution.
bool g_color_flag_passed
 Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initialized, used by terminal_should_color_output().
bool g_color_flag_value
 Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized, used by terminal_should_color_output().

Memory Debugging Macros

#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
#define SAFE_REALLOC(ptr, size, cast)
#define TRACK_ALIGNED_ALLOC(ptr, size, file, line)
#define SAFE_MALLOC_ALIGNED(size, alignment, cast)
#define SAFE_MALLOC_SIMD(size, cast)
#define SAFE_CALLOC_SIMD(count, size, cast)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
#define SAFE_FCLOSE(fp)
#define UNTRACKED_MALLOC(size, cast)
#define UNTRACKED_FREE(ptr)
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_STRDUP(dst, src)
#define SAFE_GETENV(name)
#define SAFE_SSCANF(str, format, ...)
#define SAFE_STRERROR(errnum)
#define SAFE_MEMCPY(dest, dest_size, src, count)
#define SAFE_MEMSET(dest, dest_size, ch, count)
#define SAFE_MEMMOVE(dest, dest_size, src, count)
#define SAFE_STRCPY(dest, dest_size, src)
#define read_u16_unaligned   bytes_read_u16_unaligned
#define read_u32_unaligned   bytes_read_u32_unaligned
#define write_u16_unaligned   bytes_write_u16_unaligned
#define write_u32_unaligned   bytes_write_u32_unaligned
#define safe_size_mul   bytes_safe_size_mul
#define SAFE_SNPRINTF(buffer, buffer_size, ...)
#define SAFE_BUFFER_SIZE(buffer_size, offset)
 Safe buffer size calculation for snprintf.
#define THREAD_CREATE_OR_RETURN(thread, func, arg)
 Create a thread or log error and return.
#define MUTEX_INIT_OR_RETURN(m)
 Initialize a mutex or log error and return.

Detailed Description

⚙️ Code shared throughout the library

This header provides core functionality used throughout ascii-chat:

Note
This header should be included early in other headers as it provides fundamental types and macros that many other modules depend on.

Provides a reusable FPS tracking mechanism for monitoring real-time frame delivery rates across all client threads (data reception, webcam capture, audio capture, keepalive). Tracks frame intervals, detects lag conditions, and generates periodic FPS reports every 7-15 seconds.

USAGE:

fps_t tracker;
fps_init(&tracker, 60, "WEBCAM"); // 60 FPS expected
// In your frame processing loop
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
fps_frame(&tracker, &now, "frame received");
void fps_init(fps_t *tracker, int expected_fps, const char *name)
Initialize FPS tracker.
Definition fps.c:37
Counters and timestamps used to calculate and report frame rate.
Definition fps.h:59

FEATURES:

  • Automatic frame counting and interval measurement
  • Lag detection (when frames arrive late)
  • Periodic FPS report generation (configurable, default 10 seconds)
  • Configurable expected FPS and reporting interval
  • Thread-safe (caller must synchronize if needed)
  • Integrated across all major threads (data reception, webcam, audio, keepalive)
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025
Version
2.0 (Refactored with unified thread tracking)

Macro Definition Documentation

◆ ALLOC_CALLOC

#define ALLOC_CALLOC ( count,
size )

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

Value:
calloc((count), (size))

Definition at line 238 of file include/ascii-chat/common.h.

Referenced by buffer_domain_create().

◆ ALLOC_FREE

#define ALLOC_FREE ( ptr)

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

Value:
free(ptr)

Definition at line 240 of file include/ascii-chat/common.h.

◆ ALLOC_MALLOC

#define ALLOC_MALLOC ( size)

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

Value:
malloc(size)

Definition at line 237 of file include/ascii-chat/common.h.

Referenced by buffer_acquire().

◆ ALLOC_REALLOC

#define ALLOC_REALLOC ( ptr,
size )

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

Value:
realloc((ptr), (size))

Definition at line 239 of file include/ascii-chat/common.h.

◆ ASCII_CHAT_APP_NAME

#define ASCII_CHAT_APP_NAME   "ascii-chat"

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

Application name for key comments ("ascii-chat").

Definition at line 54 of file include/ascii-chat/common.h.

Referenced by add_known_host().

◆ ASCIICHAT_CHECK_AND_LOG

#define ASCIICHAT_CHECK_AND_LOG ( expr,
ok_value,
msg,
... )

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

Value:
do { \
if ((expr) != (ok_value)) { \
log_error(msg, ##__VA_ARGS__); \
return (expr); \
} \
} while (0)

Check result and log error if operation failed.

Consolidates the pattern:

operation_result_t result = operation();
if (result != OK) {
log_error("Operation failed: %d", result);
return result;
}
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604

Usage:

ASCIICHAT_CHECK_AND_LOG(crypto_result = crypto_operation(args),
ASCIICHAT_OK, "Crypto operation failed: %d",
crypto_result);
#define ASCIICHAT_CHECK_AND_LOG(expr, ok_value, msg,...)
Check result and log error if operation failed.
@ ASCIICHAT_OK
Definition error_codes.h:50
action_args_t args

Definition at line 653 of file include/ascii-chat/common.h.

653#define ASCIICHAT_CHECK_AND_LOG(expr, ok_value, msg, ...) \
654 do { \
655 if ((expr) != (ok_value)) { \
656 log_error(msg, ##__VA_ARGS__); \
657 return (expr); \
658 } \
659 } while (0)

◆ FATAL

#define FATAL ( code,
... )

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

Value:
asciichat_fatal_with_context(code, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
void asciichat_fatal_with_context(asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)

Exit with error code and custom message, with stack trace in debug builds.

Parameters
codeError code (asciichat_error_t)
...Custom message format string and arguments (printf-style)
Note
In debug builds, includes file, line, and function information. In release builds, file/line/function are omitted to reduce binary size.
Warning
This macro terminates the program. Use only for unrecoverable errors.
Example:
FATAL(ERROR_NETWORK_BIND, "Cannot bind to port %d", port_number);
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
@ ERROR_NETWORK_BIND
Definition error_codes.h:78

Definition at line 144 of file include/ascii-chat/common.h.

Referenced by asciichat_fatal_with_context(), asciichat_shared_init(), debug_errno_cleanup_thread(), debug_stats_cleanup_thread(), ob_reserve(), and server_main().

◆ MUTEX_INIT_OR_RETURN

#define MUTEX_INIT_OR_RETURN ( m)

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

Value:
do { \
if (mutex_init(&(m)) != 0) { \
log_error("Failed to initialize mutex: %s", #m); \
return -1; \
} \
} while (0)

Initialize a mutex or log error and return.

Parameters
mPointer to mutex_t variable

Handles common pattern: init mutex, log error if failed, then return -1. Example usage:

MUTEX_INIT_OR_RETURN(mutex); // Mutex initialized successfully, continue

Definition at line 560 of file include/ascii-chat/common.h.

560#define MUTEX_INIT_OR_RETURN(m) \
561 do { \
562 if (mutex_init(&(m)) != 0) { \
563 log_error("Failed to initialize mutex: %s", #m); \
564 return -1; \
565 } \
566 } while (0)

◆ NONSTRING

#define NONSTRING   /* nothing */

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

Definition at line 77 of file include/ascii-chat/common.h.

◆ read_u16_unaligned

#define read_u16_unaligned   bytes_read_u16_unaligned

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

Definition at line 503 of file include/ascii-chat/common.h.

◆ read_u32_unaligned

#define read_u32_unaligned   bytes_read_u32_unaligned

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

Definition at line 504 of file include/ascii-chat/common.h.

◆ RUN_BURST_AND_THROTTLE

#define RUN_BURST_AND_THROTTLE ( burst_ns,
throttle_ns,
code_block )

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

Value:
do { \
static uint64_t burst_start = 0; \
uint64_t now = time_get_ns(); \
\
/* First call or timer reset */ \
if (burst_start == 0) { \
burst_start = now; \
code_block; \
} else { \
uint64_t elapsed_ns = now - burst_start; \
\
if (elapsed_ns < (uint64_t)(burst_ns)) { \
/* Within burst window */ \
code_block; \
} else if (elapsed_ns >= (uint64_t)(throttle_ns)) { \
/* Throttle period complete, reset and execute */ \
burst_start = now; \
code_block; \
} \
/* else: in throttle period, do nothing */ \
} \
} while (0)
unsigned long long uint64_t

Return the minimum of two values.

Return the maximum of two values

Calculate the number of elements in an array

Definition at line 192 of file include/ascii-chat/common.h.

192#define RUN_BURST_AND_THROTTLE(burst_ns, throttle_ns, code_block) \
193 do { \
194 static uint64_t burst_start = 0; \
195 uint64_t now = time_get_ns(); \
196 \
197 /* First call or timer reset */ \
198 if (burst_start == 0) { \
199 burst_start = now; \
200 code_block; \
201 } else { \
202 uint64_t elapsed_ns = now - burst_start; \
203 \
204 if (elapsed_ns < (uint64_t)(burst_ns)) { \
205 /* Within burst window */ \
206 code_block; \
207 } else if (elapsed_ns >= (uint64_t)(throttle_ns)) { \
208 /* Throttle period complete, reset and execute */ \
209 burst_start = now; \
210 code_block; \
211 } \
212 /* else: in throttle period, do nothing */ \
213 } \
214 } while (0)

◆ SAFE_BUFFER_SIZE

#define SAFE_BUFFER_SIZE ( buffer_size,
offset )

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

Value:
((offset) < 0 || (size_t)(offset) >= (buffer_size) ? 0 : (buffer_size) - (size_t)(offset))
int buffer_size
Size of circular buffer.
Definition grep.c:69

Safe buffer size calculation for snprintf.

Casts offset to size_t to avoid sign conversion warnings when subtracting from buffer_size. Returns 0 if offset is negative or >= buffer_size (prevents underflow).

Definition at line 520 of file include/ascii-chat/common.h.

◆ SAFE_CALLOC

#define SAFE_CALLOC ( count,
size,
cast )

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

Value:
({ \
cast _ptr = (cast)ALLOC_CALLOC((count), (size)); \
if (!_ptr) { \
FATAL(ERROR_MEMORY, "Memory allocation failed: %zu elements x %zu bytes", (size_t)(count), (size_t)(size)); \
} \
_ptr; \
})
#define ALLOC_CALLOC(count, size)
@ ERROR_MEMORY
Definition error_codes.h:55

Definition at line 282 of file include/ascii-chat/common.h.

282#define SAFE_CALLOC(count, size, cast) \
283 ({ \
284 cast _ptr = (cast)ALLOC_CALLOC((count), (size)); \
285 if (!_ptr) { \
286 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu elements x %zu bytes", (size_t)(count), (size_t)(size)); \
287 } \
288 _ptr; \
289 })

Referenced by acip_async_tcp_transport_create(), acip_outbound_create(), acip_security_init_options(), acip_tcp_transport_create(), acip_websocket_runtime_create(), ascii_create_grid(), ascii_legacy_render(), ascii_legacy_stabilizer_prepare(), ascii_luminance_render(), ascii_stabilizer_prepare(), asciichat_instr_runtime_get(), audio_processor_create(), audio_recording_create_channels(), browser_client_init(), browser_session_create(), browser_transport_create(), client_audio_pipeline_create(), client_connection_create(), crypto_session_create(), digital_rain_init(), discovery_session_create(), face_follow_image_process(), ffmpeg_encoder_create_scaled(), fps_counter_create(), h265_client_context_create(), h265_decoder_create(), h265_server_context_create(), http2_connection_create(), http2_connection_submit_response(), http_renderer_init(), http_renderer_process(), http_renderer_submit(), http_response_retain(), http_server_http3_create(), http_server_init(), levenshtein_n(), mcp_request_parse(), mcp_server_main(), mirror_render_context_create(), mixer_add_source(), mutex_stack_get_all_threads(), nat_upnp_open_protocol(), network_server_create(), options_get_enum_entries(), options_json_parse_value(), options_json_parse_value(), platform_event_listen(), platform_event_loop_create(), platform_event_loop_work(), platform_event_stream_work(), quic_connection_matches_cid(), quic_connection_submit_datagram(), quic_endpoint_open(), quic_udp_endpoint_create(), render_file_create(), render_progress_create(), render_progress_frame(), ringbuffer_create(), session_audio_create(), session_av_state_create(), session_capture_create(), session_consensus_create(), session_display_create(), session_host_create(), session_log_buffer_create(), session_network_capture_create(), session_participant_create(), session_pipeline_create(), simple_frame_swap_create(), spectral_create(), stats_runtime_peer_open(), stats_sampler_create(), stats_scope_create(), term_renderer_create(), terminal_fd_reader_create(), terminal_fd_writer_create(), test_pattern_create(), ui_password_prompt_present(), ui_session_create(), video_encoder_create(), webrtc_create_datachannel(), and webrtc_create_peer_connection().

◆ SAFE_CALLOC_DEFER_FREE

#define SAFE_CALLOC_DEFER_FREE ( name,
count,
size,
cast )

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

Value:
cast name = SAFE_CALLOC(count, size, cast); \
defer(SAFE_FREE(name))
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)

Definition at line 393 of file include/ascii-chat/common.h.

393#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast) \
394 cast name = SAFE_CALLOC(count, size, cast); \
395 defer(SAFE_FREE(name))

Referenced by framebuffer_create(), framebuffer_create_multi(), levenshtein(), packet_queue_create_config(), video_frame_buffer_create(), and webrtc_create_peer_connection().

◆ SAFE_CALLOC_SIMD

#define SAFE_CALLOC_SIMD ( count,
size,
cast )

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

Value:
({ \
size_t total_size = (count) * (size); \
cast _ptr = SAFE_MALLOC_SIMD(total_size, cast); \
memset(_ptr, 0, total_size); \
_ptr; \
})
#define SAFE_MALLOC_SIMD(size, cast)

Definition at line 372 of file include/ascii-chat/common.h.

372#define SAFE_CALLOC_SIMD(count, size, cast) \
373 ({ \
374 size_t total_size = (count) * (size); \
375 cast _ptr = SAFE_MALLOC_SIMD(total_size, cast); \
376 memset(_ptr, 0, total_size); \
377 _ptr; \
378 })

◆ SAFE_FCLOSE

#define SAFE_FCLOSE ( fp)

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

Value:
do { \
if ((fp) != NULL) { \
fclose(fp); \
(fp) = NULL; \
} \
} while (0)

Definition at line 399 of file include/ascii-chat/common.h.

399#define SAFE_FCLOSE(fp) \
400 do { \
401 if ((fp) != NULL) { \
402 fclose(fp); \
403 (fp) = NULL; \
404 } \
405 } while (0)

Referenced by add_known_host(), check_known_host_no_identity(), check_known_host_with_key(), config_create_default(), parse_keys_from_file(), parse_public_key(), remove_known_host(), and update_check_load_cache().

◆ SAFE_FREE

#define SAFE_FREE ( ptr)

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

Value:
do { \
if ((ptr) != NULL) { \
ALLOC_FREE((void *)(ptr)); \
(ptr) = NULL; \
} \
} while (0)

Definition at line 381 of file include/ascii-chat/common.h.

381#define SAFE_FREE(ptr) \
382 do { \
383 if ((ptr) != NULL) { \
384 ALLOC_FREE((void *)(ptr)); \
385 (ptr) = NULL; \
386 } \
387 } while (0)

Referenced by acds_identity_default_path(), acds_server_shutdown(), acds_strings_destroy(), acip_async_tcp_transport_create(), acip_outbound_create(), acip_outbound_destroy(), acip_render_settings_capabilities(), acip_security_cleanup(), acip_settings_request(), acip_settings_send(), acip_tcp_transport_create(), acip_transport_destroy(), acip_websocket_client_transport_create(), acip_websocket_runtime_create(), acip_websocket_runtime_destroy(), add_known_host(), ascii_convert(), ascii_convert_with_buffers_stabilized(), ascii_create_grid(), ascii_frame_finish(), ascii_legacy_render(), ascii_legacy_stabilizer_prepare(), ascii_legacy_stabilizer_reset(), ascii_luminance_render(), ascii_stabilizer_prepare(), ascii_stabilizer_reset(), ascii_write(), asciichat_instr_runtime_destroy(), asciichat_instr_runtime_get(), asciichat_mdns_destroy(), asciichat_mdns_init(), audio_destroy(), audio_free_device_list(), audio_init(), audio_processor_create(), audio_processor_destroy(), audio_recording_destroy(), audio_visualization_render_fft(), audio_visualization_render_waveform(), browser_client_cleanup(), browser_client_settings_receive(), browser_client_settings_values(), browser_session_destroy(), browser_transport_destroy(), buffer_domain_create(), check_known_host_no_identity(), check_known_host_with_key(), client_audio_pipeline_create(), client_audio_pipeline_destroy(), client_audio_render_thread(), client_connection_destroy(), client_settings_receive(), client_settings_values(), client_video_render_thread(), colorscheme_cleanup_compiled(), completions_collect_all_modes_unique(), completions_generate_fish(), completions_generate_powershell(), completions_generate_zsh(), config_create_default(), config_load_and_apply(), config_load_system_and_user(), config_schema_build_from_configs(), config_schema_destroy(), consensus_coordinator_create(), consensus_coordinator_destroy(), consensus_election_choose_hosts(), consensus_metrics_collection_add(), consensus_metrics_collection_destroy(), consensus_state_destroy(), consensus_topology_create(), consensus_topology_destroy(), create_mixed_ascii_frame_for_client(), crypto_handshake_server_start(), crypto_regex_match_known_hosts(), crypto_regex_match_public_key(), crypto_session_create(), crypto_session_destroy(), detect_client_utf8_support(), detect_default_ssh_key(), digital_rain_destroy(), digital_rain_init(), digital_rain_render_at(), discover_session_parallel(), discovery_keys_get_cache_path(), discovery_mdns_destroy(), discovery_session_create(), discovery_session_destroy(), display_height(), display_width(), ducking_destroy(), ducking_init(), face_follow_image_destroy(), fetch_github_gpg_keys(), fetch_github_ssh_keys(), fetch_gitlab_gpg_keys(), fetch_gitlab_ssh_keys(), ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), ffmpeg_decoder_destroy(), ffmpeg_encoder_create_scaled(), format_message(), fps_counter_destroy(), frame_buffer_append(), frame_buffer_create(), frame_buffer_destroy(), frame_buffer_flush(), frame_buffer_printf(), framebuffer_destroy(), get_discovery_database_dir(), get_known_hosts_path(), get_log_dir(), gpg_get_public_key(), gpg_homedir_destroy(), grep_destroy(), grep_init(), grep_restore_patterns(), grep_save_patterns(), grep_should_output(), h265_client_context_create(), h265_client_context_destroy(), h265_client_init_media_source(), h265_decoder_destroy(), h265_encoder_destroy(), h265_server_context_destroy(), handle_audio_batch_packet(), handle_audio_opus_batch_packet(), handle_audio_packet(), handle_image_frame_h265_packet(), handle_image_frame_packet(), http2_connection_create(), http2_connection_destroy(), http2_connection_submit_response(), http_render_result_destroy(), http_renderer_destroy(), http_renderer_init(), http_renderer_process(), http_renderer_process_result_destroy(), http_renderer_reap(), http_renderer_submit(), http_response_finish(), http_response_release(), http_response_retain(), http_server_destroy(), http_server_dispatch_http3(), http_server_http3_destroy(), http_server_init(), initial_options(), known_hosts_destroy(), layout_print_two_column_row(), levenshtein_n(), log_mmap_write(), log_net_message(), log_search_filter_buffer(), manpage_content_free_environment(), manpage_content_free_examples(), manpage_content_free_options(), manpage_content_free_positional(), manpage_content_free_usage(), manpage_content_generate_environment_with_manual(), manpage_content_generate_examples(), manpage_content_generate_options(), manpage_merger_free_content(), manpage_parser_free_sections(), manpage_resources_destroy(), mcp_request_destroy(), mcp_server_main(), mcp_stdio_run(), media_source_create_interruptible(), media_source_destroy(), memory_backend_create(), mirror_convert_frame(), mirror_render_audio_visualization(), mirror_render_context_destroy(), mixer_add_source(), mixer_create_channels(), mixer_destroy(), mixer_remove_source(), mutex_stack_free_all_threads(), mutex_stack_get_all_threads(), nat_upnp_close(), nat_upnp_open_protocol(), network_server_create(), network_server_destroy(), openpgp_base64_decode(), openpgp_parse_armored_pubkey(), openpgp_parse_armored_seckey(), options_apply_patch(), options_json_parse_value(), options_json_parse_value(), options_state_destroy(), opus_codec_create_decoder_channels(), opus_codec_create_encoder_channels(), opus_codec_destroy(), packet_queue_destroy(), packet_send_error(), packet_send_remote_log(), parse_gpg_key_binary(), parse_gpg_keys_from_response(), parse_keys_from_file(), parse_log_file(), parse_private_key(), parse_public_key(), parse_public_keys(), parse_ssh_ed25519_line(), parse_ssh_keys_from_response(), parse_ssh_private_key(), path_validate_user_path(), platform_event_listen(), platform_event_loop_create(), platform_event_loop_destroy(), platform_event_loop_work(), platform_event_stream_close(), platform_event_stream_work(), platform_event_stream_write(), ClientSessionBinding::process(), quic_connection_destroy(), quic_connection_matches_cid(), quic_endpoint_destroy(), quic_endpoint_open(), quic_release(), quic_tls_destroy(), quic_transport_destroy_unclaimed_on_lane(), quic_udp_connect(), quic_udp_endpoint_create(), quic_udp_endpoint_destroy(), quic_udp_remove(), quic_worker_stop(), read_password_from_stdin(), remove_known_host(), render_file_create(), render_file_destroy(), render_progress_create(), render_progress_destroy(), render_progress_frame(), ringbuffer_destroy(), sdp_session_destroy(), session_audio_create(), session_audio_destroy(), session_av_state_destroy(), session_capture_create(), session_capture_destroy(), session_consensus_create(), session_consensus_destroy(), session_display_destroy(), session_display_encode_frame(), session_display_release_ascii(), session_display_render_frame(), session_display_write_ascii_frame(), session_entry_destroy(), session_host_create(), session_host_destroy(), session_log_buffer_destroy(), session_network_capture_create(), session_participant_create(), session_participant_destroy(), session_participant_receive_settings(), session_participant_request_settings(), session_pipeline_create(), session_pipeline_destroy(), session_protocol_dispatch(), session_settings_from_options(), simd_caches_destroy_all(), simple_frame_swap_destroy(), spectral_destroy(), ssh_agent_sign(), stats_runtime_peer_close(), stats_runtime_peer_open(), stats_sampler_create(), stats_sampler_destroy(), stats_scope_create(), stats_scope_destroy(), term_renderer_create(), term_renderer_destroy(), term_renderer_feed(), terminal_fd_reader_destroy(), terminal_fd_reader_next(), terminal_fd_writer_destroy(), terminal_screen_compose(), terminal_screen_render(), test_pattern_destroy(), test_pattern_resize(), thread_pool_create(), thread_pool_create_with_workers(), thread_pool_destroy(), thread_pool_spawn(), thread_pool_stop_all(), timer_start(), timer_stop(), timer_system_destroy(), ui_notice_present(), ui_notice_present_first_use(), ui_password_prompt_present(), ui_prompt_present_kind(), ui_session_destroy(), ui_session_help_free(), update_check_load_cache(), update_check_perform(), update_check_save_cache(), url_parse(), url_parts_destroy(), utf8_palette_create(), utf8_palette_destroy(), validate_ssh_key_file(), video_frame_buffer_destroy(), wav_writer_close(), wav_writer_open(), webrtc_close_peer_connection(), webrtc_create_peer_connection(), webrtc_datachannel_destroy(), webrtc_peer_connection_destroy(), webrtc_peer_manager_create(), webrtc_peer_manager_destroy(), webrtc_peer_manager_handle_sdp(), and zalgo_apply().

◆ SAFE_GETENV

◆ SAFE_MALLOC

#define SAFE_MALLOC ( size,
cast )

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

Value:
({ \
cast _ptr = (cast)ALLOC_MALLOC(size); \
if (!_ptr) { \
FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
} \
_ptr; \
})
#define ALLOC_MALLOC(size)

Definition at line 272 of file include/ascii-chat/common.h.

272#define SAFE_MALLOC(size, cast) \
273 ({ \
274 cast _ptr = (cast)ALLOC_MALLOC(size); \
275 if (!_ptr) { \
276 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
277 } \
278 _ptr; \
279 })

Referenced by acip_render_settings_capabilities(), acip_settings_request(), acip_tcp_transport_create(), add_known_host(), ansi_strip_escapes(), ascii_create_grid(), ascii_frame_init(), ascii_half_frame_init(), ascii_pad_frame_height(), ascii_pad_frame_width(), ascii_write(), asciichat_mdns_init(), asciichat_pcre2_extract_group(), asciichat_pcre2_extract_named_group(), audio_init(), audio_visualization_render_fft(), audio_visualization_render_waveform(), browser_client_settings_receive(), browser_client_settings_values(), client_audio_render_thread(), client_settings_receive(), client_settings_values(), colorscheme_compile_scheme(), config_create_default(), config_load_and_apply(), config_load_system_and_user(), config_schema_build_from_configs(), consensus_coordinator_create(), consensus_election_choose_hosts(), consensus_metrics_collection_add(), consensus_metrics_collection_create(), consensus_state_create(), consensus_topology_create(), crypto_handshake_server_start(), digital_rain_render_at(), discover_session_parallel(), discovery_mdns_query(), ducking_init(), expand_path(), ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), format_message(), frame_buffer_append(), frame_buffer_create(), frame_buffer_flush(), frame_buffer_printf(), get_known_hosts_path(), get_log_dir(), get_modes_by_group(), get_utf8_palette_cache(), grep_highlight_colored_copy(), grep_init(), grep_should_output(), h265_client_context_create(), h265_client_init_media_source(), handle_audio_batch_packet(), handle_audio_opus_batch_packet(), handle_audio_packet(), handle_image_frame_h265_packet(), http2_connection_submit_response(), http_render_result_add_text_frame(), http_renderer_process(), http_renderer_render_file(), http_response_finish(), http_response_retain(), initial_options(), log_search_filter_buffer(), manpage_content_generate_environment(), manpage_content_generate_environment_with_manual(), manpage_content_generate_examples(), manpage_content_generate_options(), manpage_content_generate_positional(), manpage_content_generate_usage(), manpage_merger_generate_synopsis(), manpage_merger_generate_usage(), manpage_merger_merge_environment(), manpage_merger_merge_options(), manpage_merger_merge_positional(), mcp_stdio_run(), media_source_create_interruptible(), memory_backend_create(), mirror_convert_frame(), mixer_add_source(), mixer_create_channels(), mutex_stack_get_all_threads(), openpgp_base64_decode(), options_apply_patch(), options_get_enum_values(), options_registry_get_for_display(), options_registry_get_for_mode(), options_state_init(), options_state_set(), opus_codec_create_decoder_channels(), opus_codec_create_encoder_channels(), packet_send_error(), packet_send_remote_log(), parse_gpg_key_binary(), parse_gpg_keys_from_response(), parse_public_keys(), parse_ssh_keys_from_response(), path_validate_user_path(), platform_event_stream_write(), rainbow_render_ansi_at(), read_password_from_stdin(), render_file_create(), sdp_generate_answer(), sdp_generate_offer(), sdp_parse(), session_capture_create(), session_display_write_ascii_frame(), session_network_capture_create(), session_participant_receive_settings(), session_participant_request_settings(), session_protocol_dispatch(), session_settings_from_options(), simple_frame_swap_create(), ssh_agent_sign(), term_renderer_create(), term_renderer_feed(), terminal_fd_reader_create(), terminal_fd_reader_next(), terminal_screen_compose(), terminal_screen_render(), test_pattern_rgba(), thread_pool_create(), thread_pool_create_with_workers(), thread_pool_queue_work(), thread_pool_spawn(), timer_start(), ui_notice_present(), ui_notice_present_first_use(), ui_prompt_present_kind(), ui_session_context_help_render(), ui_session_help_render(), url_parse(), utf8_palette_create(), video_encoder_create(), visualization_encode(), wav_writer_open(), webrtc_create_peer_connection(), webrtc_peer_manager_create(), webrtc_peer_manager_handle_sdp(), and zalgo_apply().

◆ SAFE_MALLOC_ALIGNED

#define SAFE_MALLOC_ALIGNED ( size,
alignment,
cast )

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

Value:
({ \
size_t aligned_size = (((size) + (alignment) - 1) / (alignment)) * (alignment); \
cast _ptr = (cast)aligned_alloc((alignment), aligned_size); \
if (!_ptr) { \
FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", aligned_size, (size_t)(alignment)); \
} \
TRACK_ALIGNED_ALLOC(_ptr, aligned_size, __FILE__, __LINE__); \
_ptr; \
})

Definition at line 355 of file include/ascii-chat/common.h.

355#define SAFE_MALLOC_ALIGNED(size, alignment, cast) \
356 ({ \
357 size_t aligned_size = (((size) + (alignment) - 1) / (alignment)) * (alignment); \
358 cast _ptr = (cast)aligned_alloc((alignment), aligned_size); \
359 if (!_ptr) { \
360 FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", aligned_size, (size_t)(alignment)); \
361 } \
362 TRACK_ALIGNED_ALLOC(_ptr, aligned_size, __FILE__, __LINE__); \
363 _ptr; \
364 })

◆ SAFE_MALLOC_DEFER_FREE

#define SAFE_MALLOC_DEFER_FREE ( name,
size,
cast )

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

Value:
cast name = SAFE_MALLOC(size, cast); \
defer(SAFE_FREE(name))
#define SAFE_MALLOC(size, cast)

Definition at line 390 of file include/ascii-chat/common.h.

390#define SAFE_MALLOC_DEFER_FREE(name, size, cast) \
391 cast name = SAFE_MALLOC(size, cast); \
392 defer(SAFE_FREE(name))

Referenced by crypto_handshake_client_key_exchange(), crypto_handshake_server_auth_challenge(), gpg_homedir_create(), https_get(), levenshtein(), openpgp_base64_decode(), parse_keys_from_file(), parse_private_key(), parse_public_key(), session_protocol_update_settings(), video_frame_buffer_create(), and zalgo_apply().

◆ SAFE_MALLOC_SIMD

#define SAFE_MALLOC_SIMD ( size,
cast )

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

Value:
SAFE_MALLOC_ALIGNED(size, 16, cast)
#define SAFE_MALLOC_ALIGNED(size, alignment, cast)

Definition at line 369 of file include/ascii-chat/common.h.

◆ SAFE_MEMCPY

◆ SAFE_MEMMOVE

#define SAFE_MEMMOVE ( dest,
dest_size,
src,
count )

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

Value:
platform_memmove((dest), (dest_size), (src), (count))

Definition at line 489 of file include/ascii-chat/common.h.

◆ SAFE_MEMSET

◆ SAFE_REALLOC

#define SAFE_REALLOC ( ptr,
size,
cast )

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

Value:
({ \
void *tmp_ptr = ALLOC_REALLOC((ptr), (size)); \
if (!tmp_ptr) { \
FATAL(ERROR_MEMORY, "Memory reallocation failed: %zu bytes", (size_t)(size)); \
} \
(cast)(tmp_ptr); \
})
#define ALLOC_REALLOC(ptr, size)

Definition at line 292 of file include/ascii-chat/common.h.

292#define SAFE_REALLOC(ptr, size, cast) \
293 ({ \
294 void *tmp_ptr = ALLOC_REALLOC((ptr), (size)); \
295 if (!tmp_ptr) { \
296 FATAL(ERROR_MEMORY, "Memory reallocation failed: %zu bytes", (size_t)(size)); \
297 } \
298 (cast)(tmp_ptr); \
299 })

Referenced by completions_collect_all_modes_unique(), consensus_state_add_metrics(), grep_init(), http_response_write(), https_get(), manpage_content_generate_environment(), manpage_content_generate_environment_with_manual(), manpage_content_generate_examples(), manpage_content_generate_options(), manpage_content_generate_positional(), manpage_content_generate_usage(), manpage_merger_generate_usage(), ob_reserve(), remove_known_host(), and session_display_write_ascii_frame().

◆ safe_size_mul

#define safe_size_mul   bytes_safe_size_mul

◆ SAFE_SNPRINTF

◆ SAFE_SSCANF

#define SAFE_SSCANF ( str,
format,
... )

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

Value:
sscanf(str, format, __VA_ARGS__)

Definition at line 459 of file include/ascii-chat/common.h.

Referenced by parse_hex_color().

◆ SAFE_STRCPY

#define SAFE_STRCPY ( dest,
dest_size,
src )

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

Value:
platform_strcpy((dest), (dest_size), (src))
int platform_strcpy(char *dest, size_t dest_size, const char *src)

Definition at line 490 of file include/ascii-chat/common.h.

Referenced by h265_client_init_media_source(), log_named_format_or_original(), mixer_add_source(), and video_frame_buffer_create().

◆ SAFE_STRDUP

#define SAFE_STRDUP ( dst,
src )

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

Value:
do { \
if (src) { \
size_t _len = strlen(src) + 1; \
(dst) = SAFE_MALLOC(_len, char *); \
if (dst) { \
SAFE_MEMCPY((dst), _len, (src), _len); \
} else { \
SET_ERRNO(ERROR_MEMORY, "String duplication failed for: %s", (src)); \
} \
} else { \
(dst) = NULL; \
} \
} while (0)

Definition at line 437 of file include/ascii-chat/common.h.

437#define SAFE_STRDUP(dst, src) \
438 do { \
439 if (src) { \
440 size_t _len = strlen(src) + 1; \
441 (dst) = SAFE_MALLOC(_len, char *); \
442 if (dst) { \
443 SAFE_MEMCPY((dst), _len, (src), _len); \
444 } else { \
445 SET_ERRNO(ERROR_MEMORY, "String duplication failed for: %s", (src)); \
446 } \
447 } else { \
448 (dst) = NULL; \
449 } \
450 } while (0)

Referenced by detect_client_utf8_support().

◆ SAFE_STRERROR

#define SAFE_STRERROR ( errnum)

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

Value:
const char * platform_strerror(int errnum)
Definition system.c:52

Definition at line 484 of file include/ascii-chat/common.h.

Referenced by acip_tcp_transport_create(), gpg_sign_with_key(), gpg_verify_signature_with_binary(), and packet_send().

◆ SAFE_STRNCPY

#define SAFE_STRNCPY ( dst,
src,
size )

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

Value:
do { \
size_t _safe_strncpy_size = (size); \
if (_safe_strncpy_size > 0) { \
(void)platform_strncpy((dst), _safe_strncpy_size, (src), _safe_strncpy_size - 1); \
} \
} while (0)
int platform_strncpy(char *dest, size_t dest_size, const char *src, size_t count)

Definition at line 427 of file include/ascii-chat/common.h.

427#define SAFE_STRNCPY(dst, src, size) \
428 do { \
429 size_t _safe_strncpy_size = (size); \
430 if (_safe_strncpy_size > 0) { \
431 (void)platform_strncpy((dst), _safe_strncpy_size, (src), _safe_strncpy_size - 1); \
432 } \
433 } while (0)

Referenced by acds_client_config_init_defaults(), acds_identity_save(), acds_protocol_create(), acds_protocol_enter(), acds_protocol_join(), acds_protocol_lookup(), acds_protocol_receive(), acds_session_create(), acds_session_join(), acip_render_settings_capabilities(), acip_render_settings_options(), acip_render_settings_prepare(), acip_security_init_options(), asciichat_instr_log_line(), asciichat_mdns_advertise(), asciichat_mdns_query(), AsciiRendererBinding::AsciiRendererBinding(), browser_client_configure_crypto_options(), browser_client_set_server_address(), build_github_gpg_url(), build_gitlab_gpg_url(), client_audio_render_thread(), client_configure_crypto_options(), client_crypto_init(), client_main(), client_set_server_address(), client_video_render_thread(), colorscheme_compile_scheme(), colorscheme_load_from_file(), config_create_default(), config_schema_build_from_configs(), connection_endpoint_resolve(), crypto_handshake_init_with_password(), database_session_join(), database_session_leave(), detect_client_utf8_support(), disconnect_client_for_bad_data(), discovery_config_init_defaults(), discovery_main(), discovery_session_create(), env_pop_prompt_response(), extract_gpg_key_comment(), extract_ip_from_address(), format_gpg_key_display(), format_ip_with_port(), get_utf8_palette_cache(), gpg_get_public_key(), grep_highlight_colored(), handle_client_join_packet(), http_render_result_add_file_frame(), http_renderer_process(), is_valid_ipv4(), is_valid_ipv6(), log_init(), log_mmap_init(), log_recolor_plain_entry(), log_search_get_match_info(), log_search_init(), mcp_dispatch(), mcp_request_parse(), mcp_server_main(), mirror_convert_frame(), nat_upnp_get_endpoint(), nat_upnp_open_protocol(), negotiate_determine_result(), network_connection_prepare_security(), options_collect_identity_keys(), options_json_parse_value(), options_json_parse_value(), options_t_new(), parse_address_with_optional_port(), parse_gpg_keys_from_response(), parse_ip_with_port(), parse_log_file(), parse_palette_chars(), parse_palette_chars_option(), path_validate_user_path(), render_file_create(), sdp_generate_answer(), sdp_parse(), send_error_packet_message(), server_connection_set_ip(), session_host_add_client(), session_host_add_memory_participant(), session_host_create(), session_host_find_client(), session_participant_connect(), session_participant_create(), session_protocol_build_capabilities(), session_settings_from_values(), session_settings_to_options(), splash_set_discovery_session(), splash_set_update_notification(), thread_pool_create(), thread_pool_create_with_workers(), thread_pool_spawn(), time_pretty(), timer_start(), ui_reconnect_controller_set(), ui_session_loading(), ui_session_reconnecting(), ui_status_gather(), ui_status_render_header(), update_check_load_cache(), update_check_perform(), utf8_palette_create(), and webrtc_turn_servers_parse().

◆ THREAD_CREATE_OR_RETURN

#define THREAD_CREATE_OR_RETURN ( thread,
func,
arg )

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

Value:
do { \
if (platform_thread_create(&(thread), (func), (arg)) != 0) { \
log_error("Failed to create thread: %s", #func); \
return -1; \
} \
} while (0)

Create a thread or log error and return.

Parameters
threadPointer to thread_t variable
funcThread function (should match void* (*)(void*) signature)
argThread argument

Handles common pattern: create thread, log error if failed, then return -1. Example usage:

THREAD_CREATE_OR_RETURN(thread, thread_func, arg); // Thread created successfully, continue

Definition at line 540 of file include/ascii-chat/common.h.

540#define THREAD_CREATE_OR_RETURN(thread, func, arg) \
541 do { \
542 if (platform_thread_create(&(thread), (func), (arg)) != 0) { \
543 log_error("Failed to create thread: %s", #func); \
544 return -1; \
545 } \
546 } while (0)

◆ TRACK_ALIGNED_ALLOC

#define TRACK_ALIGNED_ALLOC ( ptr,
size,
file,
line )

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

Value:
((void)0)

Definition at line 312 of file include/ascii-chat/common.h.

◆ UNTRACKED_FREE

#define UNTRACKED_FREE ( ptr)

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

Value:
do { \
if ((ptr) != NULL) { \
free((void *)(ptr)); \
(ptr) = NULL; \
} \
} while (0)

Definition at line 418 of file include/ascii-chat/common.h.

418#define UNTRACKED_FREE(ptr) \
419 do { \
420 if ((ptr) != NULL) { \
421 free((void *)(ptr)); \
422 (ptr) = NULL; \
423 } \
424 } while (0)

Referenced by debug_sync_check_cond_deadlocks(), named_registry_for_each(), named_update_name(), and ui_sync_stop().

◆ UNTRACKED_MALLOC

#define UNTRACKED_MALLOC ( size,
cast )

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

Value:
({ \
cast _ptr = (cast)malloc(size); \
if (!_ptr) { \
FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
} \
_ptr; \
})

Definition at line 409 of file include/ascii-chat/common.h.

409#define UNTRACKED_MALLOC(size, cast) \
410 ({ \
411 cast _ptr = (cast)malloc(size); \
412 if (!_ptr) { \
413 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
414 } \
415 _ptr; \
416 })

Referenced by debug_sync_check_cond_deadlocks(), and named_registry_for_each().

◆ write_u16_unaligned

#define write_u16_unaligned   bytes_write_u16_unaligned

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

Definition at line 505 of file include/ascii-chat/common.h.

◆ write_u32_unaligned

#define write_u32_unaligned   bytes_write_u32_unaligned

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

Definition at line 506 of file include/ascii-chat/common.h.

Typedef Documentation

◆ uint16_t

typedef unsigned short uint16_t

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

Definition at line 68 of file include/ascii-chat/common.h.

◆ uint32_t

typedef unsigned int uint32_t

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

Definition at line 69 of file include/ascii-chat/common.h.

◆ uint64_t

typedef unsigned long long uint64_t

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

Definition at line 70 of file include/ascii-chat/common.h.

◆ uint8_t

typedef unsigned char uint8_t

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

Definition at line 67 of file include/ascii-chat/common.h.

Function Documentation

◆ asciichat_fatal_with_context()

_Noreturn void asciichat_fatal_with_context ( asciichat_error_t code,
const char * file,
int line,
const char * function,
const char * format,
... )

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

Definition at line 961 of file asciichat_errno.c.

963 {
964 // This path must also work when an allocator or a diagnostic itself failed.
965 bool previous = g_recording;
966 g_recording = true;
967 char message[ASCIICHAT_ERRNO_MESSAGE_MAX];
968 va_list args;
969 va_start(args, format);
970 vsnprintf(message, sizeof(message), format ? format : "", args);
971 va_end(args);
972 NOTICE(FATAL, "FATAL ERROR", "%s", asciichat_error_format(message, code));
973 log_error("Fatal: %s (at %s:%d in %s)", asciichat_error_format(message, code),
974 file ? file : "?", line, function ? function : "?");
976 g_recording = previous;
977#ifdef EMSCRIPTEN_BUILD
978 SET_ERRNO(code, "%s", message);
979#else
980 exit(code);
981#endif
982}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
void errno_print_stacks(void)
#define ASCIICHAT_ERRNO_MESSAGE_MAX
#define SET_ERRNO(code,...)
#define NOTICE(severity, title,...)
Definition notice.h:86

References args, ASCIICHAT_ERRNO_MESSAGE_MAX, asciichat_error_format(), errno_print_stacks(), FATAL, log_error, NOTICE, and SET_ERRNO.

◆ asciichat_shared_destroy()

void asciichat_shared_destroy ( void )

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

Clean up shared library subsystems.

Performs cleanup of all subsystems initialized by asciichat_shared_init(). All cleanup functions are idempotent and safe to call multiple times.

Applications should typically register this with atexit(): asciichat_shared_init(log_file, is_client); atexit(asciichat_shared_destroy);

Note
This function is safe to call even if init failed or wasn't called.
Cleanup order is the reverse of initialization order.
Library code never calls atexit() - only application code should.

Clean up shared library subsystems.

Performs comprehensive cleanup of all subsystems initialized by asciichat_shared_init(). All cleanup functions are idempotent (safe to call multiple times), so this can be called explicitly and also via atexit() without issues.

Cleanup order is carefully chosen to be the reverse of initialization, ensuring dependencies are respected (e.g., timer cleanup before memory reporting, memory reporting before errno cleanup).

Note
This function is safe to call even if init failed or wasn't called.
All subsystem cleanup functions must remain idempotent.

Definition at line 232 of file common.c.

232 {
233 // Guard against double cleanup (can be called explicitly + via atexit)
234 static bool shutdown_done = false;
235 if (shutdown_done) {
236 return;
237 }
238 shutdown_done = true;
239
240 // Ctrl-C has already stopped the application pipeline. Diagnostic workers
241 // may be inside logging/registry code and joining them from the atexit
242 // thread can deadlock. Restore the terminal output state and let the OS
243 // reclaim those process-owned workers after the remaining atexit handlers.
244 if (shutdown_is_requested()) {
246 return;
247 }
248
249 // Stop diagnostic readers before destroying symbols or synchronization state.
250 debug_sync_cleanup_thread();
253
259 // A signal-driven exit has already stopped all application workers. Do not
260 // enter the late atexit cleanup graph, whose debug-registry locks can be
261 // held by the console runtime; the OS reclaims process-owned resources.
263 return;
264
265 // Cleanup in reverse order of initialization (LIFO)
266 // This ensures dependencies are properly handled
267
268 // 0. Stop background threads first (before any cleanup that might use them)
269 // Terminal resize detection thread (Windows only, checks if active)
271
272#ifndef NDEBUG
273
274 // Clean up all remaining mutex stacks before memory report
276
277 // Clean up current thread's allocations
278 debug_sync_final_cleanup();
279
280 // Atomic debug cleanup
282#endif
283 debug_sync_destroy();
286
287 // 1. Terminal screen - cleanup frame buffer
289
290 // 2. SIMD caches - cleanup CPU-specific caches
292
293 // 3. Discovery service strings cache - cleanup session string cache
295
296 // 4. Logging - in correct order (end first, then begin)
299
300 // 5. Known hosts - cleanup authentication state
302
303 // 6. Options state - cleanup RCU-based options
305
306 // 7. buffer domain - cleanup global buffer domain
308
309 // 8. Platform cleanup - restores terminal, cleans up platform resources
310 // (includes symbol cache cleanup on Windows)
312
313 // 9. Keyboard - restore terminal settings (redundant with platform_destroy
314 // but safe)
316
317 // Workers have stopped; restore argv/environment before releasing title
318 // storage.
319 platform_process_title_destroy();
320
321 // 10. Timer system - cleanup timers (may still log!)
323
324 // 11. Error context cleanup
326
327 // 12. Logging cleanup - free log format buffers and system state
328 log_destroy();
331
332 // 13. Mutex stack cleanup - must be before memory report so stacks are freed
333#ifndef NDEBUG
335 // Final cleanup: free the main thread's debug allocations
336 debug_sync_final_cleanup();
337#endif
338
339 // 14. Memory stats (debug builds only) - runs with colors still available
340 // Note: debug_memory_report() is also called manually during shutdown in
341 // server_main() The function is safe to call multiple times with
342 // polling-based locking
343#if defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
344 print_mimalloc_stats();
345#endif
346
347#if defined(DEBUG_MEMORY) && !defined(NDEBUG)
348 debug_memory_report(GET_OPTION(color));
349#endif
350
351 // 15. Color cleanup - free compiled ANSI strings (AFTER memory report)
354
355 // 16. Clean up binary path cache explicitly
356 // Note: This is also called by platform_destroy() via atexit(), but it's
357 // idempotent
358 platform_cleanup_binary_path_cache();
359
360 // 17. Clean up RCU-based options state
362
363 // 18. Clean up errno context (allocated strings, backtrace symbols)
365
366#ifndef NDEBUG
367 // 19. Named registry - cleanup all registered thread names and debug entries
369#endif
370
371 // 21. timer resolution restore
372 platform_restore_timer_resolution(); // Restore timer resolution (no-op on
373 // POSIX)
374
375 // 22. Clean up SIMD caches
377
378 // 23. Clean up symbol cache
379 // This must be called BEFORE log_destroy() as symbol_cache_destroy() uses
380 // log_debug() Safe to call even if atexit() runs - it's idempotent (checks
381 // g_symbol_cache_initialized) Also called via platform_destroy() atexit
382 // handler, but explicit call ensures proper ordering
384
385 // 24. Clean up global buffer domain (explicitly, as atexit may not run on
386 // Ctrl-C) Note: This is also registered with atexit(), but calling it
387 // explicitly is safe (idempotent) Safe to call even if atexit() runs - it
388 // checks the default domain and sets it to NULL
390
391#ifndef NDEBUG
392 // 25. Symbol cache cleanup
394#endif
395 // No more shutdown diagnostics may scroll pending terminal errors away.
397}
void sanitizer_log_destroy(void)
Definition asan.c:53
void errno_shutdown(void)
void errno_destroy(void)
void debug_atomic_shutdown(void)
void buffer_system_cleanup(void)
Definition buffer.c:457
void colorscheme_destroy(void)
Shutdown the color system.
void acds_strings_destroy(void)
Cleanup function for session string cache Called by asciichat_shared_destroy() during library cleanup...
void debug_errno_destroy(void)
Definition errno.c:127
void debug_errno_cleanup_thread(void)
Definition errno.c:112
void ui_error_popup_flush(void)
void known_hosts_destroy(void)
Cleanup function to free cached known_hosts path.
void named_destroy(void)
Destroy the named object registry.
void log_shutdown_end(void)
End shutdown phase - restore previous logging settings.
Definition log/log.c:2231
void log_destroy(void)
Destroy the logging system and close log file.
Definition log/log.c:737
void log_cleanup_colors(void)
Clean up compiled color scheme.
Definition log/log.c:2248
void log_shutdown_begin(void)
Begin shutdown phase - disable console logging but keep file logging.
Definition log/log.c:2219
void log_system_destroy(void)
Shutdown the logging system internal state (system-level cleanup).
Definition log/log.c:801
void timer_system_destroy(void)
Cleanup the timing system.
Definition time.c:187
#define GET_OPTION(field)
Definition options.h:1339
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
void simd_caches_destroy_all(void)
Destroy all SIMD caches (palette and other caches).
void platform_destroy(void)
Definition init.c:14
void keyboard_destroy(void)
Definition keyboard.c:15
void debug_stats_cleanup_thread(void)
void debug_stats_destroy(void)
void mutex_stack_cleanup(void)
Cleanup mutex stack system.
Definition mutex.c:1064
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:483
void stats_runtime_stop(void)
Definition runtime.c:743
void terminal_stop_resize_detection(void)
int platform_restore_timer_resolution(void)
void symbol_cache_destroy(void)
void terminal_screen_cleanup(void)
Clean up terminal screen resources.
void ui_controller_restore_terminal_output(void)
void ui_controller_shutdown(void)
void ui_input_shutdown(void)
Definition tui/input.c:614

References acds_strings_destroy(), buffer_system_cleanup(), colorscheme_destroy(), debug_atomic_shutdown(), debug_errno_cleanup_thread(), debug_errno_destroy(), debug_stats_cleanup_thread(), debug_stats_destroy(), errno_destroy(), errno_shutdown(), GET_OPTION, keyboard_destroy(), known_hosts_destroy(), log_cleanup_colors(), log_destroy(), log_shutdown_begin(), log_shutdown_end(), log_system_destroy(), mutex_stack_cleanup(), named_destroy(), options_state_destroy(), platform_destroy(), platform_restore_timer_resolution(), sanitizer_log_destroy(), shutdown_is_requested(), simd_caches_destroy_all(), stats_runtime_stop(), symbol_cache_destroy(), terminal_screen_cleanup(), terminal_stop_resize_detection(), timer_system_destroy(), ui_controller_restore_terminal_output(), ui_controller_shutdown(), ui_error_popup_flush(), and ui_input_shutdown().

Referenced by client_main().

◆ asciichat_shared_init()

asciichat_error_t asciichat_shared_init ( const char * log_file,
bool is_client,
bool quiet_startup )

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

Initialize common subsystems shared by client and server.

This function performs initialization that is common to both client and server modes:

  • Platform initialization (Winsock, etc.)
  • Logging setup with default filename
  • Palette configuration
  • buffer domain initialization
  • Cleanup registration (errno, known_hosts, platform, buffer domain)
  • Mimalloc debug registration (if enabled)

Note: Memory debugging setup is handled separately by each mode due to different requirements (client has snapshot mode, server doesn't).

Call this BEFORE options_init() so that options parsing can use properly configured logging with colors. This initializes timer system, logging, and platform subsystems.

Parameters
log_fileLog filename to use (e.g., "client.log" or "ascii-chat.log")
is_clienttrue for client mode (routes all logs to stderr), false for server mode
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 134 of file common.c.

135 {
136 // Initialize shared subsystems BEFORE options_init()
137 // This allows options_init() to use properly configured logging with colors
138 //
139 // NOTE: This function is called BEFORE options_init(), so we can't use
140 // GET_OPTION() Palette config and quiet mode will be applied after
141 // options_init() is called
142
143 // Only register initialization tracking once
144 if (!g_shared_initialized) {
145 static const char *const ascii_chat_libraries[] = {"libasciichat", NULL};
146 symbol_cache_set_project_modules("ascii-chat", ascii_chat_libraries);
147
148 // 1. TIMER SYSTEM - Initialize first so timing is available for everything
149 // else
150 if (!timer_system_init()) {
151 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize timer system");
152 }
153
154 // KEYBOARD SYSTEM must be initialized BEFORE logging since keyboard_init()
155 // calls log_info() But we need to initialize logging AFTER
156 // timer_system_init() and BEFORE keyboard_init() So we move keyboard_init()
157 // to AFTER log_init()
158
159#ifndef NDEBUG
160 if (named_init() != ASCIICHAT_OK) {
161 return SET_ERRNO(ERROR_PLATFORM_INIT, "Failed to initialize named.");
162 }
163 debug_memory_ensure_init();
164 if (symbol_cache_init() != 0) {
166 "Failed to initialize symbol cache.");
167 }
168#endif
169
170 // 2. LOGGING - Initialize system state first, then user-level logging
171 // Initialize logging system internal state (terminal caps, colors)
173
174 // Initialize with provided log file
175 // Force stderr for client-like modes when stdout is piped to keep stdout
176 // clean
177 bool force_stderr = is_client && terminal_is_piped_output();
178
179 if (quiet_startup) {
181 }
182
183 // Use LOG_DEBUG by default; will be reconfigured after options_init()
185 log_init(log_file, LOG_DEBUG, force_stderr, false /* don't use_mmap */);
186
187 // 2. KEYBOARD SYSTEM - Initialize keyboard input AFTER logging (may fail if
188 // stdin/tty not available) Failure is not fatal -
189 // keyboard_read_nonblocking() safely handles uninitialized state
190 if (terminal_is_stdin_tty()) {
191 keyboard_init();
192 }
193
194 // 3. PLATFORM - Initialize platform-specific functionality (Winsock, etc)
195 if (platform_init() != ASCIICHAT_OK) {
196 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize platform");
197 }
198 if (socket_init() != 0) {
199 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize sockets");
200 }
201
202 // 4. buffer domain - Initialize global shared buffer domain
204
205 // Mark that we've initialized (prevents re-registration of subsystems)
206 g_shared_initialized = true;
207 }
208
209 // NOTE: This library function does NOT register atexit() handlers.
210 // Library code should not own the process lifecycle. The application
211 // is responsible for calling atexit(asciichat_shared_destroy) if it
212 // wants automatic cleanup on normal exit.
213
214 return ASCIICHAT_OK;
215}
void sanitizer_log_init(const char *filename)
Definition asan.c:52
void buffer_system_init(void)
Definition buffer.c:426
asciichat_error_t named_init(void)
Initialize the named object registry.
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
void log_system_init(void)
Initialize the logging system internal state (system-level init).
Definition log/log.c:784
void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
Initialize the logging system.
Definition log/log.c:627
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:663
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log/log.c:818
bool timer_system_init(void)
Initialize the timing system.
Definition time.c:164
int platform_init(void)
Definition init.c:9
#define LOG_DEBUG
Definition log/types.h:43
bool terminal_is_stdin_tty(void)
bool terminal_is_piped_output(void)

References ASCIICHAT_OK, buffer_system_init(), ERROR_PLATFORM_INIT, FATAL, LOG_DEBUG, log_file, log_init(), log_set_terminal_output(), log_system_init(), named_init(), platform_init(), sanitizer_log_init(), SET_ERRNO, terminal_is_piped_output(), terminal_is_stdin_tty(), and timer_system_init().

Referenced by browser_client_init(), and mirror_init().

◆ fps_frame_ns()

void fps_frame_ns ( fps_t * tracker,
uint64_t current_time_ns,
const char * context )

#include <include/ascii-chat/util/fps.h>

Track a frame and detect lag conditions (nanosecond version - PRIMARY).

Call this function when a frame is processed. Automatically detects when frames arrive late and generates periodic FPS reports every report_interval_ns. This is the primary API that all code should use going forward.

Parameters
trackerFPS tracker state
current_time_nsTimestamp of this frame in nanoseconds (from time_get_ns())
contextOptional context string for lag logging (e.g., "ASCII frame received")

Example usage:

fps_t tracker;
fps_init(&tracker, 60, "RENDER");
// In your frame loop
uint64_t now = time_get_ns();
fps_frame_ns(&tracker, now, "frame rendered");
void fps_frame_ns(fps_t *tracker, uint64_t current_time_ns, const char *context)
Track a frame and detect lag conditions (nanosecond version - PRIMARY).
Definition fps.c:58

Definition at line 58 of file fps.c.

59 {
60 if (!tracker) {
61 return;
62 }
63
64 // Initialize on first frame
65 if (tracker->last_fps_report_ns == 0) {
66 tracker->last_fps_report_ns = current_time_ns;
67 tracker->last_frame_time_ns = current_time_ns;
68 }
69
70 tracker->frame_count++;
71
72 // Calculate time since last frame in nanoseconds
73 uint64_t frame_interval_ns =
74 time_elapsed_ns(tracker->last_frame_time_ns, current_time_ns);
75 tracker->last_frame_time_ns = current_time_ns;
76
77 // Expected frame interval in nanoseconds
78 // For 60 FPS: 1 second / 60 = 16,666,666 ns per frame
79 uint64_t expected_interval_ns =
81 uint64_t lag_threshold_ns =
82 expected_interval_ns + (expected_interval_ns / 2); // 50% over expected
83
84 // Log error if frame arrived too late (only after first frame)
85 if (tracker->frame_count > 1 && frame_interval_ns > lag_threshold_ns) {
86 const char *context_str = context ? context : "Frame";
87
88 // Convert to milliseconds for display (but calculations stay in
89 // nanoseconds)
90 double late_ms =
91 time_ns_to_us(frame_interval_ns - expected_interval_ns) / 1000.0;
92 double expected_ms = time_ns_to_us(expected_interval_ns) / 1000.0;
93 double actual_ms = time_ns_to_us(frame_interval_ns) / 1000.0;
94 double actual_fps = 1e9 / (double)frame_interval_ns;
95
96 log_lag_event(tracker->tracker_name, context_str, late_ms, expected_ms,
97 actual_ms, actual_fps);
98 }
99
100 // Report FPS every report_interval_ns
101 uint64_t elapsed_ns =
102 time_elapsed_ns(tracker->last_fps_report_ns, current_time_ns);
103
104 if (elapsed_ns >= tracker->report_interval_ns) {
105 double elapsed_seconds = time_ns_to_s(elapsed_ns);
106 double actual_fps = (double)tracker->frame_count / elapsed_seconds;
107 log_fps_report(tracker->tracker_name, actual_fps, tracker->frame_count,
108 elapsed_seconds);
109
110 // Reset counters for next interval
111 tracker->frame_count = 0;
112 tracker->last_fps_report_ns = current_time_ns;
113 }
114}
#define NS_PER_SEC_INT
Definition time.h:173
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
const char * tracker_name
Definition fps.h:67
uint64_t frame_count
Definition fps.h:60
uint64_t report_interval_ns
Definition fps.h:65
uint64_t last_frame_time_ns
Definition fps.h:63
int expected_fps
Definition fps.h:64
uint64_t last_fps_report_ns
Definition fps.h:61

References fps_t::expected_fps, fps_t::frame_count, fps_t::last_fps_report_ns, fps_t::last_frame_time_ns, NS_PER_SEC_INT, fps_t::report_interval_ns, time_elapsed_ns(), and fps_t::tracker_name.

Referenced by client_audio_render_thread(), and client_video_render_thread().

◆ fps_init()

void fps_init ( fps_t * tracker,
int expected_fps,
const char * name )

#include <include/ascii-chat/util/fps.h>

Initialize FPS tracker.

Sets up the tracker with expected FPS and default reporting interval (10 seconds). Should be called once before using the tracker.

Parameters
trackerPointer to uninitialized fps_t (should be zero-initialized)
expected_fpsExpected frame rate in FPS (e.g., 60, 30, 20)
nameDisplay name for logging (e.g., "CLIENT", "WEBCAM", "AUDIO", "KEEPALIVE")

Definition at line 37 of file fps.c.

37 {
38 // Default report interval: 1 second
39 fps_init_with_interval(tracker, expected_fps, name, 1 * NS_PER_SEC_INT);
40}
void fps_init_with_interval(fps_t *tracker, int expected_fps, const char *name, uint64_t report_interval_ns)
Initialize FPS tracker with custom report interval.
Definition fps.c:42

References fps_init_with_interval(), and NS_PER_SEC_INT.

Referenced by client_audio_render_thread(), client_video_render_thread(), session_capture_create(), and session_network_capture_create().

◆ fps_init_with_interval()

void fps_init_with_interval ( fps_t * tracker,
int expected_fps,
const char * name,
uint64_t report_interval_ns )

#include <include/ascii-chat/util/fps.h>

Initialize FPS tracker with custom report interval.

Sets up the tracker with expected FPS and custom reporting interval in nanoseconds. Useful for different threads that may need different reporting frequencies.

Parameters
trackerPointer to uninitialized fps_t (should be zero-initialized)
expected_fpsExpected frame rate in FPS
nameDisplay name for logging
report_interval_nsCustom report interval in nanoseconds (e.g., 10000000000 = 10 seconds)

Definition at line 42 of file fps.c.

43 {
44 if (!tracker) {
45 return;
46 }
47
48 tracker->frame_count = 0;
49 tracker->expected_fps = expected_fps > 0 ? expected_fps : 60;
50 tracker->tracker_name = name ? name : "FPS";
51 tracker->report_interval_ns = report_interval_ns;
52
53 // Initialize timestamps to zero (will be set on first frame)
54 tracker->last_fps_report_ns = 0;
55 tracker->last_frame_time_ns = 0;
56}

References fps_t::expected_fps, fps_t::frame_count, fps_t::last_fps_report_ns, fps_t::last_frame_time_ns, fps_t::report_interval_ns, and fps_t::tracker_name.

Referenced by fps_init().

Variable Documentation

◆ g_argc

int g_argc
extern

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

Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from libplatform's terminal implementation during early execution.

Definition at line 62 of file common.c.

◆ g_argv

char** g_argv
extern

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

Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from libplatform's terminal implementation during early execution.

Definition at line 63 of file common.c.

◆ g_color_flag_passed

bool g_color_flag_passed
extern

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

Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initialized, used by terminal_should_color_output().

Definition at line 67 of file common.c.

Referenced by colored_string().

◆ g_color_flag_value

bool g_color_flag_value
extern

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

Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized, used by terminal_should_color_output().

Definition at line 69 of file common.c.

Referenced by colored_string().