ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
rcu.c
Go to the documentation of this file.
1
5
6#include <options/rcu.h>
7#include <options/runtime.h>
9#include <libflags/explicit.h>
10#include <math.h>
11#include <yyjson.h>
12#include <limits.h>
13#include <options/registry/core.h>
16#include <ascii-chat/common.h>
17#include <ascii-chat/log/log.h>
18#include <libplatform/lifecycle.h>
19#include <libplatform/compiler.h>
20#include <libplatform/system.h>
21#include <libplatform/terminal.h>
23#include <libplatform/process.h>
24
25#include <libplatform/atomic.h>
26#include <stdlib.h>
27#include <string.h>
28#ifndef _WIN32
29#include <pthread.h>
30#endif
31
32// ============================================================================
33// RCU State: Global Atomic Pointer
34// ============================================================================
35
45static atomic_ptr_t g_options = {0};
46
58static mutex_t g_options_write_mutex;
59
63static lifecycle_t g_options_lifecycle = LIFECYCLE_INIT;
64// Track the PID to detect fork() - after fork, child needs to reinitialize
65static pid_t g_init_pid = -1;
66
90static const options_t g_default_options = (options_t){
91 // ========================================================================
92 // Mode Detection (auto-detected, default here is uninitialized)
93 // ========================================================================
94 .detected_mode = MODE_INVALID,
95
96 // ========================================================================
97 // Binary-Level Options (parsed before mode selection)
98 // ========================================================================
99 .help = OPT_HELP_DEFAULT,
100 .version = OPT_VERSION_DEFAULT,
101 .config_file = OPT_STRING_EMPTY_DEFAULT,
102
103 // ========================================================================
104 // Terminal Dimensions
105 // ========================================================================
106 .width = OPT_WIDTH_DEFAULT,
107 .height = OPT_HEIGHT_DEFAULT,
108 .auto_width = OPT_AUTO_WIDTH_DEFAULT,
109 .auto_height = OPT_AUTO_HEIGHT_DEFAULT,
110
111 // ========================================================================
112 // Network Options
113 // ========================================================================
114 .address = OPT_ADDRESS_DEFAULT,
115 .address6 = OPT_ADDRESS6_DEFAULT,
116 .port = OPT_PORT_INT_DEFAULT,
117 .websocket_port = OPT_WEBSOCKET_PORT_SERVER_DEFAULT,
118 .max_clients = OPT_MAX_CLIENTS_DEFAULT,
119 .session_string = OPT_STRING_EMPTY_DEFAULT,
120
121 // ========================================================================
122 // Discovery Service (ACDS) Options
123 // ========================================================================
124 .discovery = OPT_ACDS_DEFAULT,
125 .discovery_expose_ip = OPT_ACDS_EXPOSE_IP_DEFAULT,
126 .discovery_insecure = OPT_ACDS_INSECURE_DEFAULT,
127 .discovery_port = OPT_ACDS_PORT_INT_DEFAULT,
128 .discovery_server = OPT_STRING_EMPTY_DEFAULT,
129 .discovery_service_key = OPT_STRING_EMPTY_DEFAULT,
130 .discovery_database_path = OPT_STRING_EMPTY_DEFAULT,
131
132 // ========================================================================
133 // LAN Discovery & WebRTC Options
134 // ========================================================================
135 .lan_discovery = OPT_LAN_DISCOVERY_DEFAULT,
136 .no_mdns_advertise = OPT_NO_MDNS_ADVERTISE_DEFAULT,
137 .enable_upnp = OPT_ENABLE_UPNP_DEFAULT,
138
139 // ========================================================================
140 // WebRTC Connection Strategy Options
141 // ========================================================================
142 .prefer_webrtc = OPT_PREFER_WEBRTC_DEFAULT,
143 .no_webrtc = OPT_NO_WEBRTC_DEFAULT,
144 .webrtc_skip_stun = OPT_WEBRTC_SKIP_STUN_DEFAULT,
145 .webrtc_relay_only = false,
146 .webrtc_disable_turn = OPT_WEBRTC_DISABLE_TURN_DEFAULT,
147 .webrtc_skip_host = OPT_WEBRTC_SKIP_HOST_DEFAULT,
148 .webrtc_ice_timeout_ms = OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT,
149
150 // ========================================================================
151 // WebRTC Connectivity Options (ACDS mode)
152 // ========================================================================
153 .stun_servers = OPT_STUN_SERVERS_DEFAULT,
154 .turn_servers = OPT_TURN_SERVERS_DEFAULT,
155 .turn_username = OPT_TURN_USERNAME_DEFAULT,
156 .turn_credential = OPT_TURN_CREDENTIAL_DEFAULT,
157 .turn_secret = OPT_STRING_EMPTY_DEFAULT,
158
159 // ========================================================================
160 // Encryption & Security Options
161 // ========================================================================
162 .encrypt_enabled = OPT_ENCRYPT_ENABLED_DEFAULT,
163 .no_encrypt = OPT_NO_ENCRYPT_DEFAULT,
164 .no_auth = OPT_NO_AUTH_DEFAULT,
165 .encrypt_key = OPT_STRING_EMPTY_DEFAULT,
166 .encrypt_keyfile = OPT_STRING_EMPTY_DEFAULT,
167 .password = OPT_STRING_EMPTY_DEFAULT,
168 .server_key = OPT_STRING_EMPTY_DEFAULT,
169 .client_keys = OPT_STRING_EMPTY_DEFAULT,
170 .require_server_identity = OPT_REQUIRE_SERVER_IDENTITY_DEFAULT,
171 .require_client_identity = OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT,
172 .require_server_verify = OPT_REQUIRE_SERVER_VERIFY_DEFAULT,
173 .require_client_verify = OPT_REQUIRE_CLIENT_VERIFY_DEFAULT,
174
175 // ========================================================================
176 // Media Options
177 // ========================================================================
178 .media_file = OPT_STRING_EMPTY_DEFAULT,
179 .media_url = OPT_STRING_EMPTY_DEFAULT,
180 .media_loop = OPT_MEDIA_LOOP_DEFAULT,
181 .media_from_stdin = OPT_MEDIA_FROM_STDIN_DEFAULT,
182 .media_seek_timestamp = OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT,
183 .pause = OPT_PAUSE_DEFAULT,
184 .yt_dlp_options = OPT_STRING_EMPTY_DEFAULT,
185
186 // ========================================================================
187 // Webcam Options
188 // ========================================================================
189 .webcam_index = OPT_WEBCAM_INDEX_DEFAULT,
190 .test_pattern = OPT_TEST_PATTERN_DEFAULT,
191 .no_audio_mixer = OPT_NO_AUDIO_MIXER_DEFAULT,
192 .stabilize = true,
193 .renderer = ASCII_RENDERER_DEFAULT,
194 .stretch = OPT_STRETCH_DEFAULT,
195 .flip_x = OPT_FLIP_X_DEFAULT,
196 .flip_y = OPT_FLIP_Y_DEFAULT,
197
198 // ========================================================================
199 // Display Options
200 // ========================================================================
201 .color = OPT_COLOR_DEFAULT,
202 .color_mode = OPT_COLOR_MODE_DEFAULT,
203 .color_filter = OPT_COLOR_FILTER_DEFAULT,
204 .color_scheme_name = OPT_COLOR_SCHEME_NAME_DEFAULT,
205 .render_mode = OPT_RENDER_MODE_DEFAULT,
206 .show_capabilities = OPT_SHOW_CAPABILITIES_DEFAULT,
207 .fps = OPT_FPS_DEFAULT,
208 .palette_type = OPT_PALETTE_TYPE_DEFAULT,
209 .palette_custom = OPT_STRING_EMPTY_DEFAULT,
210 .palette_custom_set = OPT_PALETTE_CUSTOM_SET_DEFAULT,
211
212 // ========================================================================
213 // Compression Options
214 // ========================================================================
215 .compression_level = OPT_COMPRESSION_LEVEL_DEFAULT,
216 .no_compress = OPT_NO_COMPRESS_DEFAULT,
217
218 // ========================================================================
219 // Audio Options
220 // ========================================================================
221 .audio_fft_size = 1024,
222 .test_audio = false,
223 .audio_spectral = true,
224 .audio_spectral_mixer = false,
225 .audio_spectral_gate = true,
226 .reduce_noise = true,
227 .audio_enabled = OPT_AUDIO_ENABLED_DEFAULT,
228 .audio_source = OPT_AUDIO_SOURCE_DEFAULT,
229 .audio_capture_source = OPT_AUDIO_CAPTURE_SOURCE_DEFAULT,
230 .waveform = false,
231 .fft = false,
232 .fft_scale = "-62:-6",
233 .microphone_index = OPT_MICROPHONE_INDEX_DEFAULT,
234 .speakers_index = OPT_SPEAKERS_INDEX_DEFAULT,
235 .microphone_sensitivity = OPT_MICROPHONE_SENSITIVITY_DEFAULT,
236 .speakers_volume = OPT_SPEAKERS_VOLUME_DEFAULT,
237 .audio_analysis_enabled = OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT,
238 .audio_no_playback = OPT_AUDIO_NO_PLAYBACK_DEFAULT,
239 .encode_audio = OPT_ENCODE_AUDIO_DEFAULT,
240
241 // ========================================================================
242 // Terminal & Output Options (consolidated)
243 // ========================================================================
244 .force_utf8 = OPT_FORCE_UTF8_DEFAULT,
245 .quiet = OPT_QUIET_DEFAULT,
246 .verbose_level = OPT_VERBOSE_LEVEL_DEFAULT,
247 .snapshot_mode = OPT_SNAPSHOT_MODE_DEFAULT,
248 .snapshot_delay = OPT_SNAPSHOT_DELAY_DEFAULT,
249 .matrix_rain = OPT_MATRIX_RAIN_DEFAULT,
250 .strip_ansi = OPT_STRIP_ANSI_DEFAULT,
251 .log_file = OPT_STRING_EMPTY_DEFAULT,
252 .log_level = OPT_LOG_LEVEL_DEFAULT,
253 .grep_pattern = OPT_GREP_PATTERN_DEFAULT,
254 .json = OPT_JSON_DEFAULT,
255 .log_template = OPT_LOG_TEMPLATE_DEFAULT,
256 .log_format_console_only = OPT_LOG_FORMAT_CONSOLE_DEFAULT,
257 .enable_keepawake = OPT_ENABLE_KEEPAWAKE_DEFAULT,
258 .disable_keepawake = OPT_DISABLE_KEEPAWAKE_DEFAULT,
259
260 // ========================================================================
261 // UI Screen Options
262 // ========================================================================
263 .splash_screen = OPT_SPLASH_DEFAULT,
264 .status_screen = OPT_STATUS_SCREEN_DEFAULT,
265
266 // ========================================================================
267 // Remaining Options (zero-initialized by default)
268 // ========================================================================
269 .reconnect_attempts = OPT_RECONNECT_ATTEMPTS_DEFAULT,
270 .no_check_update = OPT_NO_CHECK_UPDATE_DEFAULT,
271
272 // All remaining array fields (identity_keys, num_identity_keys, etc.)
273 // are zero-initialized (empty strings, NULL pointers, 0 values, etc.)
274 // which is appropriate for their types.
275};
276
277// ============================================================================
278// Memory Reclamation Strategy
279// ============================================================================
280
298static retired_options_t *g_retired;
299static size_t g_retired_count;
300static mutex_t g_deferred_free_mutex;
301static uint64_t g_revision;
302static options_origin_t g_origin;
303
304// options_get() borrows snapshots until shutdown. Preserve that public lifetime;
305// never free a published snapshot while a legacy reader can still hold it.
306static void deferred_free_add(options_t *old_opts) {
307 retired_options_t *node = SAFE_MALLOC(sizeof(*node), retired_options_t *);
308 node->value = old_opts;
309 mutex_lock(&g_deferred_free_mutex);
310 node->next = g_retired;
311 g_retired = node;
312 ++g_retired_count;
313 mutex_unlock(&g_deferred_free_mutex);
314}
315
317 if (!lifecycle_is_initialized(&g_options_lifecycle))
318 return 0;
319 mutex_lock(&g_deferred_free_mutex);
320 size_t count = g_retired_count;
321 mutex_unlock(&g_deferred_free_mutex);
322 return count;
323}
324
325static void deferred_free_all(void) {
326 while (g_retired) {
327 retired_options_t *node = g_retired;
328 g_retired = node->next;
329 --g_retired_count;
330 SAFE_FREE(node->value);
331 SAFE_FREE(node);
332 }
333}
334
335// ============================================================================
336// Fork Handler Registration
337// ============================================================================
338
339#ifndef _WIN32
346static void options_rcu_atfork_child(void) {
347 /* Reset the lifecycle state to allow reinitialization after fork */
348 /* This is safe because lifecycle_t is just an atomic int, can be reset directly */
349 __c11_atomic_store(&g_options_lifecycle.state, LIFECYCLE_UNINITIALIZED, __ATOMIC_RELEASE);
350
351 /* Reset the atomic options pointer to avoid dangling references */
352 /* The parent's allocated memory is not accessible/valid in the child */
353 atomic_ptr_store(&g_options, NULL);
354
355 /* Don't reset g_init_pid - we'll detect the fork in options_state_init */
356}
357
364__attribute__((constructor)) static void register_fork_handlers_constructor(void) {
365 // Register the child handler that will be called after fork() in the child process
366 pthread_atfork(NULL, NULL, options_rcu_atfork_child);
367}
368#endif
369
370// ============================================================================
371// Public API Implementation
372// ============================================================================
373
375 // RCU setters validate against the option registry, including when callers
376 // use the state API directly in tests or embedded integrations. Initialize
377 // the registry here so those callers observe the same metadata as the CLI.
379
380 // Detect fork: after fork(), child process must reinitialize
381 pid_t current_pid = platform_get_pid();
382 if ((lifecycle_is_initialized(&g_options_lifecycle) || g_init_pid != -1) && g_init_pid != current_pid) {
383 log_debug("Detected fork (parent PID %d, child PID %d) - resetting lifecycle", g_init_pid, current_pid);
384 /* Reset lifecycle to allow reinitialization after fork */
385 lifecycle_shutdown(&g_options_lifecycle);
386 g_init_pid = current_pid;
387 }
388
389 // Check if already initialized in this process using lifecycle
390 if (lifecycle_is_initialized(&g_options_lifecycle) && g_init_pid == current_pid && atomic_ptr_load(&g_options) != NULL) {
391 log_warn("Options state already initialized");
392 return ASCIICHAT_OK;
393 }
394 if (lifecycle_is_initialized(&g_options_lifecycle) && atomic_ptr_load(&g_options) == NULL) {
395 lifecycle_shutdown(&g_options_lifecycle);
396 }
397
398 /* Use lifecycle to serialize initialization */
399 if (!lifecycle_init(&g_options_lifecycle, "options")) {
400 /* Another thread is initializing or already initialized */
401 if (lifecycle_is_initialized(&g_options_lifecycle)) {
402 return ASCIICHAT_OK;
403 }
404 return SET_ERRNO(ERROR_INVALID_STATE, "Failed to acquire options initialization lock");
405 }
406
407 // Initialize write mutex
408 if (mutex_init(&g_options_write_mutex, "options_write") != 0) {
409 lifecycle_shutdown(&g_options_lifecycle);
410 return SET_ERRNO(ERROR_THREAD, "Failed to initialize options write mutex");
411 }
412
413 // Initialize deferred free mutex
414 if (mutex_init(&g_deferred_free_mutex, "deferred_free") != 0) {
415 mutex_destroy(&g_options_write_mutex);
416 lifecycle_shutdown(&g_options_lifecycle);
417 return SET_ERRNO(ERROR_THREAD, "Failed to initialize deferred free mutex");
418 }
419
420 // Allocate initial options struct (will be populated later by options_state_populate_from_globals)
421 options_t *initial_opts = SAFE_MALLOC(sizeof(options_t), options_t *);
422 if (!initial_opts) {
423 mutex_destroy(&g_options_write_mutex);
424 mutex_destroy(&g_deferred_free_mutex);
425 lifecycle_shutdown(&g_options_lifecycle);
426 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate initial options struct");
427 }
428
429 // Initialize all defaults using options_t_new()
430 *initial_opts = options_t_new();
431
432 // Publish initial struct (release semantics - make all fields visible to readers)
433 atomic_ptr_store(&g_options, initial_opts);
434
435 ++g_revision;
436 g_origin = OPTIONS_ORIGIN_CONFIG;
437 g_init_pid = current_pid; // Record PID to detect fork later
438 log_dev("Options state initialized with RCU pattern (PID %d)", current_pid);
439
440 return ASCIICHAT_OK;
441}
442
444 if (!opts) {
445 return SET_ERRNO(ERROR_INVALID_PARAM, "opts is NULL");
446 }
447
448 // Check initialization state using lifecycle
449 if (!lifecycle_is_initialized(&g_options_lifecycle)) {
450 return SET_ERRNO(ERROR_INVALID_STATE, "Options state not initialized (call options_state_init first)");
451 }
452
453 mutex_lock(&g_options_write_mutex);
454 options_t *next = SAFE_MALLOC(sizeof(*next), options_t *);
455 *next = *opts;
456 options_t *previous = atomic_ptr_load(&g_options);
457 atomic_ptr_store(&g_options, next);
458 ++g_revision;
459 g_origin = OPTIONS_ORIGIN_CONFIG;
460 deferred_free_add(previous);
461 mutex_unlock(&g_options_write_mutex);
462 return ASCIICHAT_OK;
463}
464
466 // Check if initialized using lifecycle
467 if (!lifecycle_is_initialized(&g_options_lifecycle)) {
468 return;
469 }
470
471 flags_explicit_state_destroy();
472
473 /* Shutdown lifecycle to mark as no longer initialized */
474 lifecycle_shutdown(&g_options_lifecycle);
475
476 // Get current options pointer
477 options_t *current = atomic_ptr_load(&g_options);
478
479 // Clear the atomic pointer (prevent further reads)
480 atomic_ptr_store(&g_options, NULL);
481
482 // Free current struct
483 SAFE_FREE(current);
484
485 // Free all deferred structs
486 deferred_free_all();
487
488 // Destroy dynamically created mutexes
489 mutex_destroy(&g_options_write_mutex);
490 mutex_destroy(&g_deferred_free_mutex);
491
492 log_debug("Options state shutdown complete");
493}
494
495const options_t *options_get(void) {
496 // Lock-free read with acquire semantics
497 // Guarantees we see all writes made before the pointer was published
498 options_t *current = atomic_ptr_load(&g_options);
499
500 // If options not yet published or after destruction, return safe static default.
501 // This is a critical fallback that:
502 // 1. Allows early startup code (before options_state_init) to work safely
503 // 2. Allows atexit handlers and cleanup code to call GET_OPTION() safely
504 // 3. Never crashes due to NULL pointer access
505 // 4. Provides sensible defaults for all option fields
506 //
507 // The static default options are:
508 // - Allocated once at startup (static storage)
509 // - Never freed (outlives all dynamically allocated options)
510 // - Thread-safe to read (immutable const data)
511 // - Complete with all OPT_*_DEFAULT values matching options_t_new()
512 if (!current) {
513 return (const options_t *)&g_default_options;
514 }
515
516 return current;
517}
518
519const terminal_options_t *options_terminal_settings_ptr(void) {
520 static terminal_options_t settings;
521 const options_t *options = options_get();
522 if (!options)
523 return NULL;
524 settings = (terminal_options_t){
525 .color = (terminal_color_setting_t)options->color,
526 .color_mode = options->color_mode,
527 .force_utf8 = (terminal_utf8_setting_t)options->force_utf8,
528 .render_mode = options->render_mode,
529 .width = options->width,
530 .height = options->height,
531 .fps = options->fps,
532 .snapshot_mode = options->snapshot_mode,
533 };
534 return &settings;
535}
536
537typedef struct {
538 const char *name;
540 size_t offset, size;
541 const char *cli;
548#define FIELD(name, type, cli) {#name, type, offsetof(options_t, name), sizeof(((options_t *)0)->name), cli}
549static const runtime_field_t runtime_fields[] = {
550 FIELD(width, OPTIONS_VALUE_INT, "width"),
551 FIELD(height, OPTIONS_VALUE_INT, "height"),
552 FIELD(max_clients, OPTIONS_VALUE_INT, "max-clients"),
553 FIELD(compression_level, OPTIONS_VALUE_INT, "compression-level"),
554 FIELD(reconnect_attempts, OPTIONS_VALUE_INT, "reconnect-attempts"),
555 FIELD(microphone_index, OPTIONS_VALUE_INT, "microphone-index"),
556 FIELD(speakers_index, OPTIONS_VALUE_INT, "speakers-index"),
557 FIELD(discovery_port, OPTIONS_VALUE_INT, "discovery-port"),
558 FIELD(port, OPTIONS_VALUE_INT, "port"),
559 FIELD(fps, OPTIONS_VALUE_INT, "fps"),
560 FIELD(color_mode, OPTIONS_VALUE_INT, "color-mode"),
561 FIELD(color_filter, OPTIONS_VALUE_INT, "color-filter"),
562 FIELD(render_mode, OPTIONS_VALUE_INT, "render-mode"),
563 FIELD(zalgo, OPTIONS_VALUE_INT, "zalgo"),
564 FIELD(log_level, OPTIONS_VALUE_INT, "log-level"),
565 FIELD(palette_type, OPTIONS_VALUE_INT, "palette"),
566 FIELD(no_compress, OPTIONS_VALUE_BOOL, "no-compress"),
567 FIELD(encode_audio, OPTIONS_VALUE_BOOL, "encode-audio"),
568 FIELD(flip_x, OPTIONS_VALUE_BOOL, "flip-x"),
569 FIELD(media_input, OPTIONS_VALUE_BOOL, "media-input"),
570 FIELD(flip_y, OPTIONS_VALUE_BOOL, "flip-y"),
571 FIELD(face_follow, OPTIONS_VALUE_BOOL, "face-follow"),
572 FIELD(test_pattern, OPTIONS_VALUE_BOOL, "test-pattern"),
573 FIELD(no_audio_mixer, OPTIONS_VALUE_BOOL, "no-audio-mixer"),
574 FIELD(show_capabilities, OPTIONS_VALUE_BOOL, "show-capabilities"),
575 FIELD(force_utf8, OPTIONS_VALUE_BOOL, "force-utf8"),
576 FIELD(audio_enabled, OPTIONS_VALUE_BOOL, "audio-enabled"),
577 FIELD(audio_analysis_enabled, OPTIONS_VALUE_BOOL, "audio-analysis-enabled"),
578 FIELD(audio_no_playback, OPTIONS_VALUE_BOOL, "audio-no-playback"),
579 FIELD(stabilize, OPTIONS_VALUE_BOOL, "stabilize"),
580 FIELD(renderer, OPTIONS_VALUE_INT, "renderer"),
581 FIELD(palette_explicit, OPTIONS_VALUE_BOOL, "palette-explicit"),
582 FIELD(stretch, OPTIONS_VALUE_BOOL, "stretch"),
583 FIELD(snapshot_mode, OPTIONS_VALUE_BOOL, "snapshot-mode"),
584 FIELD(strip_ansi, OPTIONS_VALUE_BOOL, "strip-ansi"),
585 FIELD(quiet, OPTIONS_VALUE_BOOL, "quiet"),
586 FIELD(encrypt_enabled, OPTIONS_VALUE_BOOL, "encrypt-enabled"),
587 FIELD(no_encrypt, OPTIONS_VALUE_BOOL, "no-encrypt"),
588 FIELD(discovery, OPTIONS_VALUE_BOOL, "discovery"),
589 FIELD(discovery_expose_ip, OPTIONS_VALUE_BOOL, "discovery-expose-ip"),
590 FIELD(discovery_insecure, OPTIONS_VALUE_BOOL, "discovery-insecure"),
591 FIELD(lan_discovery, OPTIONS_VALUE_BOOL, "lan-discovery"),
592 FIELD(no_mdns_advertise, OPTIONS_VALUE_BOOL, "no-mdns-advertise"),
593 FIELD(prefer_webrtc, OPTIONS_VALUE_BOOL, "prefer-webrtc"),
594 FIELD(no_webrtc, OPTIONS_VALUE_BOOL, "no-webrtc"),
595 FIELD(webrtc_skip_stun, OPTIONS_VALUE_BOOL, "webrtc-skip-stun"),
596 FIELD(webrtc_bind_address, OPTIONS_VALUE_STRING, "webrtc-bind-address"),
597 FIELD(webrtc_relay_only, OPTIONS_VALUE_BOOL, "webrtc-relay-only"),
598 FIELD(webrtc_disable_turn, OPTIONS_VALUE_BOOL, "webrtc-disable-turn"),
599 FIELD(enable_upnp, OPTIONS_VALUE_BOOL, "enable-upnp"),
600 FIELD(require_server_identity, OPTIONS_VALUE_BOOL, "require-server-identity"),
601 FIELD(require_client_identity, OPTIONS_VALUE_BOOL, "require-client-identity"),
602 FIELD(require_server_verify, OPTIONS_VALUE_BOOL, "require-server-verify"),
603 FIELD(require_client_verify, OPTIONS_VALUE_BOOL, "require-client-verify"),
604 FIELD(palette_custom_set, OPTIONS_VALUE_BOOL, "palette-custom-set"),
605 FIELD(media_loop, OPTIONS_VALUE_BOOL, "media-loop"),
606 FIELD(media_from_stdin, OPTIONS_VALUE_BOOL, "media-from-stdin"),
607 FIELD(auto_width, OPTIONS_VALUE_BOOL, "auto-width"),
608 FIELD(auto_height, OPTIONS_VALUE_BOOL, "auto-height"),
609 FIELD(splash_screen, OPTIONS_VALUE_BOOL, "splash-screen"),
610 FIELD(status_screen, OPTIONS_VALUE_BOOL, "status-screen"),
611 FIELD(matrix_rain, OPTIONS_VALUE_BOOL, "matrix-rain"),
612 FIELD(audio_source, OPTIONS_VALUE_INT, "audio-source"),
613 FIELD(waveform, OPTIONS_VALUE_BOOL, "waveform"),
614 FIELD(fft, OPTIONS_VALUE_BOOL, "fft"),
615 FIELD(fps_counter, OPTIONS_VALUE_BOOL, "fps-counter"),
616 FIELD(address, OPTIONS_VALUE_STRING, "address"),
617 FIELD(address6, OPTIONS_VALUE_STRING, "address6"),
618 FIELD(encrypt_key, OPTIONS_VALUE_STRING, "encrypt-key"),
619 FIELD(password, OPTIONS_VALUE_STRING, "password"),
620 FIELD(encrypt_keyfile, OPTIONS_VALUE_STRING, "encrypt-keyfile"),
621 FIELD(server_key, OPTIONS_VALUE_STRING, "server-key"),
622 FIELD(client_keys, OPTIONS_VALUE_STRING, "client-keys"),
623 FIELD(discovery_server, OPTIONS_VALUE_STRING, "discovery-server"),
624 FIELD(discovery_service_key, OPTIONS_VALUE_STRING, "discovery-service-key"),
625 FIELD(discovery_database_path, OPTIONS_VALUE_STRING, "discovery-database-path"),
626 FIELD(log_file, OPTIONS_VALUE_STRING, "log-file"),
627 FIELD(media_file, OPTIONS_VALUE_STRING, "media-file"),
628 FIELD(media_url, OPTIONS_VALUE_STRING, "media-url"),
629 FIELD(palette_custom, OPTIONS_VALUE_STRING, "palette-chars"),
630 FIELD(stun_servers, OPTIONS_VALUE_STRING, "stun-servers"),
631 FIELD(turn_servers, OPTIONS_VALUE_STRING, "turn-servers"),
632 FIELD(turn_username, OPTIONS_VALUE_STRING, "turn-username"),
633 FIELD(turn_credential, OPTIONS_VALUE_STRING, "turn-credential"),
634 FIELD(turn_secret, OPTIONS_VALUE_STRING, "turn-secret"),
635 FIELD(session_string, OPTIONS_VALUE_STRING, "session-string"),
636 FIELD(snapshot_delay, OPTIONS_VALUE_DOUBLE, "snapshot-delay"),
637 FIELD(microphone_sensitivity, OPTIONS_VALUE_DOUBLE, "microphone-volume"),
638 FIELD(speakers_volume, OPTIONS_VALUE_DOUBLE, "speakers-volume"),
639};
640#undef FIELD
641
642static const runtime_field_t *find_field(const char *name) {
643 if (!name)
644 return NULL;
645 if (!strcmp(name, "volume") || !strcmp(name, "speakers-volume"))
646 name = "speakers_volume";
647 if (!strcmp(name, "ivolume") || !strcmp(name, "microphone-volume"))
648 name = "microphone_sensitivity";
649 for (size_t i = 0; i < sizeof(runtime_fields) / sizeof(*runtime_fields); ++i)
650 if (!strcmp(name, runtime_fields[i].name) || !strcmp(name, runtime_fields[i].cli))
651 return &runtime_fields[i];
652 return NULL;
653}
654
655bool options_remote_render_field(const char *name) {
656 const runtime_field_t *field = find_field(name);
657 if (!field)
658 return false;
659 const char *allowed[] = {"width", "height", "fps", "color_mode", "color_filter", "render_mode", "palette_type", "palette_custom", "palette_explicit", "renderer", "stabilize", "matrix_rain"};
660 for (size_t i = 0; i < sizeof(allowed) / sizeof(*allowed); ++i)
661 if (!strcmp(field->name, allowed[i]))
662 return true;
663 return false;
664}
665
666static asciichat_error_t validate_field(const runtime_field_t *field, const options_t *candidate) {
667 if (!strcmp(field->name, "audio_source") && (candidate->audio_source < AUDIO_SOURCE_ALL || candidate->audio_source > AUDIO_SOURCE_MEDIA))
668 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid option 'audio_source'");
669 const registry_entry_t *entry = registry_find_entry_by_name(field->cli);
670 const char *ptr = (const char *)candidate + field->offset;
671 if (entry && entry->validate_fn && !entry->validate_fn(candidate))
672 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid option '%s'", field->name);
673 if (field->type == OPTIONS_VALUE_INT || field->type == OPTIONS_VALUE_DOUBLE) {
674 double value = field->type == OPTIONS_VALUE_INT ? *(const int *)ptr : field->size == sizeof(float) ? *(const float *)ptr : *(const double *)ptr;
675 if (!isfinite(value))
676 return SET_ERRNO(ERROR_INVALID_PARAM, "Nonfinite option '%s'", field->name);
677 // Zero disables Zalgo at runtime; the CLI's explicit intensity starts at one.
678 if (!strcmp(field->name, "zalgo") && value == 0)
679 return ASCIICHAT_OK;
680 if (entry && (entry->metadata.numeric_range.min || entry->metadata.numeric_range.max) && (value < entry->metadata.numeric_range.min || value > entry->metadata.numeric_range.max))
681 return SET_ERRNO(ERROR_INVALID_PARAM, "Option '%s' is out of range", field->name);
682 if (field->type == OPTIONS_VALUE_INT && entry && entry->metadata.enum_values && entry->metadata.input_type == OPTION_INPUT_ENUM) {
683 bool found = false;
684 for (size_t i = 0; entry->metadata.enum_values[i]; ++i) {
685 int enum_value = entry->metadata.enum_integer_values ? entry->metadata.enum_integer_values[i] : (int)i;
686 if (*(const int *)ptr == enum_value)
687 found = true;
688 }
689 if (!found)
690 return SET_ERRNO(ERROR_INVALID_PARAM, "Unknown value for '%s'", field->name);
691 }
692 if ((!strcmp(field->name, "port") || !strcmp(field->name, "discovery_port")) && (value < 1 || value > 65535))
693 return SET_ERRNO(ERROR_INVALID_PARAM, "Port must be in [1, 65535]");
694 }
695 return ASCIICHAT_OK;
696}
697
698static asciichat_error_t edit_candidate(options_t *candidate, const options_edit_t *edit) {
699 const runtime_field_t *field = find_field(edit->name);
700 if (!field || field->type != edit->type)
701 return SET_ERRNO(ERROR_INVALID_PARAM, "Unknown option or wrong type: %s", edit->name ? edit->name : "(null)");
702 char *ptr = (char *)candidate + field->offset;
703 switch (edit->type) {
704 case OPTIONS_VALUE_INT: {
705 int value = edit->value.integer;
706 if (edit->operation == OPTIONS_CYCLE) {
707 if (value <= 0 || value > 256)
708 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid cycle size");
709 value = (*(int *)ptr + 1) % value;
710 } else if (edit->operation != OPTIONS_ASSIGN)
711 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid integer operation");
712 memcpy(ptr, &value, sizeof(value));
713 if (!strcmp(field->name, "palette_type"))
714 candidate->palette_explicit = true;
715 break;
716 }
717 case OPTIONS_VALUE_BOOL: {
718 bool value = edit->value.boolean;
719 if (edit->operation == OPTIONS_TOGGLE)
720 value = field->size == sizeof(int) ? !*(int *)ptr : !*(bool *)ptr;
721 else if (edit->operation != OPTIONS_ASSIGN)
722 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid boolean operation");
723 if (field->size == sizeof(int)) {
724 int integer = value;
725 memcpy(ptr, &integer, sizeof(integer));
726 } else
727 memcpy(ptr, &value, sizeof(value));
728 // An animation selection is one coherent change, including its exclusions.
729 if (value && (!strcmp(field->name, "matrix_rain") || !strcmp(field->name, "waveform") || !strcmp(field->name, "fft"))) {
730 candidate->matrix_rain = !strcmp(field->name, "matrix_rain");
731 candidate->waveform = !strcmp(field->name, "waveform");
732 candidate->fft = !strcmp(field->name, "fft");
733 }
734 break;
735 }
737 double value = edit->value.number;
738 if (edit->operation == OPTIONS_ADD) {
739 value += field->size == sizeof(float) ? *(float *)ptr : *(double *)ptr;
740 if (!strcmp(field->name, "speakers_volume") || !strcmp(field->name, "microphone_sensitivity"))
741 value = fmax(0.0, fmin(1.0, value));
742 } else if (edit->operation != OPTIONS_ASSIGN)
743 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid number operation");
744 if (!isfinite(value))
745 return SET_ERRNO(ERROR_INVALID_PARAM, "Nonfinite option '%s'", field->name);
746 if (field->size == sizeof(float)) {
747 float number = (float)value;
748 memcpy(ptr, &number, sizeof(number));
749 } else
750 memcpy(ptr, &value, sizeof(value));
751 break;
752 }
754 if (edit->operation != OPTIONS_ASSIGN || !edit->value.string)
755 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid string option '%s'", field->name);
756 size_t length = strlen(edit->value.string);
757 if (length >= field->size)
758 return SET_ERRNO(ERROR_INVALID_PARAM, "Overlong string option '%s'", field->name);
759 memset(ptr, 0, field->size);
760 memcpy(ptr, edit->value.string, length);
761 if (!strcmp(field->name, "palette_custom")) {
762 candidate->palette_custom_set = ptr[0] != 0;
763 candidate->palette_explicit = ptr[0] != 0;
764 }
765 break;
766 }
767 }
768 return ASCIICHAT_OK;
769}
770
771asciichat_error_t options_prepare_patch(const options_t *current, const options_patch_t *patch, options_t *candidate, bool remote_only) {
772 if (!current || !candidate || current == candidate || !patch || !patch->edits || !patch->count || patch->count > OPTIONS_PATCH_MAX_EDITS)
773 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid options patch");
774 *candidate = *current;
775 bool palette_explicit_set = false;
776 bool palette_explicit_value = false;
777 for (size_t i = 0; i < patch->count; ++i) {
778 const options_edit_t *edit = &patch->edits[i];
779 const runtime_field_t *field = find_field(edit->name);
780 if (field && !strcmp(field->name, "palette_explicit")) {
781 palette_explicit_set = true;
782 palette_explicit_value = edit->operation == OPTIONS_TOGGLE ? !current->palette_explicit : edit->value.boolean;
783 }
784 }
785 for (size_t i = 0; i < patch->count; ++i) {
786 if (remote_only && (!options_remote_render_field(patch->edits[i].name) || patch->edits[i].operation != OPTIONS_ASSIGN))
787 return SET_ERRNO(ERROR_INVALID_PARAM, "Option is not a remote render preference");
788 asciichat_error_t error = edit_candidate(candidate, &patch->edits[i]);
789 if (error != ASCIICHAT_OK)
790 return error;
791 }
792 // An explicit palette flag is authoritative for the entire patch. Palette
793 // type/custom edits may imply explicit selection while they are applied, but
794 // must not overwrite an explicit false value supplied in the same patch.
795 if (palette_explicit_set)
796 candidate->palette_explicit = palette_explicit_value;
797 bool animation_changed = false;
798 bool stabilize_changed = false;
799 for (size_t i = 0; i < patch->count; ++i) {
800 const char *name = patch->edits[i].name;
801 animation_changed |= !strcmp(name, "matrix_rain") || !strcmp(name, "waveform") || !strcmp(name, "fft");
802 stabilize_changed |= !strcmp(name, "stabilize");
803 }
804 if (animation_changed && !stabilize_changed)
805 candidate->stabilize = !(candidate->waveform || candidate->fft);
806 bool orientation_changed = false;
807 bool flip_x_set_in_patch = false;
808 for (size_t i = 0; i < patch->count; ++i) {
809 const char *name = patch->edits[i].name;
810 orientation_changed |= !strcmp(name, "media_input") || !strcmp(name, "waveform") || !strcmp(name, "fft");
811 flip_x_set_in_patch |= !strcmp(name, "flip_x");
812 }
813 if (orientation_changed && !flip_x_set_in_patch && !flags_explicit_state_was_set("flip-x"))
814 candidate->flip_x = !candidate->media_input && !candidate->waveform && !candidate->fft;
815 for (size_t i = 0; i < patch->count; ++i) {
816 asciichat_error_t error = validate_field(find_field(patch->edits[i].name), candidate);
817 if (error != ASCIICHAT_OK)
818 return error;
819 }
820 asciichat_error_t palette_error = validate_glyph_palette(candidate);
821 if (palette_error != ASCIICHAT_OK)
822 return palette_error;
823 return ASCIICHAT_OK;
824}
825
827 if (!patch || !patch->edits || !patch->count || patch->count > OPTIONS_PATCH_MAX_EDITS)
828 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid options patch");
829 if (!lifecycle_is_initialized(&g_options_lifecycle))
830 return SET_ERRNO(ERROR_INVALID_STATE, "Options are not initialized");
831 mutex_lock(&g_options_write_mutex);
832 if (result)
833 *result = (options_patch_result_t){.revision = g_revision};
834 if (patch->expected_revision != OPTIONS_REVISION_ANY && patch->expected_revision != g_revision) {
835 mutex_unlock(&g_options_write_mutex);
836 return SET_ERRNO(ERROR_INVALID_STATE, "Options changed; refresh and retry");
837 }
838 options_t *current = atomic_ptr_load(&g_options);
839 options_t *candidate = SAFE_MALLOC(sizeof(*candidate), options_t *);
840 asciichat_error_t error = options_prepare_patch(current, patch, candidate, false);
841 if (error == ASCIICHAT_OK && memcmp(current, candidate, sizeof(*current))) {
842 atomic_ptr_store(&g_options, candidate);
843 deferred_free_add(current);
844 ++g_revision;
845 g_origin = patch->origin;
846 for (size_t i = 0; i < patch->count; ++i) {
847 if (!strcmp(patch->edits[i].name, "flip_x"))
848 flags_explicit_state_set("flip-x", true);
849 }
850 if (result)
851 *result = (options_patch_result_t){.revision = g_revision, .changed = true};
852 } else
853 SAFE_FREE(candidate);
854 mutex_unlock(&g_options_write_mutex);
855 return error;
856}
857
859 if (!snapshot || !lifecycle_is_initialized(&g_options_lifecycle))
860 return SET_ERRNO(ERROR_INVALID_STATE, "Options are not initialized");
861 mutex_lock(&g_options_write_mutex);
862 snapshot->values = *(options_t *)atomic_ptr_load(&g_options);
863 snapshot->revision = g_revision;
864 snapshot->origin = g_origin;
865 mutex_unlock(&g_options_write_mutex);
866 return ASCIICHAT_OK;
867}
868
870 if (!lifecycle_is_initialized(&g_options_lifecycle))
871 return 0;
872 mutex_lock(&g_options_write_mutex);
873 uint64_t revision = g_revision;
874 mutex_unlock(&g_options_write_mutex);
875 return revision;
876}
877
878static asciichat_error_t apply_one(options_edit_t edit) {
879 options_patch_t patch = {.edits = &edit, .count = 1, .expected_revision = OPTIONS_REVISION_ANY};
880 return options_apply_patch(&patch, NULL);
881}
887asciichat_error_t options_set_int(const char *name, int value) {
888 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_INT, .value.integer = value});
889}
890
895asciichat_error_t options_set_bool(const char *name, bool value) {
896 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_BOOL, .value.boolean = value});
897}
898asciichat_error_t options_set_double(const char *name, double value) {
899 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_DOUBLE, .value.number = value});
900}
901asciichat_error_t options_set_string(const char *name, const char *value) {
902 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_STRING, .value.string = value});
903}
905 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_BOOL, .operation = OPTIONS_TOGGLE});
906}
907asciichat_error_t options_adjust(const char *name, double amount) {
908 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_DOUBLE, .operation = OPTIONS_ADD, .value.number = amount});
909}
910asciichat_error_t options_cycle(const char *name, int count) {
911 return apply_one((options_edit_t){.name = name, .type = OPTIONS_VALUE_INT, .operation = OPTIONS_CYCLE, .value.integer = count});
912}
913
914static void *json_allocate(void *context, size_t size) {
915 (void)context;
916 return SAFE_MALLOC(size, void *);
917}
918static void *json_reallocate(void *context, void *ptr, size_t old_size, size_t size) {
919 (void)context;
920 (void)old_size;
921 return SAFE_REALLOC(ptr, size, void *);
922}
923static void json_release(void *context, void *ptr) {
924 (void)context;
925 SAFE_FREE(ptr);
926}
927static const yyjson_alc runtime_json_allocator = {json_allocate, json_reallocate, json_release, NULL};
928
929static asciichat_error_t parse_json_edits(const char *json, size_t length, yyjson_doc **doc, options_edit_t *edits, size_t *count) {
930 if (!json || !length || length > 4096)
931 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid settings payload size");
932 *doc = yyjson_read_opts((char *)json, length, 0, &runtime_json_allocator, NULL);
933 yyjson_val *root = *doc ? yyjson_doc_get_root(*doc) : NULL;
934 if (!yyjson_is_obj(root) || !yyjson_obj_size(root) || yyjson_obj_size(root) > OPTIONS_PATCH_MAX_EDITS)
935 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected a nonempty settings object");
936 size_t index, max;
937 yyjson_val *key, *value;
938 *count = 0;
939 yyjson_obj_foreach(root, index, max, key, value) {
940 const char *name = yyjson_get_str(key);
941 if (strlen(name) != yyjson_get_len(key))
942 return SET_ERRNO(ERROR_INVALID_PARAM, "Setting names cannot contain NUL");
943 const runtime_field_t *field = find_field(name);
944 if (!field)
945 return SET_ERRNO(ERROR_INVALID_PARAM, "Unknown setting '%s'", name);
946 for (size_t j = 0; j < *count; ++j)
947 if (find_field(edits[j].name) == field)
948 return SET_ERRNO(ERROR_INVALID_PARAM, "Duplicate setting '%s'", name);
949 options_edit_t edit = {.name = name, .type = field->type};
950 switch (field->type) {
952 if (!yyjson_is_int(value) || yyjson_get_sint(value) < INT_MIN || yyjson_get_sint(value) > INT_MAX)
953 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected integer '%s'", name);
954 edit.value.integer = (int)yyjson_get_sint(value);
955 break;
957 if (!yyjson_is_bool(value))
958 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected boolean '%s'", name);
959 edit.value.boolean = yyjson_get_bool(value);
960 break;
962 if (!yyjson_is_num(value))
963 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected number '%s'", name);
964 edit.value.number = yyjson_get_num(value);
965 break;
967 if (!yyjson_is_str(value) || strlen(yyjson_get_str(value)) != yyjson_get_len(value))
968 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected string without NUL '%s'", name);
969 edit.value.string = yyjson_get_str(value);
970 break;
971 }
972 edits[(*count)++] = edit;
973 }
974 return ASCIICHAT_OK;
975}
976
977asciichat_error_t options_prepare_json(const options_t *current, const char *json, size_t length, options_t *candidate, bool remote_only) {
978 yyjson_doc *doc = NULL;
980 size_t count = 0;
981 asciichat_error_t error = parse_json_edits(json, length, &doc, edits, &count);
982 options_patch_t patch = {.edits = edits, .count = count, .expected_revision = OPTIONS_REVISION_ANY};
983 if (error == ASCIICHAT_OK)
984 error = options_prepare_patch(current, &patch, candidate, remote_only);
985 yyjson_doc_free(doc);
986 return error;
987}
988
989asciichat_error_t options_apply_json(const char *json, size_t length, uint64_t expected_revision, options_origin_t origin, options_patch_result_t *result) {
990 yyjson_doc *doc = NULL;
992 size_t count = 0;
993 asciichat_error_t error = parse_json_edits(json, length, &doc, edits, &count);
994 options_patch_t patch = {.edits = edits, .count = count, .expected_revision = expected_revision, .origin = origin};
995 if (error == ASCIICHAT_OK)
996 error = options_apply_patch(&patch, result);
997 yyjson_doc_free(doc);
998 return error;
999}
1000
1001char *options_values_json(const options_t *values, bool remote_only) {
1002 yyjson_mut_doc *doc = yyjson_mut_doc_new(&runtime_json_allocator);
1003 if (!doc)
1004 return NULL;
1005 yyjson_mut_val *root = yyjson_mut_obj(doc);
1006 yyjson_mut_doc_set_root(doc, root);
1007 for (size_t i = 0; i < sizeof(runtime_fields) / sizeof(*runtime_fields); ++i) {
1008 const runtime_field_t *field = &runtime_fields[i];
1009 bool exposed = options_remote_render_field(field->name);
1010 if (!remote_only && (!strcmp(field->name, "flip_x") || !strcmp(field->name, "media_input") || !strcmp(field->name, "flip_y") || !strcmp(field->name, "waveform") || !strcmp(field->name, "fft") ||
1011 !strcmp(field->name, "fps_counter") || !strcmp(field->name, "audio_source") || !strcmp(field->name, "speakers_volume") || !strcmp(field->name, "microphone_sensitivity") ||
1012 !strcmp(field->name, "audio_enabled")))
1013 exposed = true;
1014 if (!exposed)
1015 continue;
1016 const char *ptr = (const char *)values + field->offset;
1017 switch (field->type) {
1018 case OPTIONS_VALUE_INT:
1019 yyjson_mut_obj_add_int(doc, root, field->name, *(const int *)ptr);
1020 break;
1021 case OPTIONS_VALUE_BOOL:
1022 yyjson_mut_obj_add_bool(doc, root, field->name, *(const bool *)ptr);
1023 break;
1025 yyjson_mut_obj_add_real(doc, root, field->name, field->size == sizeof(float) ? *(const float *)ptr : *(const double *)ptr);
1026 break;
1028 yyjson_mut_obj_add_str(doc, root, field->name, ptr);
1029 break;
1030 }
1031 }
1032 /*
1033 * The effective flip value is source-dependent: webcam input is mirrored
1034 * automatically until the user explicitly chooses an orientation. Expose
1035 * that provenance beside the effective value so browser clients can echo
1036 * engine-owned changes without turning them into an explicit preference.
1037 */
1038 if (!remote_only)
1039 yyjson_mut_obj_add_bool(doc, root, "flip_x_explicit", flags_explicit_state_was_set("flip-x"));
1040 char *json = yyjson_mut_write_opts(doc, 0, &runtime_json_allocator, NULL, NULL);
1041 yyjson_mut_doc_free(doc);
1042 return json;
1043}
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
@ OPTION_INPUT_ENUM
Choose from fixed set of enum values.
Definition builder.h:187
Platform initialization and static synchronization helpers.
const registry_entry_t * registry_find_entry_by_name(const char *long_name)
Get a registry entry by long name.
Definition core.c:126
void registry_init_size(void)
Initialize registry size and metadata.
Definition core.c:107
int color_mode
Definition fft.c:26
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:687
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
#define OPT_STRIP_ANSI_DEFAULT
Default strip ANSI escape sequences flag.
Definition options.h:446
#define OPT_WEBRTC_SKIP_STUN_DEFAULT
Default WebRTC skip STUN flag (false = use STUN).
Definition options.h:677
#define OPT_ACDS_EXPOSE_IP_DEFAULT
Default ACDS expose IP flag (false = private by default).
Definition options.h:599
#define OPT_COLOR_DEFAULT
Default color setting (COLOR_SETTING_AUTO = smart detection).
Definition options.h:449
#define OPT_NO_AUDIO_MIXER_DEFAULT
Default no audio mixer flag (false = enable mixer).
Definition options.h:513
#define OPT_FLIP_Y_DEFAULT
Default vertical flip state (false = no vertical flip).
Definition options.h:500
#define OPT_SHOW_CAPABILITIES_DEFAULT
Default show terminal capabilities flag.
Definition options.h:440
#define OPT_NO_ENCRYPT_DEFAULT
Default no encrypt flag (false = allow encryption).
Definition options.h:738
#define OPT_QUIET_DEFAULT
Default quiet mode flag (false = logging enabled).
Definition options.h:343
asciichat_error_t options_set_int(const char *name, int value)
Check if an option was explicitly set via command-line.
Definition rcu.c:887
#define OPT_MICROPHONE_INDEX_DEFAULT
Default microphone device index (-1 means system default).
Definition options.h:710
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPT_TURN_SERVERS_DEFAULT
Default TURN server URLs (comma-separated).
Definition options.h:663
#define OPT_ENCODE_AUDIO_DEFAULT
Default audio encoding state (true = Opus encoding enabled).
Definition options.h:728
#define OPT_COLOR_MODE_DEFAULT
Default color mode (auto-detect terminal capabilities).
Definition options.h:428
#define OPT_PALETTE_TYPE_DEFAULT
Default palette type (standard ASCII art).
Definition options.h:462
#define OPT_RECONNECT_ATTEMPTS_DEFAULT
Default reconnect attempts (-1 means auto/infinite).
Definition options.h:581
#define OPT_SPEAKERS_VOLUME_DEFAULT
Default speakers volume (1.0 = normal volume).
Definition options.h:719
#define OPT_NO_AUTH_DEFAULT
Default no auth flag (false = allow authentication).
Definition options.h:741
#define OPT_TEST_PATTERN_DEFAULT
Default test pattern mode (false = use actual webcam).
Definition options.h:510
#define OPT_WEBRTC_ICE_TIMEOUT_MS_DEFAULT
Default WebRTC ICE gathering timeout in milliseconds (10 seconds).
Definition options.h:686
#define OPT_COMPRESSION_LEVEL_DEFAULT
Default compression level (1-9).
Definition options.h:584
#define OPT_ENCRYPT_ENABLED_DEFAULT
Default encrypt enabled flag (true = encryption required).
Definition options.h:735
#define OPT_REQUIRE_SERVER_IDENTITY_DEFAULT
Default require-server-identity setting for ACDS.
Definition options.h:605
#define OPT_ENABLE_KEEPAWAKE_DEFAULT
Default keep-awake (prevent system sleep) flag (false = normal system sleep).
Definition options.h:330
#define OPT_RENDER_MODE_DEFAULT
Default render mode (foreground characters only).
Definition options.h:459
#define OPT_ACDS_PORT_INT_DEFAULT
Default ACDS discovery service port (integer).
Definition options.h:593
#define OPT_AUDIO_ENABLED_DEFAULT
Default audio enabled flag (true = audio enabled by default).
Definition options.h:702
#define OPT_MATRIX_RAIN_DEFAULT
Default Matrix rain effect flag (false = disabled).
Definition options.h:491
#define OPT_FORCE_UTF8_DEFAULT
Default force UTF-8 support setting (auto-detect).
Definition options.h:443
#define OPT_STRING_EMPTY_DEFAULT
Default empty string for string option fields that have no configured value.
Definition options.h:766
#define OPT_STUN_SERVERS_DEFAULT
Default STUN server URLs (comma-separated).
Definition options.h:660
#define OPT_GREP_PATTERN_DEFAULT
Default grep pattern (empty = no filtering).
Definition options.h:359
#define OPT_HELP_DEFAULT
Default help flag (false = don't show help).
Definition options.h:312
asciichat_error_t validate_glyph_palette(const options_t *opts)
Definition validation.c:25
#define OPT_ADDRESS6_DEFAULT
Default IPv6 server address.
Definition options.h:539
#define OPT_SPLASH_DEFAULT
Default splash screen flag (true = show splash, false = hide splash).
Definition options.h:318
#define OPT_MEDIA_FROM_STDIN_DEFAULT
Default media from stdin flag (false = not reading from stdin).
Definition options.h:523
#define OPT_AUDIO_ANALYSIS_ENABLED_DEFAULT
Default audio analysis enabled flag.
Definition options.h:722
const terminal_options_t * options_terminal_settings_ptr(void)
Definition rcu.c:519
asciichat_error_t options_set_double(const char *name, double value)
Definition rcu.c:898
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
#define OPT_VERSION_DEFAULT
Default version flag (false = don't show version).
Definition options.h:315
#define OPT_ACDS_DEFAULT
Default ACDS registration flag (false = disabled).
Definition options.h:590
#define OPT_NO_COMPRESS_DEFAULT
Default no compression flag (false = enable compression).
Definition options.h:587
#define OPT_AUTO_HEIGHT_DEFAULT
Default auto-detect height flag (true = auto-detect from terminal).
Definition options.h:425
#define ASCII_RENDERER_DEFAULT
Consolidated options structure.
Definition options.h:962
#define OPT_LOG_TEMPLATE_DEFAULT
Default log template string (selected based on build mode).
Definition options.h:386
#define OPT_REQUIRE_CLIENT_VERIFY_DEFAULT
Default require client verify flag (false = not required).
Definition options.h:747
#define OPT_AUDIO_NO_PLAYBACK_DEFAULT
Default audio playback flag (false = enable playback).
Definition options.h:725
#define OPT_PAUSE_DEFAULT
Default pause media flag (false = play immediately).
Definition options.h:529
#define OPT_REQUIRE_SERVER_VERIFY_DEFAULT
Default require server verify flag (false = not required).
Definition options.h:744
#define OPT_NO_MDNS_ADVERTISE_DEFAULT
Default no mDNS advertise flag (false = advertise enabled).
Definition options.h:614
#define OPT_AUDIO_SOURCE_DEFAULT
Visualize all available sources by default.
Definition options.h:705
asciichat_error_t options_set_string(const char *name, const char *value)
Definition rcu.c:901
asciichat_error_t options_set_bool(const char *name, bool value)
Definition rcu.c:895
#define OPT_COLOR_FILTER_DEFAULT
Default color filter (none - no filtering).
Definition options.h:456
#define OPT_WEBCAM_INDEX_DEFAULT
Default webcam device index.
Definition options.h:507
#define OPT_HEIGHT_DEFAULT
Default terminal height in characters.
Definition options.h:419
#define OPT_SNAPSHOT_MODE_DEFAULT
Default snapshot mode flag (false = continuous).
Definition options.h:474
#define OPT_COLOR_SCHEME_NAME_DEFAULT
Default color scheme name (pastel).
Definition options.h:365
#define OPT_MEDIA_LOOP_DEFAULT
Default loop media flag (false = play once).
Definition options.h:520
#define OPT_NO_CHECK_UPDATE_DEFAULT
Default no-check-update flag (false = check for updates enabled).
Definition options.h:336
#define OPT_STRETCH_DEFAULT
Default allow aspect ratio distortion flag.
Definition options.h:468
#define OPT_STATUS_SCREEN_DEFAULT
Default status screen flag (true = show status, false = hide status).
Definition options.h:324
#define OPT_LAN_DISCOVERY_DEFAULT
Default LAN discovery flag (false = discovery disabled).
Definition options.h:611
#define OPT_AUTO_WIDTH_DEFAULT
Default auto-detect width flag (true = auto-detect from terminal).
Definition options.h:422
#define OPT_JSON_DEFAULT
Default JSON logging flag (false = text output).
Definition options.h:362
#define OPT_ACDS_INSECURE_DEFAULT
Default ACDS insecure mode flag (false = verify server).
Definition options.h:602
#define OPT_FPS_DEFAULT
Default FPS (frames per second).
Definition options.h:471
#define OPT_REQUIRE_CLIENT_IDENTITY_DEFAULT
Default require-client-identity setting for ACDS.
Definition options.h:608
#define OPT_DISABLE_KEEPAWAKE_DEFAULT
Default disable keep-awake flag (false = allow system sleep prevention).
Definition options.h:333
#define OPT_ENABLE_UPNP_DEFAULT
Default enable UPnP flag (false = UPnP disabled).
Definition options.h:617
#define OPT_TURN_CREDENTIAL_DEFAULT
Default TURN credential (empty = use ACDS credentials).
Definition options.h:695
#define OPT_WEBRTC_SKIP_HOST_DEFAULT
Default WebRTC skip host candidates flag (false = use host candidates).
Definition options.h:683
#define OPT_VERBOSE_LEVEL_DEFAULT
Default verbose level (0 = not verbose).
Definition options.h:353
#define OPT_LOG_FORMAT_CONSOLE_DEFAULT
Default log format console only flag (false = use default format everywhere).
Definition options.h:393
#define OPT_SNAPSHOT_DELAY_DEFAULT
Default snapshot delay in seconds.
Definition options.h:487
#define OPT_LOG_LEVEL_DEFAULT
Default log level (LOG_INFO).
Definition options.h:356
#define OPT_MICROPHONE_SENSITIVITY_DEFAULT
Default microphone sensitivity (1.0 = normal volume).
Definition options.h:716
#define OPT_FLIP_X_DEFAULT
Webcam input is mirrored unless an orientation is explicitly selected.
Definition options.h:497
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
#define OPT_MAX_CLIENTS_DEFAULT
Default maximum concurrent clients (server only).
Definition options.h:578
#define OPT_PREFER_WEBRTC_DEFAULT
Default prefer WebRTC flag (false = try direct TCP first).
Definition options.h:671
options_t options_t_new(void)
Initialize options by parsing command-line arguments.
Definition options.c:643
#define OPT_WEBRTC_DISABLE_TURN_DEFAULT
Default WebRTC disable TURN flag (false = use TURN).
Definition options.h:680
#define OPT_NO_WEBRTC_DEFAULT
Default no WebRTC flag (false = WebRTC enabled).
Definition options.h:674
#define OPT_ADDRESS_DEFAULT
Default server address for client connections.
Definition options.h:536
#define OPT_AUDIO_CAPTURE_SOURCE_DEFAULT
Preserve automatic local audio capture selection by default.
Definition options.h:707
#define OPT_PALETTE_CUSTOM_SET_DEFAULT
Default custom palette set flag (false = not set).
Definition options.h:465
#define OPT_TURN_USERNAME_DEFAULT
Default TURN username (empty = use ACDS credentials).
Definition options.h:692
#define OPT_SPEAKERS_INDEX_DEFAULT
Default speakers device index (-1 means system default).
Definition options.h:713
#define OPT_WEBSOCKET_PORT_SERVER_DEFAULT
Default WebSocket port for server mode (integer).
Definition options.h:565
#define OPT_MEDIA_SEEK_TIMESTAMP_DEFAULT
Default media seek timestamp (start from beginning).
Definition options.h:526
#define OPT_WIDTH_DEFAULT
Default terminal width in characters.
Definition options.h:408
@ MODE_INVALID
Invalid mode.
Definition options.h:924
@ AUDIO_SOURCE_MEDIA
Definition options.h:285
@ AUDIO_SOURCE_ALL
Definition options.h:279
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Shared structures and macros for registry implementation.
📝 Logging API with multiple log levels and terminal output control
🔢 Mathematical Utility Functions
bool auto_height
bool auto_width
@ OPTIONS_CYCLE
@ OPTIONS_ADD
@ OPTIONS_TOGGLE
@ OPTIONS_ASSIGN
options_value_type_t
@ OPTIONS_VALUE_DOUBLE
@ OPTIONS_VALUE_INT
@ OPTIONS_VALUE_BOOL
@ OPTIONS_VALUE_STRING
options_origin_t
@ OPTIONS_ORIGIN_CONFIG
#define OPTIONS_PATCH_MAX_EDITS
#define OPTIONS_REVISION_ANY
Validation functions for options parsing.
static bool size_t index
Definition queries.h:8
if(!queries||!out||index >=DATABASE_QUERY_COUNT) return false
uint64_t options_revision(void)
Definition rcu.c:869
size_t options_retired_snapshot_count(void)
Definition rcu.c:316
asciichat_error_t options_adjust(const char *name, double amount)
Definition rcu.c:907
char * options_values_json(const options_t *values, bool remote_only)
Definition rcu.c:1001
struct retired_options retired_options_t
Deferred free list for old options structs.
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:465
asciichat_error_t options_prepare_patch(const options_t *current, const options_patch_t *patch, options_t *candidate, bool remote_only)
Definition rcu.c:771
asciichat_error_t options_state_init(void)
Initialize RCU options system.
Definition rcu.c:374
asciichat_error_t options_prepare_json(const options_t *current, const char *json, size_t length, options_t *candidate, bool remote_only)
Definition rcu.c:977
asciichat_error_t options_apply_patch(const options_patch_t *patch, options_patch_result_t *result)
Definition rcu.c:826
asciichat_error_t options_toggle(const char *name)
Definition rcu.c:904
asciichat_error_t options_read_snapshot(options_snapshot_t *snapshot)
Definition rcu.c:858
asciichat_error_t options_apply_json(const char *json, size_t length, uint64_t expected_revision, options_origin_t origin, options_patch_result_t *result)
Definition rcu.c:989
asciichat_error_t options_cycle(const char *name, int count)
Definition rcu.c:910
#define FIELD(name, type, cli)
Definition rcu.c:548
bool options_remote_render_field(const char *name)
Definition rcu.c:655
asciichat_error_t options_state_set(const options_t *opts)
Set options from a parsed options struct.
Definition rcu.c:443
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:110
options_operation_t operation
const char * string
const char * name
union options_edit_t::@262352151300275353235176125230070205337075074271 value
options_value_type_t type
const options_edit_t * edits
uint64_t expected_revision
options_origin_t origin
options_origin_t origin
bool snapshot_mode
Snapshot mode (one frame and exit).
Definition options.h:1142
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor).
Definition options.h:1084
int force_utf8
UTF-8 support setting (auto/true/false).
Definition options.h:1089
bool fft
Replace the video image with a live audio frequency spectrogram.
Definition options.h:1117
bool palette_explicit
Palette explicitly selected.
Definition options.h:1223
audio_source_t audio_source
Visualization source (all/call/mic/media).
Definition options.h:1114
int height
Terminal height in characters (int for OPTION_TYPE_INT compat).
Definition options.h:992
bool matrix_rain
Matrix digital rain effect (false = disabled).
Definition options.h:1145
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
terminal_render_mode_t render_mode
Render mode (foreground/background/half-block).
Definition options.h:1087
bool media_input
Active input is a file/URL rather than the webcam.
Definition options.h:1097
bool stabilize
Reduce frame-to-frame character flicker.
Definition options.h:1131
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
bool waveform
Replace the video image with a live audio waveform.
Definition options.h:1116
int width
Terminal width in characters (int for OPTION_TYPE_INT compat).
Definition options.h:991
int color
Color setting (COLOR_SETTING_AUTO/TRUE/FALSE).
Definition options.h:1083
bool flip_x
Effective horizontal orientation.
Definition options.h:1095
Registry entry - stores option definition with mode bitmask and metadata.
Deferred free list for old options structs.
Definition rcu.c:294
struct retired_options * next
Definition rcu.c:296
options_t * value
Definition rcu.c:295
options_value_type_t type
Definition rcu.c:539
size_t offset
Definition rcu.c:540
const char * name
Definition rcu.c:538
const char * cli
Definition rcu.c:541
size_t size
Definition rcu.c:540
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...
pid_t platform_get_pid(void)
Definition system.c:67