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

🖥️ Unified terminal display implementation More...

Go to the source code of this file.

Data Structures

struct  session_display_ctx
 Runtime terminal state and reusable workspaces for ASCII rendering. More...

Typedefs

typedef struct session_display_ctx session_display_ctx_t
 Runtime terminal state and reusable workspaces for ASCII rendering.

Functions

asciichat_error_t session_display_init_render_file (session_display_ctx_t *ctx, uint32_t fps)
 Perform complete terminal reset.
session_display_ctx_t * session_display_create (const session_display_config_t *config)
 Create a new session display context.
void session_display_begin_drain (session_display_ctx_t *ctx, uint64_t total, bool total_known)
asciichat_error_t session_display_finish_render_file (session_display_ctx_t *ctx)
 Destroy session display context and free resources.
void session_display_destroy (session_display_ctx_t *ctx)
void session_display_set_stdin_reader (session_display_ctx_t *ctx, void *reader)
 Set stdin frame reader for ASCII-to-video rendering.
bool session_display_has_tty (session_display_ctx_t *ctx)
 Check if display has a TTY (terminal) available.
const terminal_capabilities_t * session_display_get_caps (session_display_ctx_t *ctx)
 Get detected terminal capabilities.
const char * session_display_get_palette_chars (session_display_ctx_t *ctx)
 Get the palette characters string.
size_t session_display_get_palette_len (session_display_ctx_t *ctx)
 Get the palette character count.
const char * session_display_get_luminance_palette (session_display_ctx_t *ctx)
 Get the luminance mapping palette.
int session_display_get_tty_fd (session_display_ctx_t *ctx)
 Get the TTY file descriptor.
void * session_display_get_stdin_reader (session_display_ctx_t *ctx)
 Get the stdin frame reader for ASCII-to-video rendering.
uint32_t session_display_get_render_fps (session_display_ctx_t *ctx)
 Get the render FPS configured for file output.
void session_display_set_render_fps (session_display_ctx_t *ctx, uint32_t fps)
 Set the render FPS for file output encoding.
bool session_display_has_first_frame (session_display_ctx_t *ctx)
 Check if the display has rendered its first frame.
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.
bool session_display_has_render_file (session_display_ctx_t *ctx)
 Check if display has render-file configured.
void session_display_render_frame (session_display_ctx_t *ctx, const char *frame_data)
 Render an ASCII frame to the terminal.
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.
char * session_display_convert_to_ascii_reuse (session_display_ctx_t *ctx, const image_t *image)
void session_display_reset_stabilizer (session_display_ctx_t *ctx, bool recording)
void session_display_release_ascii (session_display_ctx_t *ctx, char *ascii)
void session_display_write_ascii_frame (session_display_ctx_t *ctx, const char *ascii, bool fresh)
void session_display_set_render_live_timing (session_display_ctx_t *ctx)
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).
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.
void session_display_reset (session_display_ctx_t *ctx)
 Reset terminal to default state.
void session_display_clear (session_display_ctx_t *ctx)
 Clear the terminal screen.
void session_display_cursor_home (session_display_ctx_t *ctx)
 Move cursor to home position (top-left).
bool session_display_has_audio_playback (session_display_ctx_t *ctx)
 Check if display has audio playback configured.
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.
void session_display_set_global_context (session_display_ctx_t *ctx)
 Set the global display context (for signal handlers like Ctrl+C).
session_display_ctx_t * session_display_get_global_context (void)
 Get the global display context (used for signal handlers and special cleanup).
void session_display_set_global_context_public (session_display_ctx_t *ctx)
 Set the global display context (public setter for discovery cleanup).
void keyboard_help_signal_cancel (void)
 Request help screen closure from signal handler (Ctrl+C).
bool keyboard_help_check_signal_cancel (void)
 Check if help screen closure was requested by signal handler.
bool keyboard_help_is_active (session_display_ctx_t *ctx)
 Check if keyboard help is currently active.
bool keyboard_help_is_active_global (void)
 Check if keyboard help is active (global accessor for signal handlers).
void keyboard_help_toggle_global (void)
 Toggle keyboard help (global accessor for signal handlers).
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_ascii (session_display_ctx_t *ctx, const char *ascii)
 Write ASCII frame to terminal only (no encoding).

Detailed Description

🖥️ Unified terminal display implementation

Implements the session display abstraction layer for unified terminal rendering across client, mirror, and discovery modes.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026

Definition in file src/common/session/display.c.

Function Documentation

◆ session_display_convert_to_ascii_reuse()

char * session_display_convert_to_ascii_reuse ( session_display_ctx_t * ctx,
const image_t * image )

Single display owner; result must be released before its next conversion.

Definition at line 906 of file src/common/session/display.c.

906 {
907 ASCII_OTEL_SCOPE(SESSION_DISPLAY_CONVERT_TO_ASCII_REUSE);
908 return convert_to_ascii(ctx, image, true);
909}
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...

References ASCII_OTEL_SCOPE.

Referenced by session_pipeline_run_main(), and session_render_loop().

◆ session_display_init_render_file()

asciichat_error_t session_display_init_render_file ( session_display_ctx_t * ctx,
uint32_t fps )

Perform complete terminal reset.

Initialize render-file output after the capture frame rate is known.

Executes comprehensive terminal reset sequence for clean display state. Skips terminal control operations in snapshot mode.

Parameters
snapshot_modeWhether snapshot mode is enabled

Definition at line 172 of file src/common/session/display.c.

172 {
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}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned int uint32_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
#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 GET_OPTION(field)
Definition options.h:1339
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
render_file_ctx_t * render_file
Render-to-file context (NULL if disabled).
uint32_t render_fps
Video FPS for render-file encoding.

References asciichat_error_format(), ASCIICHAT_OK, asciichat_error_context_t::context_message, ERROR_INVALID_PARAM, GET_OPTION, HAS_ERRNO, height, log_error, log_info, session_display_ctx::render_file, render_file_create(), session_display_ctx::render_fps, SET_ERRNO, and width.

Referenced by session_display_create().

◆ session_display_release_ascii()

void session_display_release_ascii ( session_display_ctx_t * ctx,
char * ascii )

Definition at line 916 of file src/common/session/display.c.

916 {
917 if (!ctx || ascii != ctx->ascii_workspace.buf)
918 SAFE_FREE(ascii);
919}
#define SAFE_FREE(ptr)
char * buf
Buffer pointer (allocated, owned by caller, must be freed).

References session_display_ctx::ascii_workspace, outbuf_t::buf, and SAFE_FREE.

Referenced by session_pipeline_run_main(), and session_render_loop().

◆ session_display_reset_stabilizer()

void session_display_reset_stabilizer ( session_display_ctx_t * ctx,
bool recording )

Clear only the history owned by the calling display or recording worker.

Definition at line 911 of file src/common/session/display.c.

911 {
912 if (ctx)
913 ascii_stabilizer_reset(recording ? &ctx->recording_stabilizer : &ctx->stabilizer);
914}
#define ascii_stabilizer_reset
ascii_stabilizer_t recording_stabilizer

References ascii_stabilizer_reset, session_display_ctx::recording_stabilizer, and session_display_ctx::stabilizer.

Referenced by session_pipeline_run_main().

◆ session_display_set_render_live_timing()

void session_display_set_render_live_timing ( session_display_ctx_t * ctx)

Definition at line 1303 of file src/common/session/display.c.

1303 {
1304 if (ctx && ctx->render_file)
1306}
void render_file_set_live_timing(render_file_ctx_t *ctx)
Definition renderer.c:252

References session_display_ctx::render_file, and render_file_set_live_timing().

Referenced by session_pipeline_create().

◆ session_display_write_ascii_frame()

void session_display_write_ascii_frame ( session_display_ctx_t * ctx,
const char * ascii,
bool fresh )

Publish an acquired frame, or redraw retained content without advancing displayed FPS.

Definition at line 921 of file src/common/session/display.c.

921 {
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}
#define APP_CALLBACK_VOID(callback_name)
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.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
int color_mode
Definition fft.c:26
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
unsigned long long uint64_t
@ ERROR_BUFFER_FULL
@ ERROR_FILE_OPERATION
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#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
int splash_intro_done(void)
Signal that intro splash should end (first frame ready to render).
Definition splash.c:465
void splash_wait_for_animation(void)
Wait for splash animation thread to fully exit.
Definition splash.c:491
void strip_ansi_codes(const char *input, char *output, size_t output_size)
Strip ANSI escape codes from a string.
void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter)
Set digital rain color from color filter.
char * digital_rain_apply(digital_rain_t *rain, const char *frame, float delta_time)
Apply digital rain effect to ASCII frame.
char * ansi_expand_rle(const char *input, size_t input_len)
Expand RLE escape sequences in a string.
Definition rle.c:14
#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
#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 ui_reconnect_controller_set(bool visible, const ui_reconnect_view_t *view)
Definition reconnect.c:299
uint64_t g_snapshot_first_frame_rendered_ns
int terminal_flush(int fd)
int terminal_get_size_fd(int fd, terminal_size_t *size)
bool terminal_is_interactive(void)
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
Growable byte buffer for assembling one complete terminal frame.
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).
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.
atomic_t output_failed
Stop submitting frames after the output consumer disappears.
terminal_capabilities_t caps
Detected terminal capabilities.
bool snapshot_mode
Snapshot mode enabled.
#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_title_activity(ui_title_activity_t activity)
void ui_controller_title_ready(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
int platform_isatty(int fd)
Definition util.c:70
asciichat_error_t zalgo_apply(const char *input, size_t length, int level, size_t max_output_bytes, char **output)
Definition zalgo.c:68

References ansi_expand_rle(), APP_CALLBACK_VOID, ASCII_OTEL_SCOPE, asciichat_error_format(), ASCIICHAT_OK, atomic_exchange_bool(), atomic_fetch_add_u64(), atomic_load_bool(), atomic_store_bool(), session_display_ctx::caps, color_mode, session_display_ctx::digital_rain, digital_rain_apply(), digital_rain_set_color_from_filter(), ERROR_BUFFER_FULL, ERROR_FILE_OPERATION, ERROR_INVALID_PARAM, session_display_ctx::first_frame, g_snapshot_first_frame_rendered, g_snapshot_first_frame_rendered_ns, GET_OPTION, session_display_ctx::has_tty, session_display_ctx::initialized, session_display_ctx::last_frame_time_ns, log_debug, log_debug_every, log_dev, log_dev_every, log_error, log_file_msg(), log_warn_every, MAX, MIN, NS_PER_MS_INT, NS_PER_SEC_INT, session_display_ctx::output_failed, platform_isatty(), session_display_ctx::render_file, SAFE_FREE, SAFE_GETENV, SAFE_MALLOC, SAFE_REALLOC, SET_ERRNO, signal_exit(), session_display_ctx::snapshot_mode, splash_intro_done(), splash_wait_for_animation(), strip_ansi_codes(), terminal_flush(), terminal_get_size_fd(), terminal_is_interactive(), TIME_DURATION_BUFFER_SIZE, time_pretty(), session_display_ctx::tty_frame_buffer, session_display_ctx::tty_frame_capacity, session_display_ctx::tty_info, UI_CONTROLLER_MAX_FRAME_BYTES, ui_controller_present(), ui_controller_present_retained(), ui_controller_remove(), ui_controller_title_activity(), ui_controller_title_ready(), ui_controller_write(), UI_MEDIA_MIN_COLS, UI_MEDIA_MIN_ROWS, ui_reconnect_controller_set(), UI_SCREEN_MEDIA, UI_SCREEN_SPLASH, UI_TITLE_ACTIVITY_IDLE, US_PER_SEC_INT, and zalgo_apply().

Referenced by session_display_write_ascii(), and session_pipeline_run_main().