ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
ascii.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3
10
13
15#include <stdint.h>
16#include <sys/types.h>
17#include <stdio.h>
18#include <stdlib.h>
20#include <string.h>
21#include <sys/stat.h>
22#include <time.h>
23#include <math.h>
24
25#include <libplatform/compiler.h>
26#include <libplatform/system.h>
27#include <libplatform/terminal.h>
28#include <libplatform/terminal.h>
29
31#include <ascii-chat/common.h>
38#include <options/options.h>
43
44/* ============================================================================
45 * ASCII Art Video Processing
46 * ============================================================================
47 */
48
49/*
50 * Resize a source image to a terminal viewport while preserving its visual
51 * aspect ratio. The source is cropped to the viewport's aspect ratio first,
52 * so the output fills the viewport instead of introducing letterbox bars.
53 * Terminal cells are approximately twice as tall as they are wide, hence the
54 * factor of two in the source crop ratio.
55 */
56/* Nested resize calls occur during compositing; retain a small thread-local
57 * pool so the render loop never enters tracked allocation. */
58#define ASCII_RESIZE_WORKSPACE_POOL_SIZE 4
59static _Thread_local int g_resize_columns_workspace[ASCII_RESIZE_WORKSPACE_POOL_SIZE][IMAGE_MAX_WIDTH];
60static _Thread_local unsigned g_resize_workspace_depth;
61
62static void image_resize_cover(const image_t *source, image_t *dest, ssize_t viewport_width, ssize_t viewport_height) {
63 if (!source || !dest || source->w <= 0 || source->h <= 0 || dest->w <= 0 || dest->h <= 0 || viewport_width <= 0 || viewport_height <= 0) {
64 SET_ERRNO(ERROR_INVALID_PARAM, "invalid image or viewport dimensions");
65 return;
66 }
67
68 const double source_aspect = (double)source->w / (double)source->h;
69 const double viewport_aspect = (double)viewport_width / ((double)viewport_height * 2.0);
70 int crop_width = source->w;
71 int crop_height = source->h;
72 int crop_x = 0;
73 int crop_y = 0;
74
75 if (source_aspect > viewport_aspect) {
76 crop_width = (int)lround((double)source->h * viewport_aspect);
77 crop_width = crop_width < 1 ? 1 : crop_width;
78 crop_width = crop_width > source->w ? source->w : crop_width;
79 crop_x = (source->w - crop_width) / 2;
80 } else if (source_aspect < viewport_aspect) {
81 crop_height = (int)lround((double)source->w / viewport_aspect);
82 crop_height = crop_height < 1 ? 1 : crop_height;
83 crop_height = crop_height > source->h ? source->h : crop_height;
84 crop_y = (source->h - crop_height) / 2;
85 }
86
87 // Horizontal source coordinates are identical for every destination row.
88 unsigned workspace_index = g_resize_workspace_depth++ % ASCII_RESIZE_WORKSPACE_POOL_SIZE;
89 int *source_columns = g_resize_columns_workspace[workspace_index];
90 for (int x = 0; x < dest->w; ++x)
91 source_columns[x] = crop_x + (int)(((int64_t)x * crop_width) / dest->w);
92 int previous_source_y = -1;
93 for (int y = 0; y < dest->h; y++) {
94 int source_y = crop_y + (int)(((int64_t)y * crop_height) / dest->h);
95 rgb_pixel_t *dest_row = dest->pixels + ((size_t)y * (size_t)dest->w);
96 if (source_y == previous_source_y) {
97 memcpy(dest_row, dest_row - dest->w, (size_t)dest->w * sizeof(*dest_row));
98 continue;
99 }
100 previous_source_y = source_y;
101 const rgb_pixel_t *source_row = source->pixels + ((size_t)source_y * (size_t)source->w);
102 for (int x = 0; x < dest->w; x++) {
103 dest_row[x] = source_row[source_columns[x]];
104 }
105 }
106 --g_resize_workspace_depth;
107}
108
109// Fit the complete source into the physical viewport, leaving black bars.
110// Half-block sampling doubles the destination height without changing geometry.
111static void image_resize_contain(const image_t *source, image_t *dest, ssize_t columns, ssize_t rows) {
112 ssize_t fitted_columns, fitted_rows;
113 aspect_ratio(source->w, source->h, columns, rows, false, &fitted_columns, &fitted_rows);
114 int width = (int)(fitted_columns * dest->w / columns);
115 int height = (int)(fitted_rows * dest->h / rows);
116 int left = (dest->w - width) / 2;
117 int top = (dest->h - height) / 2;
118 for (int y = 0; y < height; ++y) {
119 int source_y = (int)((int64_t)y * source->h / height);
120 for (int x = 0; x < width; ++x) {
121 int source_x = (int)((int64_t)x * source->w / width);
122 dest->pixels[(y + top) * dest->w + x + left] = source->pixels[source_y * source->w + source_x];
123 }
124 }
125}
126
127asciichat_error_t ascii_write_init(int fd, bool reset_terminal) {
128 // Validate file descriptor
129 if (fd < 0) {
130 log_error("Invalid file descriptor %d", fd);
131 return ERROR_INVALID_PARAM;
132 }
133
134 // Only apply terminal control sequences if:
135 // 1. reset_terminal is true (caller wants terminal reset)
136 // 2. terminal_should_use_control_sequences() confirms it's safe (TTY, not snapshot, not testing)
137 if (reset_terminal && terminal_should_use_control_sequences(fd, GET_OPTION(snapshot_mode))) {
139
140 // Disable echo using platform abstraction
141 if (terminal_set_echo(false) != 0) {
142 log_error("Failed to disable echo for fd %d", fd);
143 return ERROR_TERMINAL;
144 }
145 // Hide cursor using platform abstraction
146 if (ui_controller_write(fd, "\033[?25l", 6) != ASCIICHAT_OK) {
147 log_warn("Failed to hide cursor");
148 }
149 }
150 log_dev("ASCII writer initialized");
151 return ASCIICHAT_OK;
152}
153
154char *ascii_convert(image_t *original, const ssize_t width, const ssize_t height, const bool color, const bool _aspect_ratio, const bool stretch, const char *palette_chars,
155 const char luminance_palette[ASCII_LUMINANCE_LEVELS]) {
156 if (original == NULL || !palette_chars || !luminance_palette) {
157 log_error("invalid parameters");
158 return NULL;
159 }
160
161 // Check for empty strings
162 if (palette_chars[0] == '\0' || luminance_palette[0] == '\0') {
163 log_error("empty palette strings");
164 return NULL;
165 }
166
167 // Start with the target dimensions requested by the user (or detected from
168 // the terminal). These can be modified by aspect_ratio() if stretching is
169 // disabled and one of the dimensions was left to be calculated
170 // automatically.
171 ssize_t resized_width = width;
172 ssize_t resized_height = height;
173
174 // If stretch is enabled, use full dimensions, otherwise calculate aspect ratio
175 if (_aspect_ratio) {
176 // The server now provides images at width*2 x height pixels
177 // The aspect_ratio function will handle terminal character aspect ratio
178 aspect_ratio(original->w, original->h, resized_width, resized_height, stretch, &resized_width, &resized_height);
179 }
180
181 // Calculate padding for centering
182 size_t pad_width = 0;
183 size_t pad_height = 0;
184
185 if (_aspect_ratio) {
186 // Only calculate padding when not stretching
187 ssize_t pad_width_ss = width > resized_width ? (width - resized_width) / 2 : 0;
188 pad_width = (size_t)pad_width_ss;
189
190 ssize_t pad_height_ss = height > resized_height ? (height - resized_height) / 2 : 0;
191 pad_height = (size_t)pad_height_ss;
192 }
193
194 // Resize the captured frame to the aspect-correct dimensions.
195 if (resized_width <= 0 || resized_height <= 0) {
196 log_error("Invalid dimensions for resize: width=%zd, height=%zd", resized_width, resized_height);
197 return NULL;
198 }
199
200 // Validate dimensions fit in image_t's int fields before casting
201 if (resized_width > INT_MAX || resized_height > INT_MAX) {
202 log_error("Dimensions exceed INT_MAX: width=%zd, height=%zd", resized_width, resized_height);
203 return NULL;
204 }
205
206 // Always resize to target dimensions
207 image_t *resized = image_new((size_t)resized_width, (size_t)resized_height);
208 if (!resized) {
209 log_error("Failed to allocate resized image");
210 return NULL;
211 }
212
213 image_clear(resized);
214 image_resize(original, resized);
215
216 char *ascii;
217 if (color) {
218 // Check for half-block mode first
219 if (GET_OPTION(render_mode) == RENDER_MODE_HALF_BLOCK) {
220 const uint8_t *rgb_data = (const uint8_t *)resized->pixels;
221 ascii = ascii_render_halfblocks(rgb_data, resized->w, resized->h, 0, ASCII_COLOR_TRUE, simd_cells_backend());
222 } else {
223 // Standard color modes (foreground/background)
224 bool use_background = (GET_OPTION(render_mode) == RENDER_MODE_BACKGROUND);
225 ascii = image_print_color_simd(resized, use_background, false, palette_chars);
226 }
227 } else {
228 // Use grayscale/monochrome conversion with client's palette
229 ascii = image_print(resized, palette_chars);
230 }
231
232 if (!ascii) {
233 log_error("Failed to convert image to ASCII");
234 image_destroy(resized);
235 return NULL;
236 }
237
238 size_t ascii_len = strlen(ascii);
239 if (ascii_len == 0) {
240 log_error("ASCII conversion returned empty string (resized dimensions: %dx%d)", resized->w, resized->h);
241 SAFE_FREE(ascii);
242 image_destroy(resized);
243 return NULL;
244 }
245
246 char *ascii_width_padded = ascii_pad_frame_width(ascii, pad_width);
247 SAFE_FREE(ascii);
248
249 char *ascii_padded = ascii_pad_frame_height(ascii_width_padded, pad_height);
250 SAFE_FREE(ascii_width_padded);
251
252 // Only destroy resized if we allocated it (not when using original directly)
253 image_destroy(resized);
254
255 return ascii_padded;
256}
257
258// Capability-aware ASCII conversion using terminal capabilities
259char *ascii_convert_with_capabilities(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch,
260 const char *palette_chars) {
261
262 return ascii_convert_with_capabilities_fit(original, width, height, caps, use_aspect_ratio, stretch, palette_chars, false);
263}
264
265char *ascii_convert_with_capabilities_fit(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch,
266 const char *palette_chars, const bool contain) {
267
268 return ascii_convert_with_capabilities_workspace(original, width, height, caps, use_aspect_ratio, stretch, palette_chars, contain, NULL);
269}
270
271char *ascii_convert_with_capabilities_workspace(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch,
272 const char *palette_chars, const bool contain, image_t **workspace) {
273
274 return ascii_convert_with_buffers(original, width, height, caps, use_aspect_ratio, stretch, palette_chars, contain, workspace, NULL);
275}
276
277char *ascii_convert_with_buffers(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch,
278 const char *palette_chars, const bool contain, image_t **workspace, outbuf_t *output) {
279 return ascii_convert_with_buffers_stabilized(original, width, height, caps, use_aspect_ratio, stretch, palette_chars, contain, workspace, output, NULL);
280}
281
282char *ascii_convert_with_buffers_stabilized(image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch,
283 const char *palette_chars, const bool contain, image_t **workspace, outbuf_t *output, ascii_stabilizer_t *stabilizer) {
284 if (original == NULL || caps == NULL) {
285 log_error("Invalid parameters for ascii_convert_with_capabilities");
286 return NULL;
287 }
288
289 // Validate original image dimensions to detect corruption
290 if (original->w <= 0 || original->w > 10000 || original->h <= 0 || original->h > 10000) {
291 log_error("Invalid original image dimensions detected: w=%d, h=%d (likely corrupted)", original->w, original->h);
292 return NULL;
293 }
294
295 if (original->pixels == NULL) {
296 log_error("Original image pixels pointer is NULL");
297 return NULL;
298 }
299
300 // Start with the target dimensions requested by the user.
301 ssize_t resized_width = width;
302 ssize_t resized_height = height;
303
304 // Both contain and cover produce a complete viewport, including any black bars.
305
306 // Preserve an 8x8 sample grid for each glyph in the experimental renderer.
307 bool explicit_palette = caps->palette_explicit;
308 if (caps->text_renderer == ASCII_RENDERER_GLYPH && explicit_palette && !ascii_render_palette_supported(ASCII_RENDERER_GLYPH, palette_chars)) {
309 SET_ERRNO(ERROR_INVALID_PARAM, "Glyph palette contains characters without glyph masks");
310 return NULL;
311 }
312 bool glyph_match = caps->text_renderer == ASCII_RENDERER_GLYPH && caps->render_mode != RENDER_MODE_HALF_BLOCK && resized_width > 0 && resized_height > 0 && resized_width <= IMAGE_MAX_WIDTH / 8 &&
313 resized_height <= IMAGE_MAX_HEIGHT / 8;
314 if (glyph_match) {
315 resized_width *= 8;
316 resized_height *= 8;
317 }
318
319 // Half-block mode doubles height for 2x vertical resolution (AFTER aspect ratio)
320 if (caps->render_mode == RENDER_MODE_HALF_BLOCK) {
321 resized_height = resized_height * 2;
322 }
323
324 // Fitting is performed inside the pixel viewport, so ANSI padding is not needed.
325 size_t pad_width = 0;
326 size_t pad_height = 0;
327
328 // Resize the captured frame to the aspect-correct dimensions
329 if (resized_width <= 0 || resized_height <= 0) {
330 log_error("Invalid dimensions for resize: width=%zd, height=%zd", resized_width, resized_height);
331 return NULL;
332 }
333
334 // Validate dimensions fit in image_t's int fields before casting
335 if (resized_width > INT_MAX || resized_height > INT_MAX) {
336 log_error("Dimensions exceed INT_MAX: width=%zd, height=%zd", resized_width, resized_height);
337 return NULL;
338 }
339
340 // PROFILING: Time image allocation and resize
341 uint64_t prof_alloc_start_ns = time_get_ns();
342
343 if (workspace && *workspace && ((*workspace)->w != resized_width || (*workspace)->h != resized_height)) {
344 image_destroy(*workspace);
345 *workspace = NULL;
346 }
347 image_t *resized = workspace ? *workspace : NULL;
348 if (!resized)
349 resized = image_new((size_t)resized_width, (size_t)resized_height);
350 if (workspace)
351 *workspace = resized;
352 if (!resized) {
353 log_error("Failed to allocate resized image");
354 return NULL;
355 }
356
357 image_clear(resized);
358
359 uint64_t prof_alloc_end_ns = time_get_ns();
360
361 uint64_t prof_resize_start_ns = prof_alloc_end_ns;
362
363 if (use_aspect_ratio && !stretch) {
364 // Fit using terminal cells; half-block pixel height is only the sampling resolution.
365 if (contain)
366 image_resize_contain(original, resized, width, height);
367 else
368 image_resize_cover(original, resized, width, height);
369 } else {
370 image_resize(original, resized);
371 }
372
373 uint64_t prof_resize_end_ns = time_get_ns();
374
375 // Check original image before resize (validate dimensions to prevent integer overflow)
376 int orig_black = 0, orig_total = 0;
377 if (original->w > 0 && original->w <= 10000 && original->h > 0 && original->h <= 10000) {
378 int64_t total_pixels = (int64_t)original->w * original->h;
379 int sample_size = (total_pixels < 1000) ? (int)total_pixels : 1000;
380 for (int i = 0; i < sample_size; i++) {
381 rgb_pixel_t p = original->pixels[i];
382 orig_total++;
383 if (p.r == 0 && p.g == 0 && p.b == 0)
384 orig_black++;
385 }
386 log_debug_every(5 * NS_PER_SEC_INT, ">>> ORIGINAL image: %d/%d pixels are black (%.1f%%), first pixel=RGB(%d,%d,%d)\n", orig_black, orig_total,
387 orig_total > 0 ? 100.0 * orig_black / orig_total : 0, original->pixels[0].r, original->pixels[0].g, original->pixels[0].b);
388 } else {
389 log_warn("Skipping debug check: corrupted image dimensions (w=%d, h=%d)", original->w, original->h);
390 }
391
392 // PROFILING: Time ASCII print
393 uint64_t prof_print_start_ns = prof_resize_end_ns;
394
395 // DEBUG: Log dimensions going to renderer
396 log_debug_every(10 * US_PER_SEC_INT, "original=%dx%d, requested=%zdx%zd, resized=%dx%d, pad=%zux%zu (mode=%d)", original->w, original->h, width, height, resized->w, resized->h, pad_width,
397 pad_height, caps->render_mode);
398
399 // Check if image is all black
400 int black_pixels = 0, total_pixels = 0;
401 for (int i = 0; i < resized->w * resized->h && i < 1000; i++) {
402 rgb_pixel_t p = resized->pixels[i];
403 total_pixels++;
404 if (p.r == 0 && p.g == 0 && p.b == 0)
405 black_pixels++;
406 }
407 log_debug_every(5 * NS_PER_SEC_INT, ">>> Resized image check: %d/%d pixels are black (%.1f%%), first pixel=RGB(%d,%d,%d)\n", black_pixels, total_pixels,
408 total_pixels > 0 ? 100.0 * black_pixels / total_pixels : 0, resized->pixels[0].r, resized->pixels[0].g, resized->pixels[0].b);
409
410 // Apply the target client's filter after resizing, so it is scoped to this
411 // client and never mutates the shared source frame.
412 if (caps->color_filter != COLOR_FILTER_NONE) {
413 const float time_seconds = (float)time_get_ns() / (float)NS_PER_SEC_INT;
414 if (apply_color_filter((uint8_t *)resized->pixels, (uint32_t)resized->w, (uint32_t)resized->h, (uint32_t)(resized->w * sizeof(rgb_pixel_t)), caps->color_filter, time_seconds) != 0) {
415 log_warn("Failed to apply client color filter %d", caps->color_filter);
416 }
417 }
418
419 // Use the capability-aware image printing function with client's palette
420 // History belongs to this stream and is scoped to the current thread's conversion.
421 ascii_stabilizer_t *active_stabilizer = NULL;
422 if (stabilizer) {
423 uint64_t configuration = 1469598103934665603ULL;
424 const unsigned values[] = {(unsigned)caps->text_renderer, (unsigned)caps->color_level, (unsigned)caps->render_mode, (unsigned)caps->color_filter, (unsigned)explicit_palette,
425 (unsigned)use_aspect_ratio, (unsigned)stretch, (unsigned)contain, (unsigned)original->w, (unsigned)original->h};
426 for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) {
427 configuration ^= values[i];
428 // FNV multiplication intentionally wraps modulo 2^64.
429 (void)__builtin_mul_overflow(configuration, 1099511628211ULL, &configuration);
430 }
431 if (palette_chars) {
432 for (const unsigned char *p = (const unsigned char *)palette_chars; *p; ++p) {
433 configuration ^= *p;
434 (void)__builtin_mul_overflow(configuration, 1099511628211ULL, &configuration);
435 }
436 }
437 size_t history_height = (size_t)height * (caps->render_mode == RENDER_MODE_HALF_BLOCK ? 2u : 1u);
438 if (ascii_stabilizer_prepare(stabilizer, (size_t)width, history_height, configuration) == ASCIICHAT_OK) {
439 uint64_t now = time_get_ns();
440 stabilizer->elapsed_ns =
441 stabilizer->fixed_step_ns ? stabilizer->fixed_step_ns : (stabilizer->last_timestamp_ns && now >= stabilizer->last_timestamp_ns ? now - stabilizer->last_timestamp_ns : UINT64_MAX);
442 stabilizer->last_timestamp_ns = now;
443 active_stabilizer = stabilizer;
444 }
445 }
446 ascii_stabilizer_t *previous_stabilizer = ascii_stabilizer_set_target(active_stabilizer);
447 outbuf_t *previous_output = ascii_render_set_output_target(output);
448 ascii_color_t glyph_color = caps->color_level == TERM_COLOR_TRUECOLOR ? ASCII_COLOR_TRUE
449 : caps->color_level == TERM_COLOR_256 ? ASCII_COLOR_256
450 : caps->color_level == TERM_COLOR_16 ? ASCII_COLOR_16
452 const ascii_render_options_t glyph_options = {.kind = ASCII_RENDERER_GLYPH,
453 .color = glyph_color,
454 .palette = explicit_palette ? palette_chars : NULL,
455 .backend = simd_cells_backend(),
456 .background = caps->render_mode == RENDER_MODE_BACKGROUND};
457 char *ascii = glyph_match ? ascii_render_image(resized, &glyph_options) : image_print_with_capabilities(resized, caps, palette_chars);
458 ascii_render_set_output_target(previous_output);
459 ascii_stabilizer_set_target(previous_stabilizer);
460
461 uint64_t prof_print_end_ns = time_get_ns();
462
463 uint64_t alloc_time_us = time_ns_to_us(time_elapsed_ns(prof_alloc_start_ns, prof_alloc_end_ns));
464 uint64_t resize_time_us = time_ns_to_us(time_elapsed_ns(prof_resize_start_ns, prof_resize_end_ns));
465 uint64_t print_time_us = time_ns_to_us(time_elapsed_ns(prof_print_start_ns, prof_print_end_ns));
466
467 // PROFILING: Time padding
468 uint64_t prof_pad_start_ns = time_get_ns();
469
470 if (!ascii) {
471 log_error("Failed to convert image to ASCII using terminal capabilities");
472 if (!workspace)
473 image_destroy(resized);
474 return NULL;
475 }
476
477 size_t ascii_len = strlen(ascii);
478 if (ascii_len == 0) {
479 log_error("Capability-aware ASCII conversion returned empty string (resized dimensions: %dx%d)", resized->w, resized->h);
480 if (!output)
481 SAFE_FREE(ascii);
482 if (!workspace)
483 image_destroy(resized);
484 return NULL;
485 }
486
487 // Pixel fitting already produced the complete viewport. Return that buffer
488 // directly instead of allocating two identical copies for zero padding.
489 char *ascii_padded = ascii;
490
491 uint64_t prof_pad_end_ns = time_get_ns();
492
493 uint64_t pad_time_ns = time_elapsed_ns(prof_pad_start_ns, prof_pad_end_ns);
494 log_debug_every(US_PER_SEC_INT, "ASCII_STAGE: alloc_ms=%.3f resize_ms=%.3f glyph_ms=%.3f padding_ms=%.3f bytes=%zu", (double)alloc_time_us / 1000, (double)resize_time_us / 1000,
495 (double)print_time_us / 1000, (double)pad_time_ns / NS_PER_MS_INT, ascii_len);
496
497 if (!workspace)
498 image_destroy(resized);
499
500 return ascii_padded;
501}
502
503// NOTE: ascii_convert_with_custom_palette removed - use ascii_convert_with_capabilities() with enhanced
504// terminal_capabilities_t
505
506asciichat_error_t ascii_write(const char *frame) {
507 if (frame == NULL) {
508 log_warn("Attempted to write NULL frame");
509 return ERROR_INVALID_PARAM;
510 }
511
512 if (!terminal_should_use_control_sequences(STDOUT_FILENO, GET_OPTION(snapshot_mode)))
513 return ui_controller_write(STDOUT_FILENO, frame, strlen(frame));
514 size_t len = strlen(frame);
515 char *output = SAFE_MALLOC(len + 3, char *);
516 if (!output)
517 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate ASCII presentation");
518 memcpy(output, "\033[H", 3);
519 memcpy(output + 3, frame, len);
520 asciichat_error_t result = ui_controller_present(UI_SCREEN_MEDIA, STDOUT_FILENO, (terminal_size_t){.cols = UI_MEDIA_MIN_COLS, .rows = UI_MEDIA_MIN_ROWS}, output, len + 3);
521 SAFE_FREE(output);
522 return result;
523}
524
525void ascii_write_destroy(int fd, bool reset_terminal) {
526#if PLATFORM_WINDOWS
527 (void)fd; // Unused on Windows - terminal operations use stdout directly
528#endif
529 // console_clear(fd);
530 // cursor_reset(fd);
531 // Only restore terminal state if:
532 // 1. reset_terminal is true (caller wants terminal restore)
533 // 2. terminal_should_use_control_sequences() confirms it's safe (TTY, not snapshot, not testing)
534 if (reset_terminal && terminal_should_use_control_sequences(fd, GET_OPTION(snapshot_mode))) {
535 // Show cursor using platform abstraction
536 if (ui_controller_write(fd, "\033[?25h", 6) != ASCIICHAT_OK) {
537 log_warn("Failed to show cursor");
538 }
539
540 // Re-enable echo using platform abstraction
541 if (terminal_set_echo(true) != 0) {
542 log_warn("Failed to re-enable echo");
543 }
544 }
545 log_debug("ASCII writer destroyed");
546}
547
548/*
549 * Pads each line of an ASCII frame with a given number of leading space
550 * characters. The function allocates a new buffer large enough to hold the
551 * padded frame and returns a pointer to it. The caller is responsible for
552 * freeing the returned buffer.
553 *
554 * Parameters:
555 * frame The original, null-terminated ASCII frame. It is expected to
556 * contain `\n` at the end of every visual row.
557 * pad_left How many space characters to add in front of every visual row.
558 *
559 * Returns:
560 * A newly allocated, null-terminated string that contains the padded frame
561 * on success, or NULL if either `frame`.
562 */
563char *ascii_pad_frame_width(const char *frame, size_t pad_left) {
564 if (!frame) {
565 SET_ERRNO(ERROR_INVALID_PARAM, "frame is NULL");
566 return NULL;
567 }
568
569 if (pad_left == 0) {
570 // Nothing to do; return a copy so the caller can free it safely without
571 // worrying about the original allocation strategy.
572 size_t orig_len = strlen(frame);
573 char *copy;
574 copy = SAFE_MALLOC(orig_len + 1, char *);
575 SAFE_MEMCPY(copy, orig_len + 1, frame, orig_len + 1);
576 return copy;
577 }
578
579 // Count how many visual rows we have (lines terminated by '\n') to determine
580 // the final buffer size.
581 size_t line_count = 1; // There is always at least the first line
582 const char *char_in_frame = frame;
583 while (*char_in_frame) {
584 if (*char_in_frame == '\n') {
585 line_count++;
586 }
587 char_in_frame++;
588 }
589
590 // Total length of the source plus padding.
591 const size_t frame_len = strlen(frame);
592 const size_t left_padding_len = line_count * pad_left;
593 const size_t total_len = frame_len + left_padding_len;
594
595 char *buffer;
596 buffer = SAFE_MALLOC(total_len + 1, char *);
597
598 // Build the padded frame.
599 bool at_line_start = true;
600 const char *src = frame;
601 char *position = buffer;
602
603 while (*src) {
604 if (at_line_start) {
605 // Insert the requested amount of spaces in front of every visual row.
606 size_t remaining = (size_t)((ptrdiff_t)(buffer + total_len + 1) - (ptrdiff_t)position);
607 SAFE_MEMSET(position, remaining, ' ', (size_t)pad_left);
608 position += pad_left;
609 at_line_start = false;
610 }
611
612 *position++ = *src;
613
614 if (*src == '\n') {
615 at_line_start = true;
616 }
617
618 src++;
619 }
620
621 *position = '\0';
622 return buffer;
623}
624
625asciichat_error_t ascii_grid_layout(int source_count, int width, int height, int *grid_cols, int *grid_rows) {
626 if (source_count <= 0 || width <= 0 || height <= 0 || !grid_cols || !grid_rows)
627 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid grid dimensions");
628 // Multiple sources: create grid layout
629 // Calculate grid dimensions that maximize the use of terminal space
630 // Character aspect ratio: terminal chars are typically ~2x taller than wide
631 float char_aspect = 2.0f;
632
633 float best_score = -1.0f;
634 int best_cols = 1;
635 int best_rows = source_count;
636
637 // Try all possible grid configurations
638 for (int test_cols = 1; test_cols <= source_count; test_cols++) {
639 int test_rows = (int)ceil((double)source_count / test_cols);
640
641 // Skip configurations with too many empty cells
642 int empty_cells = (test_cols * test_rows) - source_count;
643 if (empty_cells > source_count / 2)
644 continue; // Don't waste more than 50% space
645
646 // Calculate the size each cell would have
647 int cell_width = (width - (test_cols - 1)) / test_cols; // -1 per separator
648 int cell_height = (height - (test_rows - 1)) / test_rows; // -1 per separator
649
650 // Skip if cells would be too small
651 if (cell_width < 10 || cell_height < 3)
652 continue;
653
654 // Calculate the aspect ratio of each cell (accounting for char aspect)
655 float cell_aspect = ((float)cell_width / (float)cell_height) / char_aspect;
656
657 // Score based on how close to square (1:1) each video cell would be
658 // This naturally adapts to any terminal size
659 float aspect_score = 1.0f - fabsf(logf(cell_aspect)); // log makes it symmetric around 1
660 if (aspect_score < 0)
661 aspect_score = 0;
662
663 // Bonus for better space utilization
664 float utilization = (float)source_count / (float)(test_cols * test_rows);
665
666 // For 2 clients specifically, heavily weight the aspect score
667 // This makes 2 clients naturally go horizontal on wide terminals and vertical on tall ones
668 float total_score;
669 if (source_count == 2) {
670 // For 2 clients, we want the layout that gives the most square-ish cells
671 total_score = aspect_score * 0.9f + utilization * 0.1f;
672 } else {
673 // For 3+ clients, balance aspect ratio with space utilization
674 total_score = aspect_score * 0.7f + utilization * 0.3f;
675 }
676
677 // Small bonus for simpler grids (prefer 2x2 over 3x1, etc.)
678 if (test_cols == test_rows) {
679 total_score += 0.05f; // Slight preference for square grids
680 }
681
682 if (total_score > best_score) {
683 best_score = total_score;
684 best_cols = test_cols;
685 best_rows = test_rows;
686 }
687 }
688
689 *grid_cols = best_cols;
690 *grid_rows = best_rows;
691 return ASCIICHAT_OK;
692}
693
708char *ascii_create_grid(ascii_frame_source_t *sources, int source_count, int width, int height, size_t *out_size) {
709 if (!sources || source_count <= 0 || width <= 0 || height <= 0 || !out_size) {
710 return NULL;
711 }
712
713 int grid_cols, grid_rows;
714 if (ascii_grid_layout(source_count, width, height, &grid_cols, &grid_rows) != ASCIICHAT_OK)
715 return NULL;
716
717 // Calculate dimensions for each cell (leave 1 char for separators)
718 int cell_width = (width - (grid_cols - 1)) / grid_cols;
719 int cell_height = (height - (grid_rows - 1)) / grid_rows;
720
721 if (source_count > 1 && (cell_width < 10 || cell_height < 3)) {
722 // Too small for grid layout, just use first source
723 char *result;
724 result = SAFE_MALLOC(sources[0].frame_size + 1, char *);
725 if (sources[0].frame_data && sources[0].frame_size > 0) {
726 SAFE_MEMCPY(result, sources[0].frame_size + 1, sources[0].frame_data, sources[0].frame_size);
727 result[sources[0].frame_size] = '\0';
728 *out_size = sources[0].frame_size;
729 } else {
730 // Handle NULL or empty frame data
731 result[0] = '\0';
732 *out_size = 0;
733 }
734 return result;
735 }
736
737 if (source_count == 1) {
738 source_count = 1;
739 grid_cols = grid_rows = 1;
740 cell_width = width;
741 cell_height = height;
742 }
743
744 // ANSI bytes consume storage but no terminal columns. Build rows in order
745 // instead of copying colored strings into fixed one-byte character slots.
747 if (!buf)
748 return NULL;
749 size_t *positions = SAFE_CALLOC((size_t)source_count, sizeof(size_t), size_t *);
750 int vertical_padding = 0;
751 if (source_count == 1 && sources[0].frame_data) {
752 int lines = 0;
753 size_t length = strnlen(sources[0].frame_data, sources[0].frame_size);
754 for (size_t i = 0; i < length; ++i)
755 if (sources[0].frame_data[i] == '\n')
756 ++lines;
757 if (length && sources[0].frame_data[length - 1] != '\n')
758 ++lines;
759 vertical_padding = lines < height ? (height - lines) / 2 : 0;
760 }
761
762 for (int row = 0; row < height; ++row) {
763 int grid_row = row / (cell_height + 1);
764 int cell_row = row % (cell_height + 1);
765 int columns = 0;
766 for (int col = 0; col < grid_cols; ++col) {
767 int src = grid_row * grid_cols + col;
768 bool separator = cell_row == cell_height && grid_row < grid_rows - 1;
769 int visible = 0;
770 if (!separator && src < source_count && sources[src].frame_data && row >= vertical_padding) {
771 const char *data = sources[src].frame_data;
772 size_t start = positions[src];
773 size_t end = start;
774 while (end < sources[src].frame_size && data[end] && data[end] != '\n')
775 ++end;
776 size_t line_length = end - start;
777 if (line_length > INT_MAX) {
778 SAFE_FREE(positions);
780 SET_ERRNO(ERROR_INVALID_PARAM, "ASCII source line exceeds supported length");
781 return NULL;
782 }
783 size_t copy = utf8_prefix_bytes_for_width(data + start, line_length, cell_width);
784 visible = utf8_display_width_n(data + start, copy);
785 int padding = source_count == 1 ? (cell_width - visible) / 2 : 0;
786 for (int i = 0; i < padding; ++i)
787 frame_buffer_append(buf, " ", 1);
788 frame_buffer_append(buf, data + start, (size_t)copy);
789 if (memchr(data + start, '\033', (size_t)copy))
790 frame_buffer_append(buf, "\033[0m", 4);
791 visible += padding;
792 positions[src] = end < sources[src].frame_size && data[end] == '\n' ? end + 1 : end;
793 }
794 for (int i = visible; i < cell_width; ++i)
795 frame_buffer_append(buf, separator ? "_" : " ", 1);
796 columns += cell_width;
797 if (col < grid_cols - 1) {
798 frame_buffer_append(buf, separator ? "+" : "|", 1);
799 ++columns;
800 }
801 }
802 for (; columns < width; ++columns)
803 frame_buffer_append(buf, " ", 1);
804 if (row < height - 1)
805 frame_buffer_append(buf, "\r\n", 2);
806 }
807 SAFE_FREE(positions);
808 *out_size = frame_buffer_get_length(buf);
809 char *result = SAFE_MALLOC(*out_size + 1, char *);
810 memcpy(result, frame_buffer_get_content(buf), *out_size);
811 result[*out_size] = '\0';
813 return result;
814}
815
831char *ascii_pad_frame_height(const char *frame, size_t pad_top) {
832 if (!frame) {
833 return NULL;
834 }
835
836 if (pad_top == 0) {
837 // Nothing to do; return a copy because the caller knows to free() the value.
838 size_t orig_len = strlen(frame);
839 char *copy;
840 copy = SAFE_MALLOC(orig_len + 1, char *);
841 SAFE_MEMCPY(copy, orig_len + 1, frame, orig_len + 1);
842 return copy;
843 }
844
845 // Calculate buffer size needed
846 // Each padding row needs: 1 newline character per padding row
847 size_t frame_len = strlen(frame);
848 size_t top_padding_len = pad_top; // 1 newline per padding row
849 size_t total_len = top_padding_len + frame_len;
850
851 char *buffer;
852 buffer = SAFE_MALLOC(total_len + 1, char *);
853
854 char *position = buffer;
855
856 // Add top padding with plain newlines
857 // Use plain newlines instead of ANSI escape sequences so the output works
858 // when redirected to pipes or files, not just TTY
859 for (size_t i = 0; i < pad_top; i++) {
860 *position++ = '\n';
861 }
862
863 // Copy the original frame
864 size_t remaining = frame_len + 1;
865 SAFE_MEMCPY(position, remaining, frame, frame_len);
866 position += frame_len;
867 *position = '\0';
868
869 return buffer;
870}
871
884char *image_print_with_capabilities(const image_t *image, const terminal_capabilities_t *caps, const char *palette) {
885 if (!image || !caps || !palette) {
886 return NULL;
887 }
888
889 terminal_color_mode_t color_level = caps->color_level;
890 terminal_render_mode_t render_mode = caps->render_mode;
891
892 // Half-block mode: dispatch to halfblock renderers by color depth
893 if (render_mode == RENDER_MODE_HALF_BLOCK) {
894 const uint8_t *rgb_data = (const uint8_t *)image->pixels;
895 switch (color_level) {
896 case TERM_COLOR_TRUECOLOR:
898 case TERM_COLOR_256:
900 case TERM_COLOR_16:
902 case TERM_COLOR_NONE:
903 case TERM_COLOR_AUTO:
904 default:
906 }
907 }
908
909 // Foreground/background modes: dispatch by color depth
910 switch (color_level) {
911 case TERM_COLOR_TRUECOLOR: {
912 bool use_background = (render_mode == RENDER_MODE_BACKGROUND);
913 return image_print_color_simd((image_t *)image, use_background, false, palette);
914 }
915 case TERM_COLOR_256:
916 return ascii_render(image, palette, ASCII_COLOR_256, render_mode == RENDER_MODE_BACKGROUND, false, simd_cells_backend());
917 case TERM_COLOR_16:
918 return ascii_render(image, palette, ASCII_COLOR_16, render_mode == RENDER_MODE_BACKGROUND, false, simd_cells_backend());
919 case TERM_COLOR_NONE:
920 case TERM_COLOR_AUTO:
921 default:
922 return image_print(image, palette);
923 }
924}
#define ASCII_RESIZE_WORKSPACE_POOL_SIZE
Definition ascii.c:58
char * ascii_convert_with_capabilities_workspace(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)
Definition ascii.c:271
char * ascii_convert_with_buffers(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)
Definition ascii.c:277
char * ascii_convert_with_capabilities_fit(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)
Definition ascii.c:265
asciichat_error_t ascii_grid_layout(int source_count, int width, int height, int *grid_cols, int *grid_rows)
Definition ascii.c:625
char * ascii_convert_with_buffers_stabilized(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
#define SET_ERRNO(code,...)
📐 Aspect Ratio Calculation Functions
const simd_cells_t * simd_cells_backend(void)
Definition cells.c:61
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
void frame_buffer_append(frame_buffer_t *buf, const char *str, size_t len)
Append raw bytes to the buffer.
void frame_buffer_destroy(frame_buffer_t *buf)
Destroy a frame buffer.
size_t frame_buffer_get_length(const frame_buffer_t *buf)
Get the current content length of the frame buffer.
const char * frame_buffer_get_content(const frame_buffer_t *buf)
Get a pointer to the buffer content.
frame_buffer_t * frame_buffer_create(int rows, int cols)
Create a new frame buffer.
Buffered terminal frame rendering.
struct frame_buffer frame_buffer_t
Opaque frame buffer handle.
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MEMSET(dest, dest_size, ch, count)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define SAFE_MEMCPY(dest, dest_size, src, count)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_TERMINAL
Definition error_codes.h:68
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1333
int utf8_display_width_n(const char *str, size_t max_bytes)
Calculate terminal display width of a UTF-8 string up to byte limit.
Definition utf8.c:102
void aspect_ratio(const ssize_t img_w, const ssize_t img_h, const ssize_t width, const ssize_t height, const bool stretch, ssize_t *out_width, ssize_t *out_height)
Calculate aspect ratio with terminal character correction.
char * ascii_convert_with_capabilities(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)
Convert image to ASCII art with terminal capability awareness.
Definition ascii.c:259
char * image_print(const image_t *image, const char *palette)
Print image as ASCII art (monochrome).
Definition foreground.c:12
char * image_print_with_capabilities(const image_t *image, const terminal_capabilities_t *caps, const char *palette)
Convert image to ASCII art with terminal capabilities.
Definition ascii.c:884
asciichat_error_t ascii_write_init(int fd, bool reset_terminal)
Initialize ASCII write subsystem.
Definition ascii.c:127
char * ascii_convert(image_t *original, const ssize_t width, const ssize_t height, const bool color, const bool _aspect_ratio, const bool stretch, const char *palette_chars, const char luminance_palette[ASCII_LUMINANCE_LEVELS])
Convert image to ASCII art.
Definition ascii.c:154
int apply_color_filter(uint8_t *pixels, uint32_t width, uint32_t height, uint32_t stride, color_filter_t filter, float time)
Apply color filter to entire image in-place.
void ascii_write_destroy(int fd, bool reset_terminal)
Destroy ASCII write subsystem.
Definition ascii.c:525
asciichat_error_t ascii_write(const char *frame)
Write ASCII frame to terminal.
Definition ascii.c:506
#define ASCII_LUMINANCE_LEVELS
Number of luminance levels supported (256).
Definition ascii.h:438
char * ascii_pad_frame_width(const char *frame, size_t pad_left)
Add leading spaces (left-padding) to each line of a frame.
Definition ascii.c:563
#define IMAGE_MAX_WIDTH
An owned RGB image with dimensions and row-major pixel storage.
char * ascii_pad_frame_height(const char *frame, size_t pad_top)
Add blank lines (vertical padding) to center a frame vertically.
Definition ascii.c:831
#define IMAGE_MAX_HEIGHT
Maximum image height (4K resolution).
void image_clear(image_t *p)
Clear image (set all pixels to black).
void image_resize(const image_t *s, image_t *d)
Resize image using nearest-neighbor interpolation.
char * image_print_color_simd(image_t *image, bool background, bool indexed, const char *palette)
Print image as ASCII with color using SIMD.
Definition sgr.c:159
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().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
SIMD-optimized ASCII conversion interface.
bool ascii_render_palette_supported(ascii_renderer_t kind, const char *palette)
char * ascii_render_image(const image_t *image, const ascii_render_options_t *options)
#define ascii_render_set_output_target
#define ascii_stabilizer_prepare
#define ascii_stabilizer_set_target
#define ascii_render
#define ascii_render_halfblocks
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
🔢 Mathematical Utility Functions
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
✅ Safe Integer Arithmetic and Overflow Detection
int terminal_set_echo(bool enabled)
bool terminal_should_use_control_sequences(int fd, bool user_setting)
🔤 String Manipulation and Shell Escaping Utilities
Frame source structure for grid layout.
Definition ascii.h:350
size_t frame_size
Frame data size in bytes (length of frame string).
Definition ascii.h:352
const char * frame_data
Frame data pointer (ASCII frame string, not owned).
Definition ascii.h:351
uint64_t fixed_step_ns
Definition stabilize.h:30
uint64_t last_timestamp_ns
Definition stabilize.h:29
uint64_t elapsed_ns
Definition stabilize.h:28
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).
Dynamic output buffer (auto-expanding).
uint8_t b
Blue color component (0-255).
uint8_t g
Green color component (0-255).
uint8_t r
Red color component (0-255).
⏱️ 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_redraw(void)
asciichat_error_t ui_controller_write(int fd, 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_SCREEN_MEDIA
size_t utf8_prefix_bytes_for_width(const char *str, size_t max_bytes, int max_width)
Return the byte length of a prefix fitting a terminal column limit.
Definition utf8.c:93
🔤 UTF-8 Encoding and Decoding Utilities