ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
src/common/session/display.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3
4#include <ascii-chat/otel.h>
19
24#include "session/display.h"
27#include "session/render.h"
29#include <ascii-chat/common.h>
30#include <options/colorscheme.h>
31#include <ascii-chat/log/log.h>
34#include <options/options.h>
35#include <options/runtime.h>
37#include <libplatform/terminal.h>
38#include <libplatform/compiler.h>
39#include <libplatform/system.h>
40#include <libplatform/thread.h>
41#include <libplatform/terminal.h>
60#include <libplatform/cpu.h>
61
62#include <string.h>
63#include <stdio.h>
64#include <libplatform/atomic.h>
65#include <stdlib.h>
66
67/* ============================================================================
68 * Session Display Context Structure
69 * ============================================================================ */
70
144
145// Display conversion and submission have a single owner, so scratch images can be reused.
146static image_t *display_image_workspace(image_t **workspace, int width, int height) {
147 if (*workspace && ((*workspace)->w != width || (*workspace)->h != height)) {
148 image_destroy(*workspace);
149 *workspace = NULL;
150 }
151 if (!*workspace)
152 *workspace = image_new((size_t)width, (size_t)height);
153 return *workspace;
154}
155
156/* ============================================================================
157 * Internal Helper Functions
158 * ============================================================================ */
159
168/* ============================================================================
169 * Session Display Lifecycle Functions
170 * ============================================================================ */
171
173 if (!ctx) {
174 return SET_ERRNO(ERROR_INVALID_PARAM, "Display context is NULL");
175 }
176
177 const char *render_file_opt = GET_OPTION(render_file);
178 if ((!render_file_opt || !render_file_opt[0]) && GET_OPTION(render_kitty))
179 render_file_opt = "--kitty";
180 if (!render_file_opt || render_file_opt[0] == '\0') {
181 return ASCIICHAT_OK;
182 }
183 if (ctx->render_file) {
184 return ASCIICHAT_OK;
185 }
186
187 uint32_t encoder_fps = fps;
188 if (encoder_fps == 0) {
189 encoder_fps = (uint32_t)GET_OPTION(fps);
190 }
191 if (encoder_fps == 0) {
192 encoder_fps = 60;
193 }
194
195 int width = (int)GET_OPTION(width);
196 int height = (int)GET_OPTION(height);
197 ctx->render_fps = encoder_fps;
198
199 log_info("render-file: Initializing encoder after media timing selection: path='%s', grid=%dx%d, fps=%u", render_file_opt, width, height, encoder_fps);
200 asciichat_error_t err = render_file_create(render_file_opt, width, height, (int)encoder_fps, GET_OPTION(render_theme), &ctx->render_file);
201 if (err != ASCIICHAT_OK) {
203 if (HAS_ERRNO(&error))
204 log_error("render-file: %s", error.context_message);
205 log_error("render-file: Failed to create encoder %s", asciichat_error_format(NULL, err));
206 return err;
207 }
208
209 log_info("render-file: Encoder initialized successfully at %u FPS", encoder_fps);
210 return ASCIICHAT_OK;
211}
212
213static void display_sync_entries(session_display_ctx_t *ctx, bool add) {
214 if (add)
215 NAMED_REGISTER_ATOMIC(&ctx->first_frame, "display.first_frame", NULL);
216 else
218 if (add)
219 NAMED_REGISTER_ATOMIC(&ctx->output_failed, "display.output_failed", NULL);
220 else
222}
223
225 ASCII_OTEL_SCOPE(SESSION_DISPLAY_CREATE);
226 if (GET_OPTION(zalgo) > 0 && (GET_OPTION(force_utf8) == UTF8_SETTING_FALSE ||
228 SET_ERRNO(ERROR_USAGE, "--zalgo requires UTF-8 terminal output (on Windows, run chcp 65001 first)");
229 return NULL;
230 }
231 // Auto-create config from command-line options if NULL
232 session_display_config_t auto_config = {0};
233 if (!config) {
234 auto_config.snapshot_mode = GET_OPTION(snapshot_mode);
235 auto_config.palette_type = GET_OPTION(palette_type);
236 auto_config.custom_palette = GET_OPTION(palette_custom_set) ? GET_OPTION(palette_custom) : NULL;
237 auto_config.color_mode = TERM_COLOR_AUTO;
238 config = &auto_config;
239 }
240
241 // Check if we should exit before starting initialization
242 if (config->should_exit_callback && config->should_exit_callback(config->callback_data)) {
243 return NULL;
244 }
245
246 // Allocate context
248
249 // Store configuration
250 ctx->snapshot_mode = config->snapshot_mode;
251 ctx->palette_type = config->palette_type;
253 ctx->audio_ctx = config->audio_ctx;
254 ctx->render_fps = config->render_fps;
255 atomic_store_bool(&ctx->first_frame, true);
256 atomic_store_bool(&ctx->output_failed, false);
257
258 // Get TTY info for direct terminal access
259 ctx->tty_info = get_current_tty();
260
261 // Presentation follows stdout. Opening a separate controlling terminal can
262 // fail under ConPTY even though stdout is an interactive console.
264 const char *stdout_output = GET_OPTION(render_file);
265 bool owns_stdout = GET_OPTION(render_kitty) || strcmp(stdout_output, "--kitty") == 0 || strcmp(stdout_output, "-") == 0 || strcmp(stdout_output, "pipe:") == 0;
266 if (owns_stdout)
267 ctx->has_tty = false;
268 if (ctx->has_tty) {
269 // Retain the terminal before decoder/audio workers redirect process stdio
270 // through LOG_IO. The first media submission must remain interactive too.
271 int output = platform_dup(STDOUT_FILENO);
272 if (output >= 0 && platform_isatty(output)) {
273 if (ctx->tty_info.owns_fd && ctx->tty_info.fd >= 0)
274 platform_close(ctx->tty_info.fd);
275 ctx->tty_info.fd = output;
276 ctx->tty_info.owns_fd = true;
277 } else if (output >= 0) {
278 platform_close(output);
279 }
280 }
281 if (ctx->has_tty && (ctx->tty_info.fd < 0 || !platform_isatty(ctx->tty_info.fd))) {
282 if (ctx->tty_info.owns_fd && ctx->tty_info.fd >= 0)
283 platform_close(ctx->tty_info.fd);
284 ctx->tty_info.fd = STDOUT_FILENO;
285 ctx->tty_info.owns_fd = false;
286 }
287
288 // In piped mode, force all logs to stderr to prevent frame data corruption
291 // Disable buffering for stdout to ensure frames appear immediately
292 // Each frame ends with newline, so unbuffered output is critical for real-time display
293 (void)setvbuf(stdout, NULL, _IONBF, 0);
294 }
295
296 // Also disable buffering for TTY mode to ensure smooth 40+ FPS animation
297 setvbuf(stdout, NULL, _IONBF, 0);
298
299 // Detect terminal capabilities
301
302 // Set wants_padding based on terminal output mode
303 // Enable padding for all rendering modes (including snapshot) to center output
304 // The padding adds newlines at the top, which is useful for visual centering
305 bool is_snapshot_mode = config->snapshot_mode;
306 ctx->caps.wants_padding = true;
307
308 // Calculate pad_height: when padding is enabled, add top padding for centering
309 // Halfblock mode uses 2 source rows per output row, so padding is halved
310 if (ctx->caps.wants_padding) {
311 ctx->caps.pad_height = 5; // Halfblock needs half the padding (10 / 2 = 5)
312 } else {
313 ctx->caps.pad_height = 0;
314 }
315
316 log_debug("Padding mode: wants_padding=%d (snapshot=%d, has_tty=%d, stdin_tty=%d, stdout_tty=%d), pad_height=%zu", ctx->caps.wants_padding, is_snapshot_mode, ctx->has_tty, terminal_is_stdin_tty(),
317 terminal_is_stdout_tty(), ctx->caps.pad_height);
318
319 // Apply color mode override if specified
320 if (config->color_mode != TERM_COLOR_AUTO) {
321 ctx->caps.color_level = config->color_mode;
322 }
323
324 // Apply command-line overrides
326 // The platform capability probe describes what the terminal can do; it must
327 // not replace the user's selected output mode. Keep the application option
328 // authoritative for every local frame, including webcam rendering.
329 ctx->caps.render_mode = (terminal_render_mode_t)GET_OPTION(render_mode);
330
331 // Initialize palette
332 int palette_result = initialize_client_palette(config->palette_type, config->custom_palette, ctx->palette_chars, &ctx->palette_len, ctx->luminance_palette);
333 if (palette_result != ASCIICHAT_OK) {
334 log_warn("Failed to initialize palette, using default");
335 // Fall back to standard palette
337 }
338
339 // Pre-warm UTF-8 palette cache during initialization (not during rendering)
340 // This is expensive on first use (creates lookup tables), so warm it up now to avoid frame lag
341 // This function is imported from lib/video/simd/common.h
342 (void)get_utf8_palette_cache((const char *)ctx->palette_chars);
343 log_debug("UTF-8 palette cache pre-warmed during display initialization");
344
345 // Initialize ANSI fast lookup tables based on terminal capabilities
346 if (ctx->caps.color_level == TERM_COLOR_TRUECOLOR) {
348 } else if (ctx->caps.color_level == TERM_COLOR_256) {
350 } else if (ctx->caps.color_level == TERM_COLOR_16) {
352 }
353 // TERM_COLOR_MONO requires no init
354
355 // Initialize ASCII output system if we have a TTY
356 if (ctx->has_tty && ctx->tty_info.fd >= 0) {
357 ascii_write_init(ctx->tty_info.fd, false);
358 }
359
360 // Initialize digital rain effect if enabled
361 if (GET_OPTION(matrix_rain)) {
362 // Get terminal dimensions for grid size
363 unsigned short int width_us = terminal_get_effective_width(GET_OPTION(width), 80);
364 unsigned short int height_us = terminal_get_effective_height(GET_OPTION(height), 24);
365
366 int width = (int)width_us;
367 int height = (int)height_us;
368
370 if (ctx->digital_rain) {
371 // Set color from color filter if active
372 color_filter_t filter = GET_OPTION(color_filter);
374 log_info("Digital rain effect enabled: %dx%d grid", width, height);
375 } else {
376 log_warn("Failed to initialize digital rain effect");
377 }
378 ctx->last_frame_time_ns = time_get_ns();
379 }
380
383 return NULL;
384 }
385
386 display_sync_entries(ctx, true);
387
388 // Initialize render-file unless media setup needs to determine its timing first.
389 const char *render_file_opt = GET_OPTION(render_file);
390 log_debug("render-file opt='%s' (len=%zu), deferred=%d", render_file_opt ? render_file_opt : "(null)", render_file_opt ? strlen(render_file_opt) : 0, config->defer_render_file);
391 if (!config->defer_render_file) {
393 if (render_err != ASCIICHAT_OK) {
394 log_error("render-file: Initialization failed %s", asciichat_error_format(NULL, render_err));
396 bool has_error = HAS_ERRNO(&error);
398 SET_ERRNO(render_err, "%s", has_error ? error.context_message : "Render-file initialization failed");
399 return NULL;
400 }
401 }
402
403 ctx->initialized = true;
404 if (ctx->has_tty && !ctx->snapshot_mode) {
405 const char initial[] = "\033[H";
406 (void)ui_controller_present_retained(UI_SCREEN_MEDIA, ctx->tty_info.fd, (terminal_size_t){.cols = UI_MEDIA_MIN_COLS, .rows = UI_MEDIA_MIN_ROWS}, initial, sizeof(initial) - 1);
407 }
408
409 return ctx;
410}
411
412void session_display_begin_drain(session_display_ctx_t *ctx, uint64_t total, bool total_known) {
413 if (ctx && ctx->render_file) {
415 render_file_begin_drain(ctx->render_file, total, total_known);
416 }
417}
418
420 if (!ctx || !ctx->render_file)
421 return ASCIICHAT_OK;
423 ctx->render_file = NULL;
424 return err;
425}
426
428 if (!ctx) {
429 SET_ERRNO(ERROR_INVALID_PARAM, "Session display context is NULL");
430 return;
431 }
432
434
437
438 // Cleanup ASCII rendering if we had a TTY
439 // Don't reset terminal in snapshot mode to preserve the rendered output
440 if (ctx->has_tty && ctx->tty_info.fd >= 0) {
442 }
443
444 // Close the controlling terminal if we opened it
445 if (ctx->tty_info.owns_fd && ctx->tty_info.fd >= 0) {
446 (void)platform_close(ctx->tty_info.fd);
447 ctx->tty_info.fd = -1;
448 ctx->tty_info.owns_fd = false;
449 }
450
451 // Cleanup digital rain effect
452 if (ctx->digital_rain) {
454 ctx->digital_rain = NULL;
455 }
456
460 ctx->resize_workspace = ctx->flip_workspace = ctx->filter_workspace = NULL;
465 ctx->initialized = false;
466
467 // Clear the cached display context in splash state to prevent use-after-free
468 // when worker threads try to access the display after it's been freed
470
471 display_sync_entries(ctx, false);
472 SAFE_FREE(ctx);
473}
474
476 if (!ctx) {
477 SET_ERRNO(ERROR_INVALID_PARAM, "Display context is NULL");
478 return;
479 }
480
481 ctx->stdin_reader = (terminal_fd_reader_t *)reader;
482 log_debug("stdin_reader set");
483}
484
485/* ============================================================================
486 * Session Display Query Functions
487 * ============================================================================ */
488
490 if (!ctx || !ctx->initialized) {
491 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
492 return false;
493 }
494 return ctx->has_tty;
495}
496
497const terminal_capabilities_t *session_display_get_caps(session_display_ctx_t *ctx) {
498 if (!ctx || !ctx->initialized) {
499 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
500 return NULL;
501 }
502 return &ctx->caps;
503}
504
506 if (!ctx || !ctx->initialized) {
507 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
508 return NULL;
509 }
510 return ctx->palette_chars;
511}
512
514 if (!ctx || !ctx->initialized) {
515 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
516 return 0;
517 }
518 return ctx->palette_len;
519}
520
522 if (!ctx || !ctx->initialized) {
523 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
524 return NULL;
525 }
526 return ctx->luminance_palette;
527}
528
530 if (!ctx || !ctx->initialized) {
531 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
532 return -1;
533 }
534 return ctx->tty_info.fd;
535}
536
538 if (!ctx || !ctx->initialized) {
539 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
540 return NULL;
541 }
542
543 return ctx->stdin_reader;
544}
545
547 if (!ctx)
548 return 0;
549 return ctx->render_fps;
550}
551
553 if (!ctx)
554 return;
555 ctx->render_fps = fps;
556 if (fps > 0) {
557 log_debug("Updated render FPS to %u (for correct video duration)", fps);
558 }
559}
560
562 if (!ctx) {
563 return false;
564 }
565 // Return true if first_frame flag is false (meaning first frame has been rendered)
566 return !atomic_load_bool(&ctx->first_frame);
567}
568
570 if (!ctx) {
571 return;
572 }
573 // Reset first_frame flag to true so splash screen can be shown again on next render
574 atomic_store_bool(&ctx->first_frame, true);
575}
576
578 if (!ctx) {
579 return false;
580 }
581 return ctx->render_file != NULL;
582}
583
584/* ============================================================================
585 * Session Display ASCII Conversion Functions
586 * ============================================================================ */
587
588static char *convert_to_ascii(session_display_ctx_t *ctx, const image_t *image, bool reuse) {
589 uint64_t stats_start = time_get_ns();
590 if (!ctx) {
591 SET_ERRNO(ERROR_INVALID_PARAM, "ctx is NULL");
592 return NULL;
593 }
594
595 if (!ctx->initialized) {
596 SET_ERRNO(ERROR_INVALID_STATE, "ctx not initialized");
597 return NULL;
598 }
599
600 if (!image) {
601 SET_ERRNO(ERROR_INVALID_PARAM, "image is NULL");
602 return NULL;
603 }
604
605 // Read the renderer and palette from the same committed options revision.
606 options_snapshot_t snapshot;
607 if (options_read_snapshot(&snapshot) != ASCIICHAT_OK) {
608 return NULL;
609 }
610 const options_t *values = &snapshot.values;
611 unsigned short int width = (unsigned short int)values->width;
612 unsigned short int height = (unsigned short int)values->height;
613 bool stretch = values->stretch;
614 terminal_capabilities_t caps_copy = ctx->caps;
615 caps_copy.render_mode = (terminal_render_mode_t)values->render_mode;
616 caps_copy.text_renderer = values->renderer;
617 caps_copy.stabilize = values->stabilize;
618 caps_copy.palette_explicit = values->palette_explicit;
619 terminal_color_mode_t color_mode_opt = (terminal_color_mode_t)values->color_mode;
620 const palette_def_t *builtin = get_builtin_palette(values->palette_type);
621 const char *selected_palette = !values->palette_explicit ? ctx->palette_chars : values->palette_type == PALETTE_CUSTOM ? values->palette_custom : builtin ? builtin->chars : ctx->palette_chars;
622 char palette_chars[ASCII_PALETTE_BUFFER_SIZE];
623 SAFE_STRNCPY(palette_chars, selected_palette, sizeof(palette_chars));
624 bool preserve_aspect_ratio = !stretch;
625
626 // Determine if we should apply flip_x and flip_y
627 // Synthetic test patterns are already oriented for diagnostics. Do not
628 // inherit the webcam's mirrored default unless the user explicitly chose
629 // horizontal flipping.
630 bool flip_x_enabled = GET_OPTION(flip_x);
631 bool flip_y_enabled = GET_OPTION(flip_y);
632
633 color_filter_t color_filter = GET_OPTION(color_filter);
634 if (ctx->stabilizer_filter_initialized && ctx->previous_stabilizer_filter != color_filter) {
637 }
638 ctx->previous_stabilizer_filter = color_filter;
640
641 // Handle dynamic matrix rain effect toggle
642 bool matrix_rain_enabled = GET_OPTION(matrix_rain);
643 if (matrix_rain_enabled && !ctx->digital_rain) {
644 // Initialize digital rain if it's now enabled but wasn't before
645 unsigned short int width_us = terminal_get_effective_width(GET_OPTION(width), 80);
646 unsigned short int height_us = terminal_get_effective_height(GET_OPTION(height), 24);
647 int width_for_rain = (int)width_us;
648 int height_for_rain = (int)height_us;
649 ctx->digital_rain = digital_rain_init(width_for_rain, height_for_rain);
650 if (ctx->digital_rain) {
652 log_info("Matrix rain effect: enabled");
653 }
654 } else if (!matrix_rain_enabled && ctx->digital_rain) {
655 // Disable digital rain if it's now disabled but was enabled before
657 ctx->digital_rain = NULL;
658 log_info("Matrix rain effect: disabled");
659 }
660
661 // Make a mutable copy of terminal capabilities for ascii_convert_with_capabilities
662 if (color_mode_opt != TERM_COLOR_AUTO) {
663 caps_copy.color_level = color_mode_opt;
664 }
665
666 // MEASURE EVERY OPERATION - Debug systematic timing
667 uint64_t t_flip_start = time_get_ns();
668
669 // Apply horizontal and/or vertical flips if requested
670 image_t *flipped_image = NULL;
671 const image_t *display_image = image;
672
673 if ((flip_x_enabled || flip_y_enabled) && image->w > 1 && image->h > 1 && image->pixels) {
674 uint64_t t_flip_alloc_start = time_get_ns();
675 flipped_image = ctx->render_file ? image_new(image->w, image->h) : display_image_workspace(&ctx->flip_workspace, image->w, image->h);
676 uint64_t t_flip_alloc_end = time_get_ns();
677
678 if (flipped_image) {
679 uint64_t t_flip_memcpy_start = time_get_ns();
680 // OPTIMIZATION: Copy entire image first (sequential memory access - cache-friendly)
681 memcpy(flipped_image->pixels, image->pixels, (size_t)image->w * (size_t)image->h * sizeof(rgb_pixel_t));
682 uint64_t t_flip_memcpy_end = time_get_ns();
683
684 uint64_t t_flip_reverse_start = time_get_ns();
685
686 // Apply horizontal flip (X-axis)
687 if (flip_x_enabled) {
688#if SIMD_SUPPORT_NEON
689 if (platform_cpu_features() & CPU_FEATURE_NEON) {
690 image_flip_horizontal_neon(flipped_image);
691 } else
692#endif
693 {
694 for (int y = 0; y < image->h; y++) {
695 rgb_pixel_t *row = &flipped_image->pixels[y * image->w];
696 for (int x = 0; x < image->w / 2; x++) {
697 rgb_pixel_t temp = row[x];
698 row[x] = row[image->w - 1 - x];
699 row[image->w - 1 - x] = temp;
700 }
701 }
702 }
703 }
704
705 // Apply vertical flip (Y-axis)
706 if (flip_y_enabled) {
707 for (int y = 0; y < image->h / 2; y++) {
708 rgb_pixel_t *top_row = &flipped_image->pixels[y * image->w];
709 rgb_pixel_t *bottom_row = &flipped_image->pixels[(image->h - 1 - y) * image->w];
710 for (int x = 0; x < image->w; x++) {
711 rgb_pixel_t temp = top_row[x];
712 top_row[x] = bottom_row[x];
713 bottom_row[x] = temp;
714 }
715 }
716 }
717
718 uint64_t t_flip_reverse_end = time_get_ns();
719 display_image = flipped_image;
720
721 log_dev("TIMING_FLIP: alloc=%llu us, memcpy=%llu us, flip=%llu us (x=%d, y=%d)", (t_flip_alloc_end - t_flip_alloc_start) / 1000, (t_flip_memcpy_end - t_flip_memcpy_start) / 1000,
722 (t_flip_reverse_end - t_flip_reverse_start) / 1000, flip_x_enabled, flip_y_enabled);
723 }
724 }
725 uint64_t t_flip_end = time_get_ns();
726
727 uint64_t t_filter_start = time_get_ns();
728
729 // Apply color filter to RGB pixels before ASCII conversion
730 // Rainbow filter is handled separately via ANSI color replacement
731 image_t *filtered_image = NULL;
732 if (color_filter != COLOR_FILTER_NONE && color_filter != COLOR_FILTER_RAINBOW) {
733 // Create a copy to avoid modifying the original
734 filtered_image = ctx->render_file ? image_new(display_image->w, display_image->h) : display_image_workspace(&ctx->filter_workspace, display_image->w, display_image->h);
735 if (filtered_image && filtered_image->pixels && display_image->pixels) {
736 memcpy(filtered_image->pixels, display_image->pixels, (size_t)display_image->w * (size_t)display_image->h * sizeof(rgb_pixel_t));
737
738 // Apply filter to the copy
739 int stride = (int)display_image->w * 3;
740 float time_seconds = (float)t_filter_start / (float)NS_PER_SEC_INT;
741 apply_color_filter((uint8_t *)filtered_image->pixels, (uint32_t)display_image->w, (uint32_t)display_image->h, (uint32_t)stride, color_filter, time_seconds);
742 }
743 }
744
745 const image_t *ascii_input_image = filtered_image ? filtered_image : display_image;
746 uint64_t t_filter_end = time_get_ns();
747
748 uint64_t t_convert_start = time_get_ns();
749 // Recording converts concurrently on its encoder thread and retains owned output.
750 outbuf_t *output = reuse && !ctx->render_file && color_filter == COLOR_FILTER_NONE && !matrix_rain_enabled ? &ctx->ascii_workspace : NULL;
751 // Recording and live display run on separate threads and own separate histories.
752 bool recording = ctx->render_file && !reuse;
753 ascii_stabilizer_t *history = recording ? &ctx->recording_stabilizer : &ctx->stabilizer;
754 if (recording && ctx->render_fps)
755 history->fixed_step_ns = NS_PER_SEC_INT / ctx->render_fps;
756 char *result = ascii_convert_with_buffers_stabilized(ascii_input_image, width, height, &caps_copy, preserve_aspect_ratio, stretch, palette_chars, false,
757 ctx->render_file ? NULL : &ctx->resize_workspace, output, caps_copy.stabilize ? history : NULL);
758 if (!caps_copy.stabilize)
759 ascii_stabilizer_reset(history);
760 uint64_t t_convert_end = time_get_ns();
761
762 // Apply rainbow color filter to ANSI output by replacing RGB values
763 // This preserves character selection while applying the filter colors
764 if (result && color_filter == COLOR_FILTER_RAINBOW) {
765 uint64_t t_color_replace_start = time_get_ns();
766 float time_seconds = (float)t_filter_start / (float)NS_PER_SEC_INT;
767
768 char *rainbow_result = rainbow_replace_ansi_colors(result, time_seconds);
769 if (rainbow_result) {
770 SAFE_FREE(result);
771 result = rainbow_result;
772 }
773
774 uint64_t t_color_replace_end = time_get_ns();
775 char color_replace_str[TIME_DURATION_BUFFER_SIZE];
776 time_pretty(t_color_replace_end - t_color_replace_start, -1, color_replace_str, sizeof(color_replace_str));
777 log_dev("COLOR_REPLACE: %s", color_replace_str);
778 }
779
780 // Apply digital rain effect if enabled
781 if (result && ctx->digital_rain) {
782 uint64_t t_rain_start = time_get_ns();
783 uint64_t current_time_ns = t_rain_start;
784 float delta_time = (float)(current_time_ns - ctx->last_frame_time_ns) / (float)NS_PER_SEC_INT;
785 ctx->last_frame_time_ns = current_time_ns;
786
787 // Update digital rain color from current filter (allows live filter changes)
788 color_filter_t current_filter = GET_OPTION(color_filter);
790
791 char *rain_result = digital_rain_apply(ctx->digital_rain, result, delta_time);
792 if (rain_result) {
793 SAFE_FREE(result);
794 result = rain_result;
795 }
796
797 uint64_t t_rain_end = time_get_ns();
798 char rain_str[TIME_DURATION_BUFFER_SIZE];
799 time_pretty(t_rain_end - t_rain_start, -1, rain_str, sizeof(rain_str));
800 log_dev("DIGITAL_RAIN: Effect applied (%s)", rain_str);
801 }
802
803 uint64_t validation_started_ns = time_get_ns();
804 // Validate the completed local frame using the same policy as received text.
805 // Wide palettes use the existing cell composer before the rectangular check.
806 bool explicit_palette = caps_copy.palette_explicit;
807 bool glyph_match = caps_copy.text_renderer == ASCII_RENDERER_GLYPH && caps_copy.render_mode != RENDER_MODE_HALF_BLOCK && width > 0 && height > 0 && width <= IMAGE_MAX_WIDTH / 8 &&
808 height <= IMAGE_MAX_HEIGHT / 8 && (!explicit_palette || ascii_render_palette_supported(ASCII_RENDERER_GLYPH, palette_chars));
809 if (result && !glyph_match && (size_t)utf8_display_width(palette_chars) != utf8_char_count(palette_chars)) {
810 ascii_frame_source_t source = {.frame_data = result, .frame_size = strlen(result)};
811 size_t normalized_size;
812 char *rectangular = ascii_create_grid(&source, 1, width, height, &normalized_size);
814 result = rectangular;
815 }
816 if (result) {
817 acip_render_settings_t rendering = {.caps = caps_copy};
818 const char *contract_palette = glyph_match && !explicit_palette ? " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" : palette_chars;
819 SAFE_STRNCPY(rendering.palette, contract_palette, sizeof(rendering.palette));
821 if (session_frame_validate_contract(result, strlen(result), width, height, &rendering, effects) != ASCIICHAT_OK) {
823 result = NULL;
824 }
825 }
826
827 uint64_t validation_finished_ns = time_get_ns();
828 log_debug_every(US_PER_SEC_INT, "DISPLAY_STAGE: conversion_ms=%.2f validation_ms=%.2f", (double)(t_convert_end - t_convert_start) / NS_PER_MS_INT,
829 (double)(validation_finished_ns - validation_started_ns) / NS_PER_MS_INT);
830 uint64_t t_cleanup_start = time_get_ns();
831 // Scratch images remain owned by the display until resize or teardown.
832 if (ctx->render_file) {
833 image_destroy(filtered_image);
834 image_destroy(flipped_image);
835 }
836 uint64_t t_cleanup_end = time_get_ns();
837
838 // Log total breakdown with actual measured times
839 log_dev_every(US_PER_SEC_INT, "CONVERT_TIMING: flip=%llu us, filter=%llu us, convert=%llu us, cleanup=%llu us, TOTAL=%llu us", (t_flip_end - t_flip_start) / 1000,
840 (t_filter_end - t_filter_start) / 1000, (t_convert_end - t_convert_start) / 1000, (t_cleanup_end - t_cleanup_start) / 1000, (t_cleanup_end - t_flip_start) / 1000);
841
844 return result;
845}
846
847/* ============================================================================
848 * Session Display Rendering Functions
849 * ============================================================================ */
850
851static char *session_display_create_visualization_frame(session_display_ctx_t *ctx) {
854 bool use_color = ctx->caps.color_level == TERM_COLOR_TRUECOLOR && GET_OPTION(color) != COLOR_SETTING_FALSE;
856 audio_source_t selected_audio = GET_OPTION(audio_source);
858 if (selected_audio == AUDIO_SOURCE_MEDIA)
859 visual_source = AUDIO_VISUALIZATION_SOURCE_MEDIA;
860 else if (selected_audio == AUDIO_SOURCE_MIC)
861 visual_source = AUDIO_VISUALIZATION_SOURCE_MIC;
862 else if (selected_audio == AUDIO_SOURCE_CALL)
863 visual_source = AUDIO_VISUALIZATION_SOURCE_REMOTE;
864 char *text = GET_OPTION(fft) ? audio_visualization_render_fft(width, height, visual_source, use_color, color_mode, GET_OPTION(flip_x), GET_OPTION(flip_y))
865 : audio_visualization_render_waveform(width, height, visual_source, use_color, color_mode, GET_OPTION(flip_x), GET_OPTION(flip_y));
866 if (text && session_frame_validate(text, strlen(text), width, height) != ASCIICHAT_OK) {
867 SAFE_FREE(text);
868 return NULL;
869 }
870 return text;
871}
872
873void session_display_render_frame(session_display_ctx_t *ctx, const char *frame_data) {
874 // Legacy function: shim that calls both new split functions for backward compatibility
875 // This maintains API compatibility with existing code while delegating to specialized functions
876
877 if (!ctx || !frame_data) {
878 SET_ERRNO(ERROR_INVALID_PARAM, "Display context or frame data is NULL");
879 return;
880 }
881
882 // Write the selected visualization to the render file as well as the terminal.
883 char *visualization_frame = NULL;
884 const char *render_frame = frame_data;
885 if (GET_OPTION(waveform) || GET_OPTION(fft)) {
886 visualization_frame = session_display_create_visualization_frame(ctx);
887 if (visualization_frame)
888 render_frame = visualization_frame;
889 }
890
891 // Write ASCII to terminal (main thread output path)
892 if (ctx && ctx->render_file) {
894 asciichat_error_t err = render_file_write_frame(ctx->render_file, render_frame, time_get_ns());
895 if (err != ASCIICHAT_OK)
896 log_warn_every(5 * US_PER_SEC_INT, "Recording received frame failed: %s", asciichat_error_format(NULL, err));
897 }
898 SAFE_FREE(visualization_frame);
899 session_display_write_ascii(ctx, frame_data);
900}
901
903 return convert_to_ascii(ctx, image, false);
904}
905
907 ASCII_OTEL_SCOPE(SESSION_DISPLAY_CONVERT_TO_ASCII_REUSE);
908 return convert_to_ascii(ctx, image, true);
909}
910
912 if (ctx)
913 ascii_stabilizer_reset(recording ? &ctx->recording_stabilizer : &ctx->stabilizer);
914}
915
917 if (!ctx || ascii != ctx->ascii_workspace.buf)
918 SAFE_FREE(ascii);
919}
920
921void session_display_write_ascii_frame(session_display_ctx_t *ctx, const char *ascii, bool fresh) {
922 ASCII_OTEL_SCOPE(SESSION_DISPLAY_WRITE_ASCII_FRAME);
923 uint64_t write_entered_ns = time_get_ns();
924 if (!ctx || !ctx->initialized) {
925 SET_ERRNO(ERROR_INVALID_PARAM, "Display context is NULL or uninitialized");
926 return;
927 }
928
929 // Shutdown is asynchronous; queued frames must not retry a failed output.
930 if (atomic_load_bool(&ctx->output_failed)) {
931 return;
932 }
933
934 if (!ascii) {
935 SET_ERRNO(ERROR_INVALID_PARAM, "ASCII data is NULL");
936 return;
937 }
938
939 // Re-evaluate color_level on every frame to pick up live color_mode changes
940 terminal_color_mode_t color_mode = (terminal_color_mode_t)GET_OPTION(color_mode);
941 if (color_mode != TERM_COLOR_AUTO) {
942 ctx->caps.color_level = color_mode;
943 }
944
945 // Suppress frame rendering when help screen is active
946
947 bool visualization_enabled = GET_OPTION(waveform) || GET_OPTION(fft);
948 char *visualization_frame = visualization_enabled ? session_display_create_visualization_frame(ctx) : NULL;
949 if (visualization_frame)
950 ascii = visualization_frame;
951
952 // Leave room for cursor controls when passing the frame to the presenter.
953 const size_t max_frame_len = UI_CONTROLLER_MAX_FRAME_BYTES - 7;
954 size_t frame_len = strnlen(ascii, max_frame_len);
955 if (frame_len == max_frame_len) {
956 SET_ERRNO(ERROR_BUFFER_FULL, "ASCII frame exceeds the presenter limit");
957 SAFE_FREE(visualization_frame);
958 return;
959 }
960 if (frame_len == 0) {
961 SET_ERRNO(ERROR_INVALID_PARAM, "ASCII data is empty");
962 SAFE_FREE(visualization_frame);
963 return;
964 }
965
966 /* Sample payload inspection, not just its final log message. Scanning a
967 * truecolor frame on every presentation adds work even with logging off. */
968 static _Thread_local uint64_t last_frame_inspection_ns;
969 uint64_t inspection_ns = time_get_ns();
970 if (inspection_ns - last_frame_inspection_ns >= NS_PER_SEC_INT) {
971 last_frame_inspection_ns = inspection_ns;
972 size_t lines = 0, current = 0, min_line = SIZE_MAX, max_line = 0, last_line = 0;
973 unsigned control_bytes = 0, escape_bytes = 0;
974 for (size_t i = 0; i < frame_len; ++i) {
975 unsigned char byte = (unsigned char)ascii[i];
976 if (byte == '\n') {
977 min_line = MIN(min_line, current);
978 max_line = MAX(max_line, current);
979 last_line = current;
980 ++lines;
981 current = 0;
982 } else {
983 current++;
984 if (byte < 32 && byte != '\r' && byte != '\t')
985 ++control_bytes;
986 if (byte == 0x1b)
987 ++escape_bytes;
988 }
989 }
990 if (current) {
991 min_line = MIN(min_line, current);
992 max_line = MAX(max_line, current);
993 last_line = current;
994 }
995 char tail[64] = {0};
996 size_t tail_start = frame_len > 24 ? frame_len - 24 : 0;
997 size_t tail_used = 0;
998 for (size_t i = tail_start; i < frame_len && tail_used + 4 < sizeof(tail); ++i)
999 tail_used += (size_t)safe_snprintf(tail + tail_used, sizeof(tail) - tail_used, "%02X ", (unsigned char)ascii[i]);
1000
1001 // Also capture the actual glyphs in the final row. Byte/line counts alone
1002 // cannot distinguish a bad terminal write from a bad rendered frame.
1003 size_t row_start = 0;
1004 for (size_t i = 0; i < frame_len; ++i)
1005 if (ascii[i] == '\n')
1006 row_start = i + 1;
1007 char last_row[192] = {0};
1008 size_t row_used = 0;
1009 for (size_t i = row_start; i < frame_len && row_used + 5 < sizeof(last_row); ++i) {
1010 unsigned char byte = (unsigned char)ascii[i];
1011 if (byte == 0x1b) {
1012 ++i;
1013 while (i < frame_len && !((ascii[i] >= '@' && ascii[i] <= 'Z') || (ascii[i] >= 'a' && ascii[i] <= 'z')))
1014 ++i;
1015 continue;
1016 }
1017 if (byte >= 32 && byte < 127)
1018 last_row[row_used++] = (char)byte;
1019 else if (byte == '\r' || byte == '\t')
1020 last_row[row_used++] = ' ';
1021 else
1022 row_used += (size_t)safe_snprintf(last_row + row_used, sizeof(last_row) - row_used, "\\x%02X", byte);
1023 }
1024 log_debug("FRAME_DATA: bytes=%zu lines=%zu line_bytes=%zu..%zu last=%zu controls=%u escapes=%u last_row=\"%s\" tail=%s", frame_len, lines, min_line == SIZE_MAX ? 0 : min_line, max_line, last_line,
1025 control_bytes, escape_bytes, last_row, tail);
1026 }
1027
1028 // Apply digital rain effect if enabled
1029 uint64_t inspection_done_ns = time_get_ns();
1030 char *display_frame = (char *)ascii;
1031 char *rain_result = NULL;
1032 if (ctx->digital_rain && !visualization_enabled) {
1033 uint64_t t_rain_start = time_get_ns();
1034 uint64_t current_time_ns = t_rain_start;
1035 float delta_time = (float)(current_time_ns - ctx->last_frame_time_ns) / (float)NS_PER_SEC_INT;
1036 ctx->last_frame_time_ns = current_time_ns;
1037
1038 // Update digital rain color from current filter
1039 color_filter_t current_filter = GET_OPTION(color_filter);
1041
1042 rain_result = digital_rain_apply(ctx->digital_rain, (char *)ascii, delta_time);
1043 if (rain_result) {
1044 display_frame = rain_result;
1045 frame_len = strnlen(rain_result, max_frame_len);
1046 if (frame_len == max_frame_len) {
1047 SET_ERRNO(ERROR_BUFFER_FULL, "Digital rain frame exceeds the presenter limit");
1048 SAFE_FREE(rain_result);
1049 SAFE_FREE(visualization_frame);
1050 return;
1051 }
1052
1053 uint64_t t_rain_end = time_get_ns();
1054 char rain_str[TIME_DURATION_BUFFER_SIZE];
1055 time_pretty(t_rain_end - t_rain_start, -1, rain_str, sizeof(rain_str));
1056 log_debug("DIGITAL_RAIN (write_ascii): Effect applied (%s)", rain_str);
1057 }
1058 }
1059
1060 // Binary video owns stdout in every terminal mode.
1061 const char *output = GET_OPTION(render_file);
1062 bool binary_stdout = ctx->render_file && (strcmp(output, "-") == 0 || strcmp(output, "pipe:") == 0 || strcmp(output, "--kitty") == 0 || GET_OPTION(render_kitty));
1063 char *zalgo_frame = NULL;
1064 int zalgo_level = GET_OPTION(zalgo);
1065 if (zalgo_level > 0 && !binary_stdout) {
1066 asciichat_error_t err = zalgo_apply(display_frame, frame_len, zalgo_level, UI_CONTROLLER_MAX_FRAME_BYTES - 7, &zalgo_frame);
1067 if (err == ASCIICHAT_OK) {
1068 display_frame = zalgo_frame;
1069 frame_len = strlen(zalgo_frame);
1070 } else {
1071 log_warn_every(5 * US_PER_SEC_INT, "Cannot apply Zalgo: %s", asciichat_error_format(NULL, err));
1072 }
1073 }
1074
1075 char *plain_frame = NULL;
1076 if (GET_OPTION(strip_ansi)) {
1077 // Expand REP before stripping escapes so repeated cells are preserved.
1078 char *expanded = ansi_expand_rle(display_frame, frame_len);
1079 if (expanded) {
1080 size_t capacity = strlen(expanded) + 1;
1081 plain_frame = SAFE_MALLOC(capacity, char *);
1082 strip_ansi_codes(expanded, plain_frame, capacity);
1083 SAFE_FREE(expanded);
1084 display_frame = plain_frame;
1085 frame_len = strlen(plain_frame);
1086 }
1087 }
1088
1089 // Handle first frame - perform initial terminal reset and splash cleanup
1090 bool was_first_frame = atomic_exchange_bool(&ctx->first_frame, false);
1091 if (was_first_frame) {
1094 // Stop splash screen when first frame is ready
1097 asciichat_error_t reconnect_result = ui_reconnect_controller_set(false, NULL);
1098 if (reconnect_result != ASCIICHAT_OK)
1099 log_error("Cannot hide reconnect view after first frame: %s", asciichat_error_string(reconnect_result));
1100 }
1101
1102 if (binary_stdout) {
1103 if (GET_OPTION(snapshot_mode) && !g_snapshot_first_frame_rendered) {
1105 g_snapshot_first_frame_rendered_ns = time_get_ns();
1106 }
1107 SAFE_FREE(plain_frame);
1108 SAFE_FREE(zalgo_frame);
1109 SAFE_FREE(rain_result);
1110 SAFE_FREE(visualization_frame);
1111 return;
1112 }
1113
1114 // Output routing logic
1115 // A snapshot still needs terminal cursor framing when stdout is a real TTY.
1116 // `terminal_is_interactive()` also depends on stdin, which is commonly false
1117 // for scripted snapshot invocations even though the PTY can display output.
1118 bool use_tty_control = ctx->has_tty || (ctx->snapshot_mode && ctx->tty_info.fd >= 0 && platform_isatty(ctx->tty_info.fd));
1119
1120 uint64_t frame_write_started_ns = time_get_ns();
1121
1122 // Increment shared frame counter for both client and host rendering
1123 // This metric is used by debug scripts to measure FPS across all modes
1124 static atomic_t g_display_frames_rendered = {0};
1125 int frame_number = (int)(atomic_fetch_add_u64(&g_display_frames_rendered, 1) + 1);
1126 log_dev("[FRAMES_RENDERED_TOTAL] %d", frame_number);
1127
1128 if (use_tty_control) {
1129 // TTY mode: Buffer cursor control + frame data together for atomic frame display
1130 // Media output must not inherit a scrolling region left by another UI
1131 // screen or by terminal-side diagnostic handling. A plain home command
1132 // homes within that region, so a later frame can begin on a different
1133 // physical row after the terminal scrolls.
1134 const char *cursor_home_sequence = "\033[r\033[H";
1135 const char *erase_below_sequence = "\033[J";
1136 size_t cursor_seq_len = 6;
1137 size_t erase_below_len = 3;
1138 // ESC[J erases from the cursor through the end of the screen. When the
1139 // frame fills the terminal height, the cursor is on the final cell and
1140 // ESC[J erases the bottom-right glyph we just rendered. Only clear below
1141 // shorter frames, where the cursor is guaranteed to be above the last row.
1142 size_t frame_rows = 1;
1143 for (size_t i = 0; i < frame_len; ++i)
1144 frame_rows += display_frame[i] == '\n';
1145 int output_fd = ctx->tty_info.fd >= 0 ? ctx->tty_info.fd : STDOUT_FILENO;
1146 terminal_size_t terminal = {0};
1147 static _Thread_local int trace_terminal_size;
1148 if (!trace_terminal_size) {
1149 const char *value = SAFE_GETENV("ASCII_CHAT_TRACE_TERMINAL_WRITES");
1150 trace_terminal_size = value && strcmp(value, "1") == 0 ? 1 : -1;
1151 }
1152 bool trace_size = trace_terminal_size > 0;
1153 if (trace_size)
1154 log_file_msg("TERMINAL_CALL_BEGIN: thread=%llu caller=display call=terminal_get_size_fd fd=%d at_ns=%llu", (unsigned long long)thread_current_id(), output_fd, (unsigned long long)time_get_ns());
1155 uint64_t size_started_ns = trace_size ? time_get_ns() : 0;
1156 int size_result = terminal_get_size_fd(output_fd, &terminal);
1157 uint64_t size_returned_ns = trace_size ? time_get_ns() : 0;
1158 if (trace_size)
1159 log_file_msg("TERMINAL_CALL_END: thread=%llu caller=display call=terminal_get_size_fd fd=%d result=%d cols=%d rows=%d elapsed_ms=%.3f at_ns=%llu", (unsigned long long)thread_current_id(),
1160 output_fd, size_result, terminal.cols, terminal.rows, (double)(size_returned_ns - size_started_ns) / NS_PER_MS_INT, (unsigned long long)size_returned_ns);
1161 if (size_result == ASCIICHAT_OK && frame_rows >= (size_t)terminal.rows)
1162 erase_below_len = 0;
1163 uint64_t framing_done_ns = time_get_ns();
1164 // The frame is shorter than the terminal in some configurations. Erase
1165 // from the final frame cursor to the bottom of the screen in the same
1166 // submission so stale rows cannot survive a resize or a shorter frame.
1167 size_t total_size = cursor_seq_len + frame_len + erase_below_len;
1168
1169 if (ctx->tty_frame_capacity < total_size) {
1170 size_t capacity = ctx->tty_frame_capacity ? ctx->tty_frame_capacity : 4096;
1171 while (capacity < total_size && capacity <= SIZE_MAX / 2)
1172 capacity *= 2;
1173 if (capacity < total_size)
1174 capacity = total_size;
1175 ctx->tty_frame_buffer = SAFE_REALLOC(ctx->tty_frame_buffer, capacity, char *);
1176 ctx->tty_frame_capacity = capacity;
1177 }
1178 char *frame_buffer = ctx->tty_frame_buffer;
1179 if (frame_buffer) {
1180 memcpy(frame_buffer, cursor_home_sequence, cursor_seq_len);
1181 memcpy(frame_buffer + cursor_seq_len, display_frame, frame_len);
1182 memcpy(frame_buffer + cursor_seq_len + frame_len, erase_below_sequence, erase_below_len);
1183
1184 log_debug_every(US_PER_SEC_INT, "FRAME_WRITE_TTY: Writing %zu bytes (cursor=%zu + frame=%zu) to stdout", total_size, cursor_seq_len, frame_len);
1185 asciichat_error_t presented = ASCIICHAT_OK;
1186 if (ctx->snapshot_mode) {
1187 // Snapshot processes may exit immediately after the first frame. Write
1188 // directly so teardown cannot discard a queued UI-controller update.
1189 if (platform_write_all(output_fd, frame_buffer, total_size) != total_size)
1190 presented = SET_ERRNO(ERROR_FILE_OPERATION, "Cannot write snapshot frame to terminal");
1191 } else {
1192 uint64_t present_started_ns = time_get_ns();
1193 log_debug("MEDIA_PRESENT_CALL: fd=%d bytes=%zu fresh=%d", output_fd, total_size, fresh ? 1 : 0);
1194 presented = (fresh ? ui_controller_present : ui_controller_present_retained)(UI_SCREEN_MEDIA, output_fd, (terminal_size_t){.cols = UI_MEDIA_MIN_COLS, .rows = UI_MEDIA_MIN_ROWS}, frame_buffer,
1195 total_size);
1196 uint64_t present_elapsed_ns = time_get_ns() - present_started_ns;
1197 static _Thread_local uint64_t stage_last_ns, stage_count, stage_totals[5];
1198 stage_totals[0] += inspection_done_ns - write_entered_ns;
1199 stage_totals[1] += frame_write_started_ns - inspection_done_ns;
1200 stage_totals[2] += framing_done_ns - frame_write_started_ns;
1201 stage_totals[3] += present_started_ns - framing_done_ns;
1202 stage_totals[4] += present_elapsed_ns;
1203 ++stage_count;
1204 uint64_t stage_now_ns = time_get_ns();
1205 if (stage_now_ns - stage_last_ns >= NS_PER_SEC_INT) {
1206 double divisor = (double)stage_count * NS_PER_MS_INT;
1207 log_debug("DISPLAY_PUBLISH_STAGE: frames=%llu inspection_ms=%.2f effects_ms=%.2f framing_ms=%.2f copy_ms=%.2f submit_ms=%.2f", (unsigned long long)stage_count, stage_totals[0] / divisor,
1208 stage_totals[1] / divisor, stage_totals[2] / divisor, stage_totals[3] / divisor, stage_totals[4] / divisor);
1209 memset(stage_totals, 0, sizeof(stage_totals));
1210 stage_count = 0;
1211 stage_last_ns = stage_now_ns;
1212 }
1213 if (present_elapsed_ns >= 50 * NS_PER_MS_INT)
1214 log_debug("MEDIA_PRESENT_RETURN: fd=%d bytes=%zu elapsed_ms=%.2f result=%d", output_fd, total_size, (double)present_elapsed_ns / NS_PER_MS_INT, presented);
1215 }
1216 if (was_first_frame && presented == ASCIICHAT_OK)
1218 ssize_t written = presented == ASCIICHAT_OK ? (ssize_t)total_size : -1;
1219 log_debug_every(US_PER_SEC_INT, "FRAME_WRITE_TTY: Wrote %zd bytes (requested %zu)", written, total_size);
1220
1221 // Start snapshot timer on first ASCII frame rendered
1222 if (GET_OPTION(snapshot_mode) && !g_snapshot_first_frame_rendered) {
1224 g_snapshot_first_frame_rendered_ns = time_get_ns();
1225 log_debug("SNAPSHOT: FIRST ASCII FRAME RENDERED (write_ascii) - Timer started");
1226 }
1227
1228 // The UI controller copies the submission before this workspace is reused.
1229 }
1230
1231 // Live presentation owns terminal writes on its worker. Draining here
1232 // blocks packet reception, including audio, behind a slow terminal reader.
1233 if (ctx->snapshot_mode) {
1234 (void)fflush(stdout);
1235 int flush_fd = (ctx->tty_info.fd >= 0) ? ctx->tty_info.fd : STDOUT_FILENO;
1236 (void)terminal_flush(flush_fd);
1237 }
1238
1239 } else if (terminal_is_interactive()) {
1240 // Piped to interactive terminal: output ASCII frames with newline
1241 char *write_buf = SAFE_MALLOC(frame_len + 1, char *);
1242 if (write_buf) {
1243 memcpy(write_buf, display_frame, frame_len);
1244 write_buf[frame_len] = '\n';
1245 if (ui_controller_write(STDOUT_FILENO, write_buf, frame_len + 1) != ASCIICHAT_OK) {
1246 atomic_store_bool(&ctx->output_failed, true);
1248 SAFE_FREE(write_buf);
1249 goto cleanup_frame;
1250 }
1251 SAFE_FREE(write_buf);
1252 }
1253
1254 if (ctx->snapshot_mode) {
1255 (void)fflush(stdout);
1256 int flush_fd = (ctx->tty_info.fd >= 0) ? ctx->tty_info.fd : STDOUT_FILENO;
1257 (void)terminal_flush(flush_fd);
1258 }
1259 } else {
1260 // Named render files leave stdout available for ASCII output
1261 char *write_buf = SAFE_MALLOC(frame_len + 1, char *);
1262 if (write_buf) {
1263 memcpy(write_buf, display_frame, frame_len);
1264 write_buf[frame_len] = '\n';
1265 if (ui_controller_write(STDOUT_FILENO, write_buf, frame_len + 1) != ASCIICHAT_OK) {
1266 atomic_store_bool(&ctx->output_failed, true);
1268 SAFE_FREE(write_buf);
1269 goto cleanup_frame;
1270 }
1271
1272 // Start snapshot timer on first ASCII frame rendered
1273 if (GET_OPTION(snapshot_mode) && !g_snapshot_first_frame_rendered) {
1275 g_snapshot_first_frame_rendered_ns = time_get_ns();
1276 log_debug("SNAPSHOT: FIRST ASCII FRAME RENDERED (write_ascii piped) - Timer started");
1277 }
1278
1279 SAFE_FREE(write_buf);
1280 }
1281
1282 // Writes already reach the OS synchronously; streaming frames do not need
1283 // a durability barrier or a terminal drain on the receiving thread.
1284 (void)fflush(stdout);
1285 if (ctx->snapshot_mode && ctx->has_tty) {
1286 int flush_fd = (ctx->tty_info.fd >= 0) ? ctx->tty_info.fd : STDOUT_FILENO;
1287 (void)terminal_flush(flush_fd);
1288 }
1289 }
1290
1291cleanup_frame:
1292 log_dev_every(3 * US_PER_SEC_INT, "FRAME_WRITE: Published in %.2f ms", (double)(time_get_ns() - frame_write_started_ns) / NS_PER_MS_INT);
1293
1294 // Clean up digital rain result if allocated
1295 SAFE_FREE(plain_frame);
1296 SAFE_FREE(zalgo_frame);
1297 if (rain_result) {
1298 SAFE_FREE(rain_result);
1299 }
1300 SAFE_FREE(visualization_frame);
1301}
1302
1307
1309 ASCII_OTEL_SCOPE(SESSION_DISPLAY_ENCODE_FRAME);
1310 static int call_count = 0;
1311 if (call_count++ < 5) {
1312 log_debug("ctx=%p, image=%p, captured_ns=%llu, ctx->render_file=%p", (void *)ctx, (void *)image, (unsigned long long)captured_ns, ctx ? (void *)ctx->render_file : NULL);
1313 }
1314
1315 if (!ctx || !ctx->initialized) {
1316 return SET_ERRNO(ERROR_INVALID_PARAM, "Display context is NULL or uninitialized");
1317 }
1318
1319 if (!image) {
1320 return SET_ERRNO(ERROR_INVALID_PARAM, "Image is NULL");
1321 }
1322
1323 // Only encode if render_file is active
1324 if (!ctx->render_file) {
1325 log_warn_every(10 * US_PER_SEC_INT, "render_file is NULL, skipping encode");
1326 return ASCIICHAT_OK;
1327 }
1328
1329 // Convert image to ASCII
1330 uint64_t conversion_started_ns = time_get_ns();
1331 char *ascii = session_display_convert_to_ascii(ctx, image);
1332 uint64_t converted_ns = time_get_ns();
1333 if (!ascii) {
1334 log_warn("Failed to convert image to ASCII");
1335 return SET_ERRNO(ERROR_MEDIA_INIT, "Cannot convert recording frame to ASCII");
1336 }
1337
1338 // Write the same selected visualization used by the terminal to the render-file encoder.
1339 char *visualization_frame = NULL;
1340 const char *render_frame = ascii;
1341 if (GET_OPTION(waveform) || GET_OPTION(fft)) {
1342 visualization_frame = session_display_create_visualization_frame(ctx);
1343 if (visualization_frame)
1344 render_frame = visualization_frame;
1345 }
1346
1347 uint64_t stats_record_start = time_get_ns();
1348 asciichat_error_t fe = render_file_write_frame(ctx->render_file, render_frame, captured_ns);
1349 uint64_t recorded_ns = time_get_ns();
1350 log_debug_every(US_PER_SEC_INT, "RECORD_FRAME: convert_ms=%.2f output_ms=%.2f total_ms=%.2f", (double)(converted_ns - conversion_started_ns) / NS_PER_MS_INT,
1351 (double)(recorded_ns - converted_ns) / NS_PER_MS_INT, (double)(recorded_ns - conversion_started_ns) / NS_PER_MS_INT);
1352 stats_duration_record(stats_runtime_scope(), STATS_DURATION_RECORDING, time_get_ns() - stats_record_start);
1353 if (fe == ASCIICHAT_OK)
1355 SAFE_FREE(visualization_frame);
1356 if (fe != ASCIICHAT_OK) {
1357 log_warn_every(5 * US_PER_SEC_INT, "render-file: encode failed (%s)", asciichat_error_format(NULL, fe));
1358 }
1359
1360 SAFE_FREE(ascii);
1361 return fe;
1362}
1363
1364void session_display_write_raw(session_display_ctx_t *ctx, const char *data, size_t len) {
1365 ASCII_OTEL_SCOPE(SESSION_DISPLAY_WRITE_RAW);
1366 if (!ctx || !ctx->initialized || !data || len == 0) {
1367 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, data=%p, len=%zu", ctx, data, len);
1368 return;
1369 }
1370
1371 int fd = -1;
1372 if (ctx->has_tty && ctx->tty_info.fd >= 0) {
1373 fd = ctx->tty_info.fd;
1374 } else {
1375 fd = STDOUT_FILENO;
1376 }
1377
1378 // Write all data with automatic retry on transient errors
1379 (void)ui_controller_write(fd, data, len);
1380
1381 // Flush immediately after write to TTY to ensure data is sent
1382 (void)terminal_flush(fd);
1383}
1384
1386 if (ctx && !ctx->snapshot_mode)
1388}
1389
1391 if (ctx && !ctx->snapshot_mode)
1393}
1394
1399
1401 if (!ctx || !ctx->initialized) {
1402 SET_ERRNO(ERROR_INVALID_PARAM, "Session display context is NULL or uninitialized");
1403 return false;
1404 }
1405 return ctx->audio_playback_enabled;
1406}
1407
1408asciichat_error_t session_display_write_audio(session_display_ctx_t *ctx, const float *buffer, size_t num_samples) {
1409 ASCII_OTEL_SCOPE(SESSION_DISPLAY_WRITE_AUDIO);
1410 if (!ctx || !ctx->initialized || !buffer || num_samples == 0) {
1411 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, buffer=%p, num_samples=%zu", ctx, buffer, num_samples);
1412 }
1413
1414 if (!ctx->audio_playback_enabled || !ctx->audio_ctx) {
1415 // Audio not enabled, but not an error - just skip silently
1416 return ASCIICHAT_OK;
1417 }
1418
1419 // For mirror mode with local files: write samples directly without jitter buffering
1420 // The jitter buffer is designed for network scenarios with irregular packet arrivals
1421 // For local playback, we just want raw samples flowing to the speakers
1422 audio_context_t *audio_ctx = (audio_context_t *)ctx->audio_ctx;
1423 if (audio_ctx && audio_ctx->playback_buffer) {
1424 audio_ring_buffer_t *rb = audio_ctx->playback_buffer;
1425
1426 // Simple direct write: append samples to ring buffer without network-oriented complexity
1427 uint32_t write_idx = (uint32_t)atomic_load_u64(&rb->write_index);
1428 uint32_t read_idx = (uint32_t)atomic_load_u64(&rb->read_index);
1429
1430 // Calculate available space in ring buffer
1431 uint32_t available = (read_idx - write_idx - 1) & (AUDIO_RING_BUFFER_SIZE - 1);
1432
1433 if ((uint32_t)num_samples > available) {
1434 // Buffer full - just skip this write to avoid distortion from overwriting old audio
1435 return ASCIICHAT_OK;
1436 }
1437
1438 // Direct memcpy to ring buffer, handling wrap-around
1439 uint32_t space_before_wrap = AUDIO_RING_BUFFER_SIZE - write_idx;
1440 if ((uint32_t)num_samples <= space_before_wrap) {
1441 memcpy(&rb->data[write_idx], buffer, num_samples * sizeof(float));
1442 } else {
1443 // Split write: first part to end of buffer, second part wraps to beginning
1444 uint32_t first_part = space_before_wrap;
1445 uint32_t second_part = (uint32_t)(num_samples - first_part);
1446 memcpy(&rb->data[write_idx], buffer, first_part * sizeof(float));
1447 memcpy(&rb->data[0], &buffer[first_part], second_part * sizeof(float));
1448 }
1449
1450 // Update write index atomically
1451 atomic_store_u64(&rb->write_index, (write_idx + num_samples) % AUDIO_RING_BUFFER_SIZE);
1452
1453 return ASCIICHAT_OK;
1454 }
1455
1456 return ASCIICHAT_OK;
1457}
1458
1459/* ============================================================================
1460 * Keyboard Help Functions (from keyboard_help module)
1461 * ============================================================================ */
1462
1466// Global reference to current display context (used by signal handlers)
1467// Set during render loop, cleared on exit
1468static atomic_ptr_t g_current_display_ctx = {0};
1469
1470// Signal-safe flag to request help screen closure from Ctrl+C handler
1471static atomic_t g_help_signal_cancel = {0};
1472
1473// Signal handler safe way to access current display context
1474static session_display_ctx_t *get_current_display_ctx(void) {
1475 return (session_display_ctx_t *)atomic_ptr_load(&g_current_display_ctx);
1476}
1477
1478// Called by render loop to register/unregister the display context
1480 atomic_ptr_store(&g_current_display_ctx, (void *)ctx);
1481}
1482
1483// Public getter for global display context
1485 return get_current_display_ctx();
1486}
1487
1488// Public setter for global display context (used by discovery participant cleanup)
1492
1493// Called from Ctrl+C signal handler to request help screen closure
1495 atomic_store_bool(&g_help_signal_cancel, true);
1496}
1497
1498// Called from render loop to check if help should be closed
1500 bool expected = true;
1501 return atomic_cas_bool(&g_help_signal_cancel, &expected, false);
1502}
1503
1505 if (!ctx) {
1506 SET_ERRNO(ERROR_INVALID_PARAM, "Session display context is NULL");
1507 return false;
1508 }
1509
1510 // Disable help in snapshot mode only - allow help state check even if stdin/stdout aren't TTYs
1511 if (GET_OPTION(snapshot_mode)) {
1512 return false;
1513 }
1514
1516}
1517
1518// Global accessor for signal handlers (called from Ctrl+C handler)
1519// Checks raw help state without snapshot mode check (signal handler needs to know
1520// if help is active even in snapshot mode)
1522 session_display_ctx_t *ctx = get_current_display_ctx();
1524}
1525
1529
1531 log_debug("duration=%.3f, ctx=%p, render_file=%p", actual_duration_sec, (void *)ctx, ctx ? (void *)ctx->render_file : NULL);
1532
1533 if (!ctx) {
1534 SET_ERRNO(ERROR_INVALID_PARAM, "Session display context is NULL");
1535 return;
1536 }
1537
1538 if (!ctx->render_file) {
1539 // Terminal snapshots have no render-file encoder; their duration is
1540 // governed by the capture loop and requires no additional action.
1541 return;
1542 }
1543
1544 log_debug(" -> Passing duration %.3f to render_file encoder", actual_duration_sec);
1545 render_file_set_snapshot_actual_duration(ctx->render_file, actual_duration_sec);
1546}
1547
1549 session_display_write_ascii_frame(ctx, ascii, true);
1550}
ANSI escape sequence utilities and fast color code generation.
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
char * ascii_convert_with_buffers_stabilized(const image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch, const char *palette_chars, const bool contain, image_t **workspace, outbuf_t *output, ascii_stabilizer_t *stabilizer)
Definition ascii.c:282
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.
terminal_background_t colorscheme_current_background(void)
@ TERM_BACKGROUND_DARK
Definition colorscheme.h:71
Named object registry for debugging — log identifiable resource names.
Matrix-style digital rain effect for ASCII frames.
int color_mode
Definition fft.c:26
asciichat_error_t audio_visualization_fft_init(void)
Definition fft.c:82
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
char * audio_visualization_render_fft(unsigned int width, unsigned int height, audio_visualization_source_t source, bool use_color, int color_mode, bool flip_x, bool flip_y)
Definition fft.c:128
int platform_close(int fd)
Definition filesystem.c:91
asciichat_error_t session_frame_validate(const char *text, size_t length, uint32_t width, uint32_t height)
asciichat_error_t session_frame_validate_contract(const char *text, size_t length, uint32_t width, uint32_t height, const acip_render_settings_t *settings, uint32_t effects)
void ansi_fast_init_256color(void)
Definition ansi.c:231
void ansi_fast_init(void)
Definition ansi.c:226
void ansi_fast_init_16color(void)
Definition ansi.c:314
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_BUFFER_FULL
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_MEDIA_INIT
Definition error_codes.h:70
@ ERROR_FILE_OPERATION
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
void log_set_force_stderr(bool enabled)
Force all terminal log output to stderr.
Definition log/log.c:840
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void log_file_msg(const char *fmt,...)
Log to file only, no stderr output.
Definition log/log.c:1952
#define NS_PER_SEC_INT
Definition time.h:173
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1339
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
audio_source_t
Audio source selected for visualization.
Definition options.h:277
#define options_terminal_settings()
Definition options.h:1287
@ UTF8_SETTING_AUTO
Smart detection (default): UTF-8 if terminal supports it.
Definition options.h:265
@ UTF8_SETTING_FALSE
Force UTF-8 OFF: disable UTF-8 support.
Definition options.h:269
@ AUDIO_SOURCE_MIC
Definition options.h:283
@ AUDIO_SOURCE_CALL
Definition options.h:281
@ AUDIO_SOURCE_MEDIA
Definition options.h:285
@ COLOR_SETTING_FALSE
Force colors OFF: disable all colors and logging colors.
Definition options.h:250
int initialize_client_palette(palette_type_t palette_type, const char *custom_chars, char client_palette_chars[ASCII_PALETTE_BUFFER_SIZE], size_t *client_palette_len, char client_luminance_palette[ASCII_LUMINANCE_LEVELS])
Initialize client palette with full configuration.
Definition palette.c:292
const palette_def_t * get_builtin_palette(palette_type_t type)
Get built-in palette definition.
Definition palette.c:45
palette_type_t
Built-in palette type enumeration.
Definition palette.h:96
const char * chars
Character sequence (ordered from dark to light).
Definition palette.h:134
@ PALETTE_CUSTOM
User-defined via –palette-chars.
Definition palette.h:110
@ PALETTE_STANDARD
Standard ASCII palette: " ...',;:clodxkO0KXNWM".
Definition palette.h:100
struct audio_ring_buffer audio_ring_buffer_t
Audio ring buffer for real-time audio streaming.
#define AUDIO_RING_BUFFER_SIZE
Audio ring buffer size in samples (192000 samples = 4 seconds @ 48kHz).
Definition ringbuffer.h:136
void session_display_destroy(session_display_ctx_t *ctx)
void session_display_set_render_fps(session_display_ctx_t *ctx, uint32_t fps)
Set the render FPS for file output encoding.
void session_display_write_ascii(session_display_ctx_t *ctx, const char *ascii)
Write ASCII frame to terminal only (no encoding).
session_display_ctx_t * session_display_create(const session_display_config_t *config)
Create a new session display context.
asciichat_error_t session_display_finish_render_file(session_display_ctx_t *ctx)
Destroy session display context and free resources.
void session_display_clear(session_display_ctx_t *ctx)
Clear the terminal screen.
void * session_display_get_stdin_reader(session_display_ctx_t *ctx)
Get the stdin frame reader for ASCII-to-video rendering.
size_t session_display_get_palette_len(session_display_ctx_t *ctx)
Get the palette character count.
void session_display_set_stdin_reader(session_display_ctx_t *ctx, void *reader)
Set stdin frame reader for ASCII-to-video rendering.
bool keyboard_help_is_active_global(void)
Check if keyboard help is active (global accessor for signal handlers).
bool keyboard_help_is_active(session_display_ctx_t *ctx)
Check if keyboard help is currently active.
struct session_display_ctx session_display_ctx_t
session display config is intentionally a small, concrete record. Fields such as snapshot_mode,...
int splash_intro_done(void)
Signal that intro splash should end (first frame ready to render).
Definition splash.c:465
void session_display_begin_drain(session_display_ctx_t *ctx, uint64_t total, bool total_known)
void session_display_set_snapshot_actual_duration(session_display_ctx_t *ctx, double actual_duration_sec)
Set the actual wall-clock duration for snapshot mode frame timing.
void session_display_write_raw(session_display_ctx_t *ctx, const char *data, size_t len)
Render raw bytes to the terminal without frame processing.
asciichat_error_t session_display_encode_frame(session_display_ctx_t *ctx, const image_t *image, uint64_t captured_ns)
Encode frame to render-file (FFmpeg only, no terminal output).
asciichat_error_t session_display_write_audio(session_display_ctx_t *ctx, const float *buffer, size_t num_samples)
Write audio samples to playback buffer.
session_display_ctx_t * session_display_get_global_context(void)
Get the global display context (used for signal handlers and special cleanup).
bool session_display_has_tty(session_display_ctx_t *ctx)
Check if display has a TTY (terminal) available.
void session_display_cursor_home(session_display_ctx_t *ctx)
Move cursor to home position (top-left).
void keyboard_help_toggle_global(void)
Toggle keyboard help (global accessor for signal handlers).
const char * session_display_get_luminance_palette(session_display_ctx_t *ctx)
Get the luminance mapping palette.
void keyboard_help_signal_cancel(void)
Request help screen closure from signal handler (Ctrl+C).
void session_display_set_global_context_public(session_display_ctx_t *ctx)
Set the global display context (public setter for discovery cleanup).
void session_display_render_frame(session_display_ctx_t *ctx, const char *frame_data)
Render an ASCII frame to the terminal.
void session_display_reset_first_frame(session_display_ctx_t *ctx)
Reset the first frame flag to allow splash screen to show again on next render.
int session_display_get_tty_fd(session_display_ctx_t *ctx)
Get the TTY file descriptor.
void splash_clear_display_context(void)
Clear the cached display context to prevent use-after-free.
Definition splash.c:481
bool session_display_has_first_frame(session_display_ctx_t *ctx)
Check if the display has rendered its first frame.
void session_display_set_global_context(session_display_ctx_t *ctx)
Set the global display context (for signal handlers like Ctrl+C).
bool session_display_has_render_file(session_display_ctx_t *ctx)
Check if display has render-file configured.
bool keyboard_help_check_signal_cancel(void)
Check if help screen closure was requested by signal handler.
const char * session_display_get_palette_chars(session_display_ctx_t *ctx)
Get the palette characters string.
void splash_wait_for_animation(void)
Wait for splash animation thread to fully exit.
Definition splash.c:491
const terminal_capabilities_t * session_display_get_caps(session_display_ctx_t *ctx)
Get detected terminal capabilities.
bool session_display_has_audio_playback(session_display_ctx_t *ctx)
Check if display has audio playback configured.
char * session_display_convert_to_ascii(session_display_ctx_t *ctx, const image_t *image)
Convert an image to ASCII art using display context and command-line options.
void session_display_reset(session_display_ctx_t *ctx)
Reset terminal to default state.
uint32_t session_display_get_render_fps(session_display_ctx_t *ctx)
Get the render FPS configured for file output.
void strip_ansi_codes(const char *input, char *output, size_t output_size)
Strip ANSI escape codes from a string.
int utf8_display_width(const char *str)
Calculate terminal display width of a UTF-8 string.
Definition utf8.c:102
size_t utf8_char_count(const char *str)
Count UTF-8 characters (not bytes).
Definition utf8.c:112
char * rainbow_replace_ansi_colors(const char *ansi_string, float time_seconds)
Replace all RGB ANSI codes with rainbow color.
utf8_palette_cache_t * get_utf8_palette_cache(const char *ascii_chars)
Get UTF-8 palette cache for a character set.
asciichat_error_t ascii_write_init(int fd, bool reset_terminal)
Initialize ASCII write subsystem.
Definition ascii.c:127
void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter)
Set digital rain color from color filter.
void ascii_write_destroy(int fd, bool reset_terminal)
Destroy ASCII write subsystem.
Definition ascii.c:525
#define ASCII_LUMINANCE_LEVELS
Number of luminance levels supported (256).
Definition ascii.h:438
#define IMAGE_MAX_WIDTH
An owned RGB image with dimensions and row-major pixel storage.
#define IMAGE_MAX_HEIGHT
Maximum image height (4K resolution).
void digital_rain_destroy(digital_rain_t *rain)
Destroy digital rain effect context.
char * digital_rain_apply(digital_rain_t *rain, const char *frame, float delta_time)
Apply digital rain effect to ASCII frame.
struct digital_rain digital_rain_t
Digital rain effect context.
digital_rain_t * digital_rain_init(int num_columns, int num_rows)
Initialize digital rain effect context.
char * ascii_create_grid(ascii_frame_source_t *sources, int source_count, int width, int height, size_t *out_size)
Create a grid layout from multiple ASCII frames.
Definition ascii.c:708
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
char * ansi_expand_rle(const char *input, size_t input_len)
Expand RLE escape sequences in a string.
Definition rle.c:14
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
SIMD-optimized ASCII conversion interface.
🆘 Interactive keyboard help overlay for session keyboard shortcuts
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
bool ascii_render_palette_supported(ascii_renderer_t kind, const char *palette)
#define ascii_stabilizer_reset
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:716
void signal_exit(void)
Definition main.c:262
NEON-optimized ASCII rendering functions.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
ASCII Palette Management for Video-to-ASCII Conversion.
#define MIN(a, b)
Definition param.h:6
#define MAX(a, b)
Definition param.h:10
bool g_snapshot_first_frame_rendered
asciichat_error_t options_read_snapshot(options_snapshot_t *snapshot)
Definition rcu.c:934
struct terminal_fd_reader_s terminal_fd_reader_t
Read ANSI ASCII frames from file descriptor, chunked by height.
asciichat_error_t ui_reconnect_controller_set(bool visible, const ui_reconnect_view_t *view)
Definition reconnect.c:299
#define FRAME_RENDER_CONTRACT_RAIN
void render_file_set_snapshot_actual_duration(render_file_ctx_t *ctx, double actual_duration_sec)
Definition renderer.c:350
asciichat_error_t render_file_write_frame(render_file_ctx_t *ctx, const char *frame, uint64_t captured_ns)
Definition renderer.c:329
void render_file_set_live_timing(render_file_ctx_t *ctx)
Definition renderer.c:252
asciichat_error_t render_file_create(const char *output_path, int cols, int rows, int fps, int theme, render_file_ctx_t **out)
Definition renderer.c:53
asciichat_error_t render_file_destroy(render_file_ctx_t *ctx)
Definition renderer.c:356
void render_file_begin_drain(render_file_ctx_t *ctx, uint64_t total, bool total_known)
Definition renderer.c:345
Terminal-to-pixel renderer and render-file output (audio + video).
struct render_file_ctx_s render_file_ctx_t
Definition renderer.h:69
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
Intro and status screen display for ascii-chat with animated rainbow effects.
void session_display_release_ascii(session_display_ctx_t *ctx, char *ascii)
void session_display_reset_stabilizer(session_display_ctx_t *ctx, bool recording)
asciichat_error_t session_display_init_render_file(session_display_ctx_t *ctx, uint32_t fps)
Perform complete terminal reset.
char * session_display_convert_to_ascii_reuse(session_display_ctx_t *ctx, const image_t *image)
void session_display_set_render_live_timing(session_display_ctx_t *ctx)
void session_display_write_ascii_frame(session_display_ctx_t *ctx, const char *ascii, bool fresh)
🖥️ Unified terminal display abstraction for session-based rendering
uint64_t g_snapshot_first_frame_rendered_ns
Centralized render loop abstraction for all display modes.
tty_info_t get_current_tty(void)
terminal_capabilities_t apply_color_mode_override(terminal_capabilities_t caps, const terminal_options_t *)
int terminal_flush(int fd)
terminal_capabilities_t detect_terminal_capabilities(const terminal_options_t *options)
int terminal_get_size_fd(int fd, terminal_size_t *size)
unsigned short int terminal_get_effective_height(int height_option, unsigned short fallback_height)
bool terminal_is_interactive(void)
bool terminal_is_stdin_tty(void)
bool terminal_is_stdout_tty(void)
unsigned short int terminal_get_effective_width(int width_option, unsigned short fallback_width)
bool terminal_should_force_stderr(void)
🔤 String Manipulation and Shell Escaping Utilities
acip render settings keeps the values that move through the subsystem: caps, width,...
Frame source structure for grid layout.
Definition ascii.h:350
uint64_t fixed_step_ns
Definition stabilize.h:30
Atomic value wrapper for integral/boolean types.
Definition atomic.h:114
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
When code needs to work with audio device info, it keeps index, max_input_channels,...
audio_ring_buffer_t * playback_buffer
atomic_t read_index
Read index (consumer position) - LOCK-FREE with atomic operations.
Definition ringbuffer.h:220
atomic_t write_index
Write index (producer position) - LOCK-FREE with atomic operations.
Definition ringbuffer.h:218
float data[192000]
Audio sample data buffer.
Definition ringbuffer.h:216
Growable byte buffer for assembling one complete terminal frame.
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
int width
Terminal width in characters (int for OPTION_TYPE_INT compat).
Definition options.h:991
Dynamic output buffer (auto-expanding).
char * buf
Buffer pointer (allocated, owned by caller, must be freed).
Validated luminance palette used to turn brightness into characters.
Definition palette.h:130
Terminal-rendering and snapshot settings used to create a display context.
void * callback_data
Opaque data passed to should_exit_callback.
palette_type_t palette_type
Palette type for ASCII rendering.
void * audio_ctx
Audio context for playback (borrowed, not owned).
bool defer_render_file
Defer render-file encoder creation until media timing is known.
const char * custom_palette
Custom palette characters (required if palette_type == PALETTE_CUSTOM).
bool enable_audio_playback
Enable audio playback (mirror mode).
session_display_should_exit_fn should_exit_callback
Optional: callback to check if initialization should be cancelled (e.g., shutdown signal).
uint32_t render_fps
Video FPS for render-file encoding (0 = use default/option).
bool snapshot_mode
Enable snapshot mode (single frame capture).
terminal_color_mode_t color_mode
Color mode override (TERM_COLOR_AUTO for auto-detection).
Runtime terminal state and reusable workspaces for ASCII rendering.
char luminance_palette[ASCII_LUMINANCE_LEVELS]
Luminance-to-character mapping table (256 entries).
bool has_tty
True if we have a valid TTY for interactive output.
tty_info_t tty_info
TTY information (file descriptor, path, ownership).
digital_rain_t * digital_rain
Digital rain effect context (NULL if disabled).
char palette_chars[ASCII_PALETTE_BUFFER_SIZE]
Palette character string for rendering.
uint64_t last_frame_time_ns
Last frame timestamp for digital rain delta time calculation.
bool initialized
Context is fully initialized.
atomic_t first_frame
First frame flag for logging control.
render_file_ctx_t * render_file
Render-to-file context (NULL if disabled).
void * audio_ctx
Audio context for playback (borrowed, not owned).
atomic_t output_failed
Stop submitting frames after the output consumer disappears.
terminal_capabilities_t caps
Detected terminal capabilities.
bool audio_playback_enabled
Audio playback is enabled.
palette_type_t palette_type
Configured palette type.
bool snapshot_mode
Snapshot mode enabled.
uint32_t render_fps
Video FPS for render-file encoding.
size_t palette_len
Number of characters in palette.
terminal_fd_reader_t * stdin_reader
Stdin frame reader for ASCII-to-video rendering (borrowed ref, not owned).
ascii_stabilizer_t recording_stabilizer
⏱️ High-precision timing utilities using sokol_time.h and uthash
#define UI_MEDIA_MIN_COLS
Definition too_small.h:9
#define UI_MEDIA_MIN_ROWS
Definition too_small.h:10
void ui_controller_remove(ui_screen_t screen)
void ui_controller_redraw(void)
void ui_controller_title_activity(ui_title_activity_t activity)
void ui_controller_title_ready(void)
int ui_controller_interactive_screen(void)
bool ui_controller_is_blocked(void)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
asciichat_error_t ui_controller_present_retained(ui_screen_t screen, int fd, terminal_size_t minimum, const char *data, size_t len)
asciichat_error_t ui_controller_present(ui_screen_t screen, int fd, terminal_size_t minimum, const char *data, size_t len)
@ UI_TITLE_ACTIVITY_IDLE
#define UI_CONTROLLER_MAX_FRAME_BYTES
@ UI_SCREEN_MEDIA
@ UI_SCREEN_SPLASH
@ UI_SCREEN_HELP
🔤 UTF-8 Encoding and Decoding Utilities
int platform_isatty(int fd)
Definition util.c:70
@ ASCII_RENDERER_GLYPH
audio_visualization_source_t
@ AUDIO_VISUALIZATION_SOURCE_MIX
@ AUDIO_VISUALIZATION_SOURCE_MEDIA
@ AUDIO_VISUALIZATION_SOURCE_MIC
@ AUDIO_VISUALIZATION_SOURCE_REMOTE
#define AUDIO_VISUALIZATION_COLOR_BRIGHTER
#define AUDIO_VISUALIZATION_COLOR_DARKER
char * audio_visualization_render_waveform(unsigned int width, unsigned int height, audio_visualization_source_t source, bool use_color, int color_mode, bool flip_x, bool flip_y)
Definition waveform.c:31
asciichat_error_t zalgo_apply(const char *input, size_t length, int level, size_t max_output_bytes, char **output)
Definition zalgo.c:68