ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
runtime.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define STATS_RUNTIME_TRANSPORT_BUFFER_SIZE 16
4#define STATS_RUNTIME_STATE_BUFFER_SIZE 64
5#define STATS_RUNTIME_OUTPUT_BUFFER_SIZE 8192
6#define STATS_RUNTIME_FIRST_USE_PATH_BUFFER_SIZE 4096
7#define STATS_RUNTIME_FIRST_USE_MESSAGE_BUFFER_SIZE 512
8
9/* Existing buffer budgets in bytes, including NUL for text storage. */
10#define STATS_PEER_CAPACITY 64
11
12#include <ascii-chat/common.h>
16#include <ascii-chat/otel.h>
28#include <ctype.h>
29#include <libplatform/atomic.h>
30#include <libplatform/compiler.h>
31#include <libplatform/filesystem.h>
32#include <libplatform/system.h>
33#include <libplatform/systemd.h>
34#include <libplatform/terminal.h>
35#include <libplatform/thread.h>
36#include <math.h>
37#include <options/options.h>
38#include <stdarg.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42
55
56static stats_scope_t *g_scope;
57static stats_sampler_t *g_sampler;
58static mutex_t g_peers_mutex, g_provider_mutex;
59static stats_peer_t *g_peers[STATS_PEER_CAPACITY];
60static uint64_t g_peer_id, g_peer_count;
61static stats_provider_fn g_provider;
62static void *g_provider_data;
63static char g_mode[STATS_RUNTIME_MODE_BUFFER_SIZE],
65static unsigned g_interval;
66static atomic_t g_stop, g_active, g_onboarding_wait;
67static platform_thread_t g_worker;
68static bool g_started, g_keyboard;
69static int g_fd;
70static atomic_t g_media_width, g_media_height, g_media_position,
71 g_media_duration;
72void stats_runtime_media(unsigned width, unsigned height, double position,
73 double duration) {
74 if (!g_scope)
75 return;
76 atomic_store_u64_impl(&g_media_width, width);
77 atomic_store_u64_impl(&g_media_height, height);
78 atomic_store_u64_impl(&g_media_position,
79 isfinite(position) && position >= 0 && position < 1e12
80 ? (uint64_t)(position * 1000) + 1
81 : 0);
82 atomic_store_u64_impl(&g_media_duration,
83 isfinite(duration) && duration > 0 && duration < 1e12
84 ? (uint64_t)(duration * 1000) + 1
85 : 0);
86}
87
88stats_scope_t *stats_runtime_scope(void) { return g_scope; }
90 return peer ? peer->scope : NULL;
91}
98
100 if (g_started && g_keyboard) {
101 bool active = !stats_runtime_active();
102 atomic_store_bool_impl(&g_active, active);
104 log_debug("Statistics TUI requested: %s", active ? "open" : "closed");
105 }
106}
107
108static void stats_view_vadd(stats_view_t *view, bool heading,
109 const char *format, va_list args) {
110 if (view->count >= STATS_VIEW_LINES)
111 return;
112 vsnprintf(view->lines[view->count], sizeof(view->lines[0]), format, args);
113 // Provider labels must never inject terminal controls.
114 for (char *p = view->lines[view->count]; *p; ++p)
115 if ((unsigned char)*p < 32 || (unsigned char)*p > 126)
116 *p = '?';
117 view->headings[view->count++] = heading;
118}
119
120void stats_view_add(stats_view_t *view, const char *format, ...) {
121 va_list args;
122 va_start(args, format);
123 stats_view_vadd(view, false, format, args);
124 va_end(args);
125}
126
127void stats_view_add_header(stats_view_t *view, const char *format, ...) {
128 va_list args;
129 va_start(args, format);
130 stats_view_vadd(view, true, format, args);
131 va_end(args);
132}
133
135 if (!g_scope)
136 return;
137 mutex_lock(&g_provider_mutex);
138 g_provider = provider;
139 g_provider_data = data;
140 mutex_unlock(&g_provider_mutex);
141}
142
143void stats_runtime_connection_state(const char *state) {
144 if (!g_scope)
145 return;
146 mutex_lock(&g_provider_mutex);
147 snprintf(g_state, sizeof(g_state), "%s", state);
148 mutex_unlock(&g_provider_mutex);
149}
150
151static stats_capabilities_t network_capabilities(void) {
152 stats_capabilities_t caps = {0};
154 ++i)
155 caps.counters[i] = true;
158 return caps;
159}
160
161stats_peer_t *stats_runtime_peer_open(const char *transport) {
162 if (!g_scope)
163 return NULL;
164 stats_peer_t *peer = SAFE_CALLOC(1, sizeof(*peer), stats_peer_t *);
165 if (!peer)
166 return NULL;
167 stats_capabilities_t caps = network_capabilities();
169 if (stats_scope_create(&caps, &peer->scope) != ASCIICHAT_OK ||
170 stats_sampler_create(&config, &peer->sampler) != ASCIICHAT_OK) {
172 SAFE_FREE(peer);
173 return NULL;
174 }
175 snprintf(peer->transport, sizeof(peer->transport), "%s", transport);
176 mutex_lock(&g_peers_mutex);
177 peer->id = ++g_peer_id;
178 ++g_peer_count;
179 stats_gauge_set(g_scope, STATS_GAUGE_CONNECTIONS_ACTIVE, g_peer_count);
180 for (unsigned i = 0; i < STATS_PEER_CAPACITY; ++i) {
181 if (!g_peers[i]) {
182 g_peers[i] = peer;
183 break;
184 }
185 }
186 mutex_unlock(&g_peers_mutex);
187 return peer;
188}
189
191 if (!peer)
192 return;
193 mutex_lock(&g_peers_mutex);
194 for (unsigned i = 0; i < STATS_PEER_CAPACITY; ++i)
195 if (g_peers[i] == peer)
196 g_peers[i] = NULL;
197 --g_peer_count;
198 stats_gauge_set(g_scope, STATS_GAUGE_CONNECTIONS_ACTIVE, g_peer_count);
199 mutex_unlock(&g_peers_mutex);
202 SAFE_FREE(peer);
203}
204
205void stats_runtime_packet(stats_peer_t *peer, unsigned type,
206 size_t payload_bytes, bool sent, bool success) {
207 if (success) {
208 ascii_otel_metric(sent ? ASCII_OTEL_METRIC_NET_TX_SIZE
209 : ASCII_OTEL_METRIC_NET_RX_SIZE,
210 (double)payload_bytes);
211 }
212 if (sent && type == PACKET_TYPE_ERROR_MESSAGE)
214 stats_scope_t *scopes[] = {g_scope, peer ? peer->scope : NULL};
215 for (unsigned i = 0; i < 2; ++i) {
216 if (!success) {
218 scopes[i],
220 continue;
221 }
223 scopes[i],
225 stats_counter_add(scopes[i],
228 sizeof(packet_header_t) + payload_bytes);
229 if (type == PACKET_TYPE_ASCII_FRAME || type == PACKET_TYPE_IMAGE_FRAME ||
233 scopes[i],
235 }
236}
237
238static void build_view(stats_view_t *view, stats_snapshot_t *snapshot,
239 stats_rates_t *rates) {
240 snprintf(view->mode, sizeof(view->mode), "%s", g_mode);
241 view->sampled_ns = snapshot->sampled_ns;
242 if (!view->page) {
243 stats_view_add(view, "Uptime %.1fs",
244 (double)(snapshot->sampled_ns - snapshot->started_ns) / 1e9);
245 stats_view_add_header(view, "%-28s %14s %14s",
246 strcmp(g_mode, "mcp-server") == 0
247 ? "MCP REQUESTS / RENDERS"
248 : "PIPELINE / NETWORK",
249 "TOTAL", "PER SECOND");
250 for (int i = 0; i < STATS_COUNTER_COUNT; ++i) {
251 if (!snapshot->capabilities.counters[i])
252 continue;
253 const stats_descriptor_t *descriptor = stats_counter_descriptor(i);
254 if (rates->ready)
255 stats_view_add(view, "%-28s %14llu %14.1f", descriptor->name,
256 (unsigned long long)snapshot->counters[i],
257 rates->counters_per_second[i]);
258 else
259 stats_view_add(view, "%-28s %14llu %14s", descriptor->name,
260 (unsigned long long)snapshot->counters[i], "warming up");
261 }
262 stats_view_add(view, "");
263 stats_view_add_header(view, "%-28s %14s %14s", "TIMINGS", "MEAN/LAST ms",
264 "LIFETIME MAX");
265 for (int i = 0; i < STATS_DURATION_COUNT; ++i) {
266 if (!snapshot->capabilities.durations[i])
267 continue;
268 if (i == STATS_DURATION_ASCII_CONVERT && strcmp(g_mode, "client") == 0 &&
269 !snapshot->durations[i].observations)
270 stats_view_add(view, "%-28s %14s %14s", "ascii_convert", "n/a (server)",
271 "n/a");
272 else if (i == STATS_DURATION_CONNECTION_SETUP &&
273 snapshot->durations[i].observations)
274 stats_view_add(view, "%-28s %14.3f %14.3f", "connection_setup (last)",
275 (double)snapshot->durations[i].last_ns / 1e6,
276 (double)snapshot->durations[i].max_ns / 1e6);
277 else if (rates->duration_valid[i])
278 stats_view_add(view, "%-28s %14.3f %14.3f",
280 rates->duration_mean_ns[i] / 1e6,
281 (double)snapshot->durations[i].max_ns / 1e6);
282 else if (snapshot->durations[i].observations)
283 stats_view_add(view, "%-28s %14s %14.3f",
284 stats_duration_descriptor(i)->name, "idle",
285 (double)snapshot->durations[i].max_ns / 1e6);
286 else
287 stats_view_add(view, "%-28s %14s %14s",
288 stats_duration_descriptor(i)->name, "not sampled",
289 "not sampled");
290 }
291 stats_view_add(view, "");
292 for (int i = 0; i < STATS_GAUGE_COUNT; ++i)
293 if (snapshot->capabilities.gauges[i])
294 stats_view_add(view, "%s: %llu", stats_gauge_descriptor(i)->name,
295 (unsigned long long)snapshot->gauges[i]);
296 uint64_t source_width = atomic_load_u64_impl(&g_media_width);
297 if (source_width) {
298 stats_view_add(view, "Source: %llux%llu Output: %ux%u Target: %d fps",
299 (unsigned long long)source_width,
300 (unsigned long long)atomic_load_u64_impl(&g_media_height),
302 uint64_t position = atomic_load_u64_impl(&g_media_position),
303 duration = atomic_load_u64_impl(&g_media_duration);
304 if (position && duration)
305 stats_view_add(view, "Media position: %.1fs / %.1fs",
306 (double)(position - 1) / 1000,
307 (double)(duration - 1) / 1000);
308 else
309 stats_view_add(view, "Media position: unavailable (live source)");
310 }
311 if (strcmp(g_mode, "discovery-service") != 0 &&
312 strcmp(g_mode, "mcp-server") != 0)
313 stats_view_add(view, "Audio: %s Recording: %s",
314 GET_OPTION(audio_enabled) ? "enabled" : "disabled",
315 GET_OPTION(render_file)[0] ? "enabled" : "disabled");
316 if (strcmp(g_mode, "mirror") != 0 && strcmp(g_mode, "mcp-server") != 0) {
317 stats_view_add(view, "Bytes: ACIP header + payload, excluding "
318 "transport/encryption overhead.");
319 stats_view_add(view, "RTT includes uniquely matched probes only; "
320 "unanswered probes are excluded.");
321 }
322 }
323 mutex_lock(&g_peers_mutex);
324 unsigned peers = 0;
325 if (view->page && strcmp(g_mode, "mcp-server") != 0)
326 stats_view_add_header(view, "%-5s %-12s %12s %12s %10s %10s", "ID",
327 "TRANSPORT", "TX bytes/s", "RX bytes/s", "TX fps",
328 "RX fps");
329 for (unsigned i = 0; i < STATS_PEER_CAPACITY; ++i) {
330 stats_peer_t *peer = g_peers[i];
331 if (!peer)
332 continue;
333 peers++;
335 stats_rates_t pr;
336 stats_scope_snapshot(peer->scope, &ps);
337 stats_sampler_update(peer->sampler, &ps, &pr);
338 if (view->page)
339 stats_view_add(view, "%-5llu %-12s %12.0f %12.0f %10.1f %10.1f",
340 (unsigned long long)peer->id, peer->transport,
345 }
346 stats_gauge_set(g_scope, STATS_GAUGE_CONNECTIONS_ACTIVE, g_peer_count);
347 mutex_unlock(&g_peers_mutex);
348 if (view->page && strcmp(g_mode, "mcp-server") != 0)
349 stats_view_add(view,
350 "%u transport handles shown (up to 64); process totals "
351 "include all peers.",
352 peers);
353 mutex_lock(&g_provider_mutex);
354 if (g_state[0])
355 stats_view_add(view, "State: %s", g_state);
356 if (g_provider)
357 g_provider(view, g_provider_data);
358 mutex_unlock(&g_provider_mutex);
359}
360
361static void sample_hidden_peers(void) {
362 mutex_lock(&g_peers_mutex);
363 for (unsigned i = 0; i < STATS_PEER_CAPACITY; ++i) {
364 stats_peer_t *peer = g_peers[i];
365 if (!peer)
366 continue;
367 stats_snapshot_t snapshot;
368 stats_rates_t rates;
369 stats_scope_snapshot(peer->scope, &snapshot);
370 stats_sampler_update(peer->sampler, &snapshot, &rates);
371 }
372 mutex_unlock(&g_peers_mutex);
373}
374
375static bool summary_append(char *output, size_t capacity, size_t *used,
376 const char *format, ...) {
377 if (*used >= capacity)
378 return false;
379 va_list args;
380 va_start(args, format);
381 int written = vsnprintf(output + *used, capacity - *used, format, args);
382 va_end(args);
383 if (written < 0)
384 return false;
385 if ((size_t)written >= capacity - *used) {
386 *used = capacity - 1;
387 return false;
388 }
389 *used += (size_t)written;
390 return true;
391}
392
393static void print_summary(const stats_snapshot_t *snapshot,
394 const stats_rates_t *rates) {
396 size_t used = 0;
397 // Reserve the final byte for the newline, even if a field is truncated.
398 size_t capacity = sizeof(output) - 1;
399 if (!summary_append(
400 output, capacity, &used, "stats mode=%s uptime_s=%.3f", g_mode,
401 (double)(snapshot->sampled_ns - snapshot->started_ns) / 1e9))
402 goto done;
403 for (int i = 0; i < STATS_COUNTER_COUNT; ++i)
404 if (snapshot->capabilities.counters[i] &&
405 !summary_append(output, capacity, &used, " %s=%llu %s_per_s=%.3f",
407 (unsigned long long)snapshot->counters[i],
409 rates->counters_per_second[i]))
410 goto done;
411 for (int i = 0; i < STATS_GAUGE_COUNT; ++i)
412 if (snapshot->capabilities.gauges[i] &&
413 !summary_append(output, capacity, &used, " %s=%llu",
414 stats_gauge_descriptor(i)->name,
415 (unsigned long long)snapshot->gauges[i]))
416 goto done;
417 for (int i = 0; i < STATS_DURATION_COUNT; ++i) {
418 if (!snapshot->capabilities.durations[i])
419 continue;
420 bool appended =
421 rates->duration_valid[i]
422 ? summary_append(output, capacity, &used, " %s_mean_ms=%.3f",
424 rates->duration_mean_ns[i] / 1e6)
425 : summary_append(output, capacity, &used, " %s_mean_ms=unavailable",
427 if (!appended)
428 goto done;
429 }
430done:
431 output[used++] = '\n';
432 ui_controller_write(STDOUT_FILENO, output, used);
433}
434
435static bool show_first_use_instructions(void) {
436 if (!g_keyboard || GET_OPTION(snapshot_mode) || GET_OPTION(render_file)[0] ||
437 !platform_isatty(STDERR_FILENO))
438 return false;
439 const char *title = NULL, *text = NULL;
440 if (!strcmp(g_mode, "mirror")) {
441 title = "Mirror mode";
442 text = "Preview your camera locally.\n\n?\tShow keyboard shortcuts";
443 } else if (!strcmp(g_mode, "client")) {
444 title = "Client mode";
445 text = "Connect to a server with ascii-chat client <address>.\n\n?\tShow "
446 "keyboard shortcuts";
447 } else if (!strcmp(g_mode, "discovery")) {
448 title = "Discovery mode";
449 text = "Start without a name to create a session. Share its name to invite "
450 "others. "
451 "Join with ascii-chat <session-name>.\n\n?\tShow keyboard shortcuts";
452 } else if (!strcmp(g_mode, "server")) {
453 title = "Server mode";
454 text = "Share this server's address and port with participants.\n\n?\tShow "
455 "keyboard shortcuts";
456 } else if (!strcmp(g_mode, "discovery-service")) {
457 title = "Discovery service mode";
458 text = "Help participants find sessions. Configure clients to use this "
459 "service's address and port."
460 "\n\n?\tShow keyboard shortcuts";
461 } else if (!strcmp(g_mode, "mcp-server")) {
462 title = "MCP server mode";
463 text = "Expose rendering tools to MCP clients. Configure an MCP client to "
464 "connect."
465 "\n\n?\tShow keyboard shortcuts";
466 }
467 if (!text)
468 return false;
470 const char *disabled = platform_getenv("ASCII_CHAT_DISABLE_FIRST_USE");
471 if (disabled && !strcmp(disabled, "1")) {
473 return false;
474 }
475 const char *override = platform_getenv("ASCII_CHAT_FIRST_USE_DIR");
476 char *dir = override && *override ? platform_strdup(override)
478 if (!dir) {
480 return false;
481 }
483 int length = snprintf(marker_path, sizeof(marker_path), "%s/first-use-%s",
484 dir, g_mode);
486 snprintf(message, sizeof(message), "%s", text);
487 bool shown =
488 length > 0 && (size_t)length < sizeof(marker_path) &&
489 !platform_is_regular_file(marker_path) &&
491 ui_notice_present_first_use(title, message, marker_path) == ASCIICHAT_OK;
492 SAFE_FREE(dir);
494 return shown;
495}
496
497static void *stats_worker(void *unused) {
498 (void)unused;
499 uint64_t next_sample = 0,
500 next_print = time_get_ns() + (uint64_t)g_interval * NS_PER_SEC_INT;
501 unsigned page = 0;
502 size_t last_count = 0;
503 ui_viewport_t viewport = {0};
504 bool was_active = false;
505 uint64_t next_telemetry = 0;
506 while (!atomic_load_bool_impl(&g_stop) && !shutdown_is_requested()) {
507 platform_systemd_notify_watchdog();
508 if (strcmp(g_mode, "mirror") == 0) {
509 platform_sleep_ns(10 * NS_PER_MS_INT);
510 continue;
511 }
513 bool active = stats_runtime_active();
514 // Own input only while our screen is visible, or while a server has no
515 // screen.
516 bool server_like = strcmp(g_mode, "server") == 0 ||
517 strcmp(g_mode, "discovery-service") == 0 ||
518 (strcmp(g_mode, "mcp-server") == 0 &&
519 !strcmp(GET_OPTION(mcp_transport), "http"));
520 bool first_use_input =
521 atomic_load_bool_impl(&g_onboarding_wait) &&
525 if (g_keyboard &&
526 (first_use_input || active ||
527 (server_like && !ui_controller_screen_live(UI_SCREEN_STATUS)))) {
528 keyboard_key_t key = ui_input_read_key(
529 first_use_input && screen == UI_SCREEN_HELP ? UI_SCREEN_HELP
531 if (first_use_input && (key == 'q' || key == 3)) {
533 continue;
534 }
535 active = stats_runtime_active();
536 if (active && key == ']') {
538 active = false;
540 } else if (active && (key == '=' || key == KEY_ESCAPE)) {
541 atomic_store_bool_impl(&g_active, false);
542 active = false;
543 } else if (!active && key == '=') {
545 active = stats_runtime_active();
546 } else if (key == '\t' || key == KEY_LEFT || key == KEY_RIGHT) {
547 page = !page;
548 viewport = (ui_viewport_t){0};
549 } else {
550 terminal_size_t size = ui_controller_size();
551 ui_viewport_key(&viewport, last_count,
552 size.rows > 6 ? (size_t)size.rows - 6 : 1, key);
553 }
554 }
555 if (active != was_active)
556 log_debug("Statistics TUI visibility: %d (selected=%d)", active,
558 if (!active && was_active) {
560 if (ui_controller_state().screen < 0) {
561 const char restore[] = "\033[0m\033[2J\033[H\033[?25h";
562 ui_controller_write(g_fd, restore, sizeof(restore) - 1);
563 }
564 }
565 uint64_t now = time_get_ns();
566 if (now >= next_sample || active != was_active) {
567 stats_view_t view = {.page = page};
568 stats_snapshot_t snapshot;
569 stats_rates_t rates;
570 stats_scope_snapshot(g_scope, &snapshot);
571 stats_sampler_update(g_sampler, &snapshot, &rates);
572 bool print_due = g_interval && now >= next_print;
573 bool telemetry_due = ascii_otel_enabled() && now >= next_telemetry;
574 if (active || print_due || telemetry_due) {
575 build_view(&view, &snapshot, &rates);
576 // Providers refresh gauges while building the view.
577 stats_scope_snapshot(g_scope, &snapshot);
578 } else {
579 sample_hidden_peers();
580 }
581 if (telemetry_due)
582 next_telemetry = now + NS_PER_SEC_INT;
583 terminal_size_t size = ui_controller_size();
584 ui_viewport_update(&viewport, view.count,
585 size.rows > 6 ? (size_t)size.rows - 6 : 1);
586 last_count = view.count;
587 view.selected = (unsigned)viewport.selected;
588 view.offset = (unsigned)viewport.first_visible;
589 if (active)
591 tui_stats_render, &view, sizeof(view));
592 if (print_due) {
593 print_summary(&snapshot, &rates);
594 next_print = now + (uint64_t)g_interval * NS_PER_SEC_INT;
595 }
596 next_sample = now + 250 * NS_PER_MS_INT;
597 }
598 was_active = active;
599 platform_sleep_ns(10 * NS_PER_MS_INT);
600 }
602 return NULL;
603}
604
606 unsigned interval_seconds) {
607 if (!mode)
608 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing statistics mode");
609 if (g_started)
610 return ASCIICHAT_OK;
611 bool mcp = strcmp(mode, "mcp-server") == 0;
612 stats_capabilities_t caps = network_capabilities();
613 bool mirror = strcmp(mode, "mirror") == 0,
614 acds = strcmp(mode, "discovery-service") == 0;
615 if (mirror)
616 memset(&caps, 0, sizeof(caps));
617 if (!acds) {
618 for (int i = 0; i <= STATS_COUNTER_FRAMES_DROPPED; ++i)
619 caps.counters[i] = true;
623 caps.counters[STATS_COUNTER_AUDIO_OVERRUNS] = GET_OPTION(audio_enabled);
624 for (int i = 0; i <= STATS_DURATION_TERMINAL_WRITE; ++i)
625 caps.durations[i] = true;
628 GET_OPTION(audio_enabled) && !mirror;
629 if (mirror) {
633 caps.durations[STATS_DURATION_DECODE] = false;
634 }
635 } else {
640 caps.counters[i] = true;
645 }
646 if (strcmp(mode, "discovery") == 0)
648 caps.gauges[STATS_GAUGE_VIDEO_QUEUE_DEPTH] = strcmp(mode, "server") == 0;
649 if (GET_OPTION(render_file)[0]) {
652 }
653 if (!mirror) {
655 caps.durations[STATS_DURATION_RTT] = !acds;
660 }
661 if (mcp) {
662 memset(&caps, 0, sizeof(caps));
663 for (unsigned i = STATS_COUNTER_MCP_REQUESTS;
665 caps.counters[i] = true;
666 for (unsigned i = STATS_COUNTER_HTTP_REQUESTS;
668 caps.counters[i] = true;
673 }
674 asciichat_error_t result = stats_scope_create(&caps, &g_scope);
675 if (result != ASCIICHAT_OK)
676 return result;
679 result = stats_sampler_create(&config, &g_sampler);
680 if (result != ASCIICHAT_OK)
681 goto fail_scope;
682 if (mutex_init(&g_peers_mutex, "stats_peers") != 0) {
683 result = SET_ERRNO(ERROR_THREAD, "Cannot initialize stats peer mutex");
684 goto fail_sampler;
685 }
686 if (mutex_init(&g_provider_mutex, "stats_provider") != 0) {
687 result = SET_ERRNO(ERROR_THREAD, "Cannot initialize stats provider mutex");
688 goto fail_peers;
689 }
690 g_peer_count = g_peer_id = 0;
691 memset(g_peers, 0, sizeof(g_peers));
692 g_state[0] = 0;
693 stats_runtime_media(0, 0, -1, -1);
694 snprintf(g_mode, sizeof(g_mode), "%s", mode);
695 g_interval = interval_seconds;
696 g_fd = platform_isatty(STDOUT_FILENO) ? STDOUT_FILENO : STDERR_FILENO;
697 // Mirror mode has no statistics-screen interaction. Avoid installing the
698 // console reader there so shutdown cannot leave the worker inside a UI
699 // input path while the mirror tears down its display.
700 g_keyboard = !mirror &&
701 (!mcp || !strcmp(GET_OPTION(mcp_transport), "http")) &&
702 platform_isatty(STDIN_FILENO) && platform_isatty(g_fd) &&
703 keyboard_init() == ASCIICHAT_OK;
704 atomic_store_bool_impl(&g_stop, false);
705 atomic_store_bool_impl(&g_active, false);
706 atomic_store_bool_impl(&g_onboarding_wait, false);
707 g_started = true;
708 bool server_like = strcmp(mode, "server") == 0 ||
709 strcmp(mode, "discovery-service") == 0 ||
710 (mcp && !strcmp(GET_OPTION(mcp_transport), "http"));
711 if (g_keyboard && server_like &&
713 LOG_ERRNO_IF_SET("Cannot start terminal presentation");
714 if (platform_thread_create(&g_worker, "stats", stats_worker, NULL) == 0) {
715 atomic_store_bool_impl(&g_onboarding_wait, true);
716 bool shown = show_first_use_instructions();
720 if (state.screen == UI_SCREEN_NOTICE && state.covered)
721 break;
722 platform_sleep_ms(10);
723 }
724 atomic_store_bool_impl(&g_onboarding_wait, false);
725 return ASCIICHAT_OK;
726 }
727 result = SET_ERRNO(ERROR_THREAD, "Cannot start stats worker");
728 g_started = false;
729 if (g_keyboard)
731 mutex_destroy(&g_provider_mutex);
732fail_peers:
733 mutex_destroy(&g_peers_mutex);
734fail_sampler:
735 stats_sampler_destroy(g_sampler);
736 g_sampler = NULL;
737fail_scope:
738 stats_scope_destroy(g_scope);
739 g_scope = NULL;
740 return result;
741}
742
744 if (!g_started)
745 return;
746 atomic_store_bool_impl(&g_stop, true);
747 thread_join(&g_worker, NULL);
749 if (g_keyboard)
751 g_provider = NULL;
752 g_provider_data = NULL;
753 stats_sampler_destroy(g_sampler);
754 stats_scope_destroy(g_scope);
755 g_sampler = NULL;
756 g_scope = NULL;
757 mutex_destroy(&g_provider_mutex);
758 mutex_destroy(&g_peers_mutex);
759 g_started = false;
760}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
void atomic_store_u64_impl(atomic_t *a, uint64_t value)
uint64_t atomic_load_u64_impl(const atomic_t *a)
bool atomic_load_bool_impl(const atomic_t *a)
void atomic_store_bool_impl(atomic_t *a, uint64_t value)
const stats_descriptor_t * stats_duration_descriptor(stats_duration_id_t id)
const stats_descriptor_t * stats_gauge_descriptor(stats_gauge_id_t id)
const stats_descriptor_t * stats_counter_descriptor(stats_counter_id_t id)
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
char * platform_get_data_dir(void)
Definition filesystem.c:101
Buffered terminal frame rendering.
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
#define GET_OPTION(field)
Definition options.h:1339
int keyboard_help_parent_screen(void)
void shutdown_request(void)
Definition common.c:85
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
⚙️ Common definitions, error codes, macros, and types shared throughout the application
@ STATS_COUNTER_RATE_LIMIT_REJECTIONS
@ STATS_COUNTER_MIGRATION_FAILURES
@ STATS_COUNTER_MCP_HTTP_RESPONSES
@ STATS_GAUGE_PARTICIPANTS_ACTIVE
@ STATS_GAUGE_HTTP_CONNECTIONS_ACTIVE
@ STATS_GAUGE_HTTP_STREAMS_ACTIVE
@ STATS_GAUGE_AUDIO_BUFFERED_SAMPLES
@ STATS_DURATION_CONNECTION_SETUP
struct stats_sampler stats_sampler_t
struct stats_scope stats_scope_t
void keyboard_destroy(void)
Definition keyboard.c:15
int keyboard_help_previous_interactive(void)
🆘 Interactive keyboard help overlay for session keyboard shortcuts
void stats_scope_destroy(stats_scope_t *scope)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_sampler_destroy(stats_sampler_t *sampler)
asciichat_error_t stats_scope_snapshot(const stats_scope_t *scope, stats_snapshot_t *out)
stats sampler config keeps the values that move through the subsystem: window_ns, resolution_ns....
asciichat_error_t stats_scope_create(const stats_capabilities_t *capabilities, stats_scope_t **out_scope)
asciichat_error_t stats_sampler_update(stats_sampler_t *sampler, const stats_snapshot_t *snapshot, stats_rates_t *out_rates)
void stats_gauge_set(stats_scope_t *scope, stats_gauge_id_t id, uint64_t value)
asciichat_error_t stats_sampler_create(const stats_sampler_config_t *config, stats_sampler_t **out_sampler)
void tui_stats_render(terminal_size_t size, const void *data)
terminal_size_t tui_stats_minimum(const stats_view_t *view)
🔢 Mathematical Utility Functions
asciichat_error_t ui_notice_present_first_use(const char *title, const char *text, const char *marker_path)
Definition notice.c:450
action_args_t args
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
bool ascii_otel_enabled(void)
Definition otel.c:171
void ascii_otel_stats_attach(stats_scope_t *scope)
Definition otel.c:237
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
stats_scope_t * stats_runtime_peer_scope(stats_peer_t *peer)
Definition runtime.c:89
#define STATS_RUNTIME_TRANSPORT_BUFFER_SIZE
Definition runtime.c:3
void stats_runtime_set_provider(stats_provider_fn provider, void *data)
Definition runtime.c:134
void stats_view_add_header(stats_view_t *view, const char *format,...)
Definition runtime.c:127
#define STATS_RUNTIME_STATE_BUFFER_SIZE
Definition runtime.c:4
void stats_runtime_toggle(void)
Definition runtime.c:99
void stats_runtime_connection_state(const char *state)
Definition runtime.c:143
void stats_runtime_peer_close(stats_peer_t *peer)
Definition runtime.c:190
void stats_runtime_media(unsigned width, unsigned height, double position, double duration)
Definition runtime.c:72
void stats_runtime_stop(void)
Definition runtime.c:743
bool stats_runtime_active(void)
Definition runtime.c:92
#define STATS_RUNTIME_OUTPUT_BUFFER_SIZE
Definition runtime.c:5
#define STATS_RUNTIME_FIRST_USE_MESSAGE_BUFFER_SIZE
Definition runtime.c:7
stats_peer_t * stats_runtime_peer_open(const char *transport)
Definition runtime.c:161
#define STATS_RUNTIME_FIRST_USE_PATH_BUFFER_SIZE
Definition runtime.c:6
void stats_view_add(stats_view_t *view, const char *format,...)
Definition runtime.c:120
void stats_runtime_packet(stats_peer_t *peer, unsigned type, size_t payload_bytes, bool sent, bool success)
Definition runtime.c:205
#define STATS_PEER_CAPACITY
Definition runtime.c:10
asciichat_error_t stats_runtime_start(const char *mode, unsigned interval_seconds)
Definition runtime.c:605
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
Interactive search filtering for terminal screens.
Shutdown check system for clean library/application separation.
char * platform_strdup(const char *s)
#define STATS_VIEW_LINES
#define STATS_RUNTIME_MODE_BUFFER_SIZE
void(* stats_provider_fn)(stats_view_t *view, void *data)
struct stats_peer stats_peer_t
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
stats descriptor is intentionally a small, concrete record. Fields such as name, unit,...
bool counters[STATS_COUNTER_COUNT]
bool durations[STATS_DURATION_COUNT]
When code needs to work with stats peer, it keeps scope, sampler, id here instead of scattering it ac...
Definition runtime.c:49
uint64_t id
Definition runtime.c:53
char transport[16]
Definition runtime.c:52
stats_sampler_t * sampler
Definition runtime.c:51
stats_scope_t * scope
Definition runtime.c:50
double duration_mean_ns[STATS_DURATION_COUNT]
bool duration_valid[STATS_DURATION_COUNT]
double counters_per_second[STATS_COUNTER_COUNT]
stats_capabilities_t capabilities
uint64_t gauges[STATS_GAUGE_COUNT]
uint64_t counters[STATS_COUNTER_COUNT]
stats_duration_snapshot_t durations[STATS_DURATION_COUNT]
uint64_t sampled_ns
char mode[32]
bool headings[128]
unsigned page
char lines[128][160]
unsigned selected
unsigned offset
unsigned count
For ui viewport, this is the live record that ties selected, first_visible, page_size together....
Definition viewport.h:20
size_t first_visible
Definition viewport.h:21
size_t selected
Definition viewport.h:21
const char * platform_getenv(const char *name)
Definition system.c:45
Reusable "fixed header + scrolling logs" terminal screen abstraction.
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t ui_controller_start_terminal(int fd)
void ui_controller_remove(ui_screen_t screen)
void ui_controller_select_interactive(int screen)
asciichat_error_t ui_controller_submit(ui_screen_t screen, int fd, terminal_size_t minimum, ui_render_fn render, const void *snapshot, size_t bytes)
void ui_controller_toggle_logs(void)
int ui_controller_current_screen(void)
terminal_size_t ui_controller_size(void)
void ui_controller_shutdown(void)
int ui_controller_interactive_screen(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
ui_presentation_state_t ui_controller_state(void)
bool ui_controller_screen_live(ui_screen_t screen)
@ UI_SCREEN_NOTICE
@ UI_SCREEN_STATS
@ UI_SCREEN_STATUS
@ UI_SCREEN_HELP
keyboard_key_t ui_input_read_key(ui_screen_t screen)
Definition tui/input.c:374
int platform_isatty(int fd)
Definition util.c:70
int platform_is_regular_file(const char *path)
Definition util.c:136
bool ui_viewport_key(ui_viewport_t *v, size_t count, size_t rows, keyboard_key_t key)
Definition viewport.c:40
ui_viewport_range_t ui_viewport_update(ui_viewport_t *v, size_t count, size_t rows)
Definition viewport.c:4