ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Video to ASCII Conversion

🖼️ Everything necessary to turn pixels into text art More...

Topics

 Video Frame Buffers
 📹 High-performance video frame management with double-buffering and lock-free operations

Files

file  digital_rain.c
 Matrix-style digital rain effect implementation.
file  ansi.c
 ANSI escape sequence utilities and fast color code generation with SIMD-accelerated terminal output.
file  digital_rain.h
 Matrix-style digital rain effect for ASCII frames.
file  avx2.h
 AVX2-optimized ASCII rendering functions.
file  common.h
 SIMD-optimized ASCII conversion interface.
file  neon.h
 NEON-optimized ASCII rendering functions.
file  sgr.h
 ANSI SGR (Select Graphic Rendition) color sequence generation.
file  sse2.h
 SSE2-optimized ASCII rendering functions.
file  ssse3.h
 SSSE3-optimized ASCII rendering functions.
file  sve.h
 SVE-optimized ASCII rendering functions.
file  ansi.h
 ANSI escape sequence utilities and fast color code generation.

Data Structures

struct  digital_rain_column_t
 digital rain column keeps the values that move through the subsystem: time_offset, speed_multiplier, phase_offset. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself. More...
struct  digital_rain
 Digital rain effect context. More...
struct  ascii_frame_source_t
 Frame source structure for grid layout. More...
struct  dec3_t
 Decimal conversion cache structure (1-3 digits). More...
struct  global_dec3_cache_t
 Global decimal cache for digit conversion. More...
struct  Str
 Growable NUL-terminated buffer used while assembling ASCII output. More...
struct  RLEState
 Run-length encoding state for ANSI color optimization. More...
struct  ImageRGB
 ImageRGB structure for NEON renderers. More...
struct  simd_benchmark_t
 SIMD benchmark results structure. More...
struct  utf8_char_t
struct  utf8_palette_cache
struct  outbuf_t
 Dynamic output buffer (auto-expanding). More...
struct  color_filter_def_t
 For color filter def, this is the live record that ties name, cli_name, r, g together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record. More...
struct  rgb_pixel_t
struct  rgb_pixel_simd_t
 rgb pixel is intentionally a small, concrete record. Fields such as r, g, b give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed. More...
struct  image
 SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the layout aligned for vector loads; it is normally embedded in renderer buffers, not individually allocated. More...

Macros

#define DIGITAL_RAIN_DEFAULT_FALL_SPEED   10.0f
 Default fall speed for raindrops.
#define DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH   12.0f
 Default raindrop length.
#define DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY   0.1f
 Default brightness decay factor.
#define DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED   1.0f
 Default animation speed multiplier.
#define DIGITAL_RAIN_DEFAULT_COLOR_R   0
 Default Matrix green color (R, G, B).
#define DIGITAL_RAIN_DEFAULT_COLOR_G   255
#define DIGITAL_RAIN_DEFAULT_COLOR_B   80
#define DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS   2.0f
 Cursor brightness multiplier.
#define ASCII_LUMINANCE_LEVELS   256
 Number of luminance levels supported (256).
#define ASCII_SLEEP_NS   50000L
 Sleep duration in nanoseconds between frames (50000 ns = 50 μs).
#define ANSI_FG_PREFIX   "\033[38;2;"
 ANSI foreground color prefix (truecolor mode).
#define ANSI_BG_PREFIX   "\033[48;2;"
 ANSI background color prefix (truecolor mode).
#define ANSI_COLOR_SUFFIX   "m"
 ANSI color suffix.
#define print(s)
 Print string to stdout.
#define console_clear(fd)
 Clear console and move cursor to home position.
#define cursor_reset(fd)
 Reset cursor to home position.
#define ascii_clear_screen(fd)
 Clear terminal screen.
#define ascii_zzz()
 Sleep for frame rate limiting.
#define ASCII_LUMINANCE_LEVELS   256
#define ASCII_PALETTE_BUFFER_SIZE   256
#define RAMP64_SIZE   64
 UTF-8 character palette cache.
#define CACHE_FREQUENCY_DECAY_TIME   10000
#define CACHE_RECENCY_SCALE   100
#define CACHE_MAX_LIFETIME   3600
#define IMAGE_MAX_WIDTH   3840
 An owned RGB image with dimensions and row-major pixel storage.
#define IMAGE_MAX_HEIGHT   2160
 Maximum image height (4K resolution).
#define IMAGE_MAX_PIXELS_SIZE   (IMAGE_MAX_WIDTH * IMAGE_MAX_HEIGHT * sizeof(rgb_pixel_t))
 Maximum pixel data size in bytes.

Typedefs

typedef struct digital_rain digital_rain_t
 Digital rain effect context.
typedef struct utf8_palette_cache utf8_palette_cache_t
typedef struct image image_t
 SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the layout aligned for vector loads; it is normally embedded in renderer buffers, not individually allocated.

Functions

digital_rain_t * digital_rain_init (int num_columns, int num_rows)
 Initialize digital rain effect context.
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.
void digital_rain_reset (digital_rain_t *rain)
 Reset digital rain effect state.
void digital_rain_set_fall_speed (digital_rain_t *rain, float speed)
 Set digital rain fall speed.
void digital_rain_set_raindrop_length (digital_rain_t *rain, float length)
 Set digital rain raindrop length.
void digital_rain_set_color (digital_rain_t *rain, uint8_t r, uint8_t g, uint8_t b)
 Set digital rain color.
void digital_rain_set_color_from_filter (digital_rain_t *rain, color_filter_t filter)
 Set digital rain color from color filter.
int digital_rain_glyph_group (uint32_t codepoint)
asciichat_error_t ascii_write_init (int fd, bool reset_terminal)
 Initialize ASCII write subsystem.
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.
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.
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.
asciichat_error_t ascii_write (const char *frame)
 Write ASCII frame to terminal.
void ascii_write_destroy (int fd, bool reset_terminal)
 Destroy ASCII write subsystem.
char * ascii_pad_frame_width (const char *frame, size_t pad)
 Add leading spaces (left-padding) to each line of a frame.
char * ascii_pad_frame_height (const char *frame, size_t pad_top)
 Add blank lines (vertical padding) to center a frame vertically.
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.
char * get_lum_palette (void)
 Get luminance palette for character mapping.
void init_dec3 (void)
 Initialize decimal lookup table.
void ascii_simd_init (void)
 Initialize SIMD subsystem.
void init_default_luminance_palette (void)
 Initialize default luminance palette.
void str_init (Str *s)
 Initialize string buffer.
void str_destroy (Str *s)
 Free string buffer.
void str_reserve (Str *s, size_t need)
 Reserve space in string buffer.
void str_append_bytes (Str *s, const void *src, size_t n)
 Append bytes to string buffer.
void str_append_c (Str *s, char c)
 Append character to string buffer.
void str_printf (Str *s, const char *fmt,...)
 Append formatted string to buffer.
ImageRGB alloc_image (int w, int h)
 Allocate a new ImageRGB (RGB8 format).
void convert_pixels_scalar (const rgb_pixel_t *pixels, char *ascii_chars, int count, const char luminance_palette[256])
 Convert pixels to ASCII (scalar fallback).
char * convert_pixels_scalar_with_newlines (image_t *image, const char luminance_palette[256])
 Convert image to ASCII with newlines (scalar fallback).
simd_benchmark_t benchmark_simd_conversion (int width, int height, int iterations)
 Benchmark SIMD conversion methods (monochrome).
simd_benchmark_t benchmark_simd_color_conversion (int width, int height, int iterations, bool background_mode)
 Benchmark SIMD color conversion methods.
simd_benchmark_t benchmark_simd_conversion_with_source (int width, int height, int iterations, bool background_mode, const image_t *source_image, bool use_256color)
 Benchmark SIMD conversion with source image.
simd_benchmark_t benchmark_simd_color_conversion_with_source (int width, int height, int iterations, bool background_mode, const image_t *source_image, bool use_256color)
 Benchmark SIMD color conversion with source image.
void print_simd_capabilities (void)
 Print detected SIMD capabilities.
char * image_print_color_simd (image_t *image, bool use_background_mode, bool use_256color, const char *ascii_chars)
 Print image as ASCII with color using SIMD.
void set_color_quality_mode (bool high_quality)
 Set color quality mode.
bool get_256_color_fast_path (void)
 Get 256-color fast path setting.
void prewarm_sgr256_fg_cache (void)
 Prewarm 256-color foreground cache for benchmarks.
void prewarm_sgr256_cache (void)
 Prewarm 256-color foreground/background cache for benchmarks.
char * get_sgr256_fg_string (uint8_t fg, uint8_t *len_out)
 Get 256-color foreground ANSI sequence string.
char * get_sgr256_bg_string (uint8_t bg, uint8_t *len_out)
 Get 256-color background ANSI sequence string.
char * get_sgr256_fg_bg_string (uint8_t fg, uint8_t bg, uint8_t *len_out)
 Get 256-color foreground/background ANSI sequence string.
size_t write_row_rep_from_arrays_enhanced (const uint8_t *fg_r, const uint8_t *fg_g, const uint8_t *fg_b, const uint8_t *bg_r, const uint8_t *bg_g, const uint8_t *bg_b, const uint8_t *fg_idx, const uint8_t *bg_idx, const char *ascii_chars, int width, char *dst, size_t cap, bool is_truecolor)
 Enhanced REP compression writer.
void build_utf8_luminance_cache (const char *ascii_chars, utf8_char_t cache[256])
 Build UTF-8 luminance cache for all 256 levels.
void build_utf8_ramp64_cache (const char *ascii_chars, utf8_char_t cache64[64], uint8_t char_index_ramp[256])
 Build UTF-8 ramp64 cache and character index ramp.
utf8_palette_cache_t * get_utf8_palette_cache (const char *ascii_chars)
 Get UTF-8 palette cache for a character set.
void simd_caches_destroy_all (void)
 Destroy all SIMD caches (palette and other caches).
void ob_reserve (outbuf_t *ob, size_t need)
 Dynamic output buffer (auto-expanding).
void ob_putc (outbuf_t *ob, char c)
 Append a character to buffer.
void ob_write (outbuf_t *ob, const void *s, size_t n)
 Append a string to buffer.
void ob_term (outbuf_t *ob)
 Append null terminator to buffer.
void ob_u8 (outbuf_t *ob, uint8_t v)
 Append unsigned 8-bit integer as decimal string.
void ob_u32 (outbuf_t *ob, uint32_t v)
 Append unsigned 32-bit integer as decimal string.
void emit_set_truecolor_fg (outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
 Emit truecolor foreground ANSI sequence.
void emit_set_truecolor_bg (outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
 Emit truecolor background ANSI sequence.
void emit_set_256_color_fg (outbuf_t *ob, uint8_t color_idx)
 Emit 256-color foreground ANSI sequence.
void emit_set_256_color_bg (outbuf_t *ob, uint8_t color_idx)
 Emit 256-color background ANSI sequence.
void emit_reset (outbuf_t *ob)
 Emit ANSI reset sequence.
bool rep_is_profitable (uint32_t runlen)
 Check if run-length encoding is profitable.
void emit_rep (outbuf_t *ob, uint32_t extra)
 Emit run-length encoded sequence.
void emit_set_fg (outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
 Emit foreground color sequence (auto-select mode).
void emit_set_bg (outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
 Emit background color sequence (auto-select mode).
char * ansi_expand_rle (const char *input, size_t input_len)
 Expand RLE escape sequences in a string.
char * ansi_compress_rle (const char *input, size_t input_len)
 Compress repeated characters using RLE escape sequences.
char * rgb_to_truecolor_halfblocks_scalar (const uint8_t *rgb, int width, int height, int stride_bytes)
 Convert RGB to truecolor half-blocks using scalar code.
char * rgb_to_halfblocks_scalar (const uint8_t *rgb, int width, int height, int stride_bytes, const char *palette)
 Convert RGB to monochrome (grayscale) half-blocks using scalar code.
char * rgb_to_16color_halfblocks_scalar (const uint8_t *rgb, int width, int height, int stride_bytes, const char *palette)
 Convert RGB to 16-color half-blocks using scalar code.
char * rgb_to_256color_halfblocks_scalar (const uint8_t *rgb, int width, int height, int stride_bytes, const char *palette)
 Convert RGB to 256-color half-blocks using scalar code.
const color_filter_def_t * color_filter_get_metadata (color_filter_t filter)
 Get color filter metadata by enum value.
color_filter_t color_filter_from_cli_name (const char *cli_name)
 Convert color filter CLI name to enum value.
void color_filter_calculate_rainbow (float time, uint8_t *r, uint8_t *g, uint8_t *b)
 Calculate rainbow color from time (3.5s cycle).
char * rainbow_replace_ansi_colors (const char *ansi_string, float time_seconds)
 Replace all RGB ANSI codes with rainbow color.
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.
image_t * image_new (size_t width, size_t height)
 Create a new image with standard allocation.
void image_destroy (image_t *p)
 Destroy an image allocated with image_new().
void image_clear (image_t *p)
 Clear image (set all pixels to black).
image_t * image_new_copy (const image_t *source)
 Create a copy of an existing image.
char * image_print (const image_t *p, const char *palette)
 Print image as ASCII art (monochrome).
char * image_print_color (const image_t *p, const char *palette)
 Print image as ASCII art with color.
char * image_print_256color (const image_t *image, const char *palette)
 Print image using 256-color ANSI mode.
char * image_print_16color (const image_t *image, const char *palette)
 Print image using 16-color ANSI mode.
char * image_print_16color_dithered (const image_t *image, const char *palette)
 Print image using 16-color ANSI mode with dithering.
char * image_print_16color_dithered_with_background (const image_t *image, bool use_background, const char *palette)
 Print image using 16-color ANSI mode with dithering and background colors.
void quantize_color (int *r, int *g, int *b, int levels)
 Quantize color to specified number of levels.
void precalc_rgb_palettes (const float red, const float green, const float blue)
 Precalculate RGB palettes with color adjustment.
void image_resize (const image_t *source, image_t *dest)
 Resize image using nearest-neighbor interpolation.
void image_resize_interpolation (const image_t *source, image_t *dest)
 Resize image using bilinear interpolation.
char * rgb_to_ansi_fg (int r, int g, int b)
 Convert RGB to ANSI foreground color code.
char * rgb_to_ansi_bg (int r, int g, int b)
 Convert RGB to ANSI background color code.
void rgb_to_ansi_8bit (int r, int g, int b, int *fg_code, int *bg_code)
 Convert RGB to 8-bit ANSI color codes.

Variables

char ascii_palette []
 Non-owning source reference used when laying out an ASCII frame. frame_data points to the source text and frame_size tells the compositor how many bytes are valid; the source must remain alive until layout and copy-out finish.
uint8_t dec3_t::len
char dec3_t::s [3]
dec3_t global_dec3_cache_t::dec3_table [256]
bool global_dec3_cache_t::dec3_initialized
global_dec3_cache_t g_dec3_cache
 Global decimal cache instance.
char g_default_luminance_palette [256]
 Default luminance palette (256 characters).
char * Str::data
size_t Str::len
size_t Str::cap
int RLEState::cFR
int RLEState::cFG
int RLEState::cFB
int RLEState::cBR
int RLEState::cBG
int RLEState::cBB
int RLEState::runLen
int RLEState::seeded
int ImageRGB::w
int ImageRGB::h
uint8_t * ImageRGB::pixels
double simd_benchmark_t::scalar_time
double simd_benchmark_t::sse2_time
double simd_benchmark_t::ssse3_time
double simd_benchmark_t::avx2_time
double simd_benchmark_t::neon_time
double simd_benchmark_t::sve_time
double simd_benchmark_t::speedup_best
const char * simd_benchmark_t::best_method
uint8_t utf8_char_t::width
uint8_t utf8_char_t::utf8_bytes [4]
uint8_t utf8_char_t::byte_len
uint8_t utf8_char_t::_pad
utf8_char_t utf8_palette_cache::cache [256]
utf8_char_t utf8_palette_cache::cache64 [64]
uint8_t utf8_palette_cache::char_index_ramp [256]
atomic_t utf8_palette_cache::last_access_time
atomic_t utf8_palette_cache::access_count
uint32_t utf8_palette_cache::total_age_seconds
uint64_t utf8_palette_cache::creation_time
double utf8_palette_cache::cached_score
size_t utf8_palette_cache::heap_index
uint32_t utf8_palette_cache::key
char utf8_palette_cache::palette_hash [256]
bool utf8_palette_cache::initialized
bool utf8_palette_cache::is_valid
UT_hash_handle utf8_palette_cache::hh

Luminance Calculation Constants

Cached decimal text for a small integer. len says how many characters are valid in the inline representation, allowing hot rendering paths to avoid formatting and allocation for values from one to three digits.

Global decimal cache for digit conversion

Small RGB image view used by the NEON renderer. w and h describe the image geometry and pixels points at row-major RGB storage owned by the caller; the renderer reads it and does not free the pixels.

Run-length encoding state for ANSI color optimization

This is the handoff point for simd benchmark. Callers fill scalar_time, sse2_time, ssse3_time, avx2_time before passing it on; consumers read the values during the operation and return ownership only where the member contract explicitly says they do.

Growable NUL-terminated buffer used while assembling ASCII output

utf8 char is intentionally a small, concrete record. Fields such as width, byte_len, _pad give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed.

Owns the temporary storage used by utf8 palette cache. The data pointers and size or cursor fields describe the live portion of the allocation; callers must use the type's cleanup path when the buffer or queue is no longer needed.

#define LUMA_RED   77
 Luminance red coefficient (0.299 * 256 = 77).
#define LUMA_GREEN   150
 Luminance green coefficient (0.587 * 256 = 150).
#define LUMA_BLUE   29
 Luminance blue coefficient (0.114 * 256 = 29).
#define LUMA_THRESHOLD   128
 Luminance threshold for rounding.

Detailed Description

🖼️ Everything necessary to turn pixels into text art

Implements a Matrix-inspired digital rain effect that can be applied to ASCII frames as a post-processing step. The effect creates the illusion of "falling" characters by modulating brightness in a sawtooth wave pattern.

ALGORITHM OVERVIEW:

The digital rain effect is based on the observation that Matrix code rain isn't actually falling characters - it's stationary characters whose brightness changes to create the illusion of rain. Key concepts:

  1. Sawtooth Wave: Each column has a brightness wave that repeats, creating multiple "raindrops" falling at different speeds.
  2. Cursor/Tracer: The bright leading character is detected where brightness increases (where the wave rises).
  3. Organic Variation: Random timing offsets and wobble functions prevent mechanical-looking patterns.

IMPLEMENTATION:

  • Per-column state tracking (timing, speed, phase)
  • Brightness calculation using fractional time wrapping
  • ANSI color code injection for brightness modulation
  • Cursor highlighting with increased brightness
  • Smooth brightness transitions via decay blending
Note
This effect is applied AFTER ASCII conversion
Works with both color and monochrome ASCII frames
Minimal performance impact (O(frame_size) single pass)
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

This header provides comprehensive functions for converting images to ASCII art and outputting frames to the terminal. Supports multiple color modes, aspect ratio preservation, capability-aware conversion, and frame layout management.

CORE FEATURES:

  • Image-to-ASCII conversion with color support
  • Terminal capability-aware conversion (auto-selects optimal color mode)
  • Aspect ratio preservation for proper image proportions
  • Terminal frame output and management
  • Frame padding and layout utilities (horizontal and vertical)
  • Grid layout for multiple frames (multi-user support)
  • buffer domain integration for efficient memory management
  • SIMD-optimized conversion for performance

CONVERSION MODES:

The system supports multiple conversion modes:

  • Standard conversion: Basic image-to-ASCII with optional color
  • Capability-aware: Automatically selects best color mode for terminal
  • Aspect ratio preservation: Maintains image proportions (terminal correction)
  • Stretch mode: Fills terminal dimensions exactly (may distort proportions)

FRAME MANAGEMENT:

Frame management includes:

  • Terminal initialization and cleanup
  • Frame output to terminal
  • Frame padding (horizontal and vertical)
  • Grid layout for multiple frames
  • Frame source management
Note
All conversion functions return allocated strings that must be freed.
Terminal initialization functions must be matched with cleanup.
Capability-aware conversion is recommended for optimal results.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

This header provides AVX2 (Advanced Vector Extensions 2) optimized functions for converting images to ASCII art on modern x86-64 CPUs.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

This header provides SIMD-optimized functions for converting images to ASCII art. Supports multiple architectures including SSE2, SSSE3, AVX2 (x86), NEON (ARM), and SVE (ARM).

The interface provides:

  • SIMD initialization and setup
  • Architecture-specific rendering functions
  • Benchmarking utilities
  • Cache management
  • UTF-8 character handling
Note
SIMD support is automatically detected and enabled based on CPU capabilities. CMake controls SIMD levels via ENABLE_SIMD_* options.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides NEON (Advanced SIMD) optimized functions for converting images to ASCII art on ARM processors.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
August 2025

This header provides a dynamic output buffer system with automatic expansion and optimized ANSI escape sequence emission functions. The buffer is designed for efficient ASCII art frame construction and terminal output.

CORE FEATURES:

  • Auto-expanding output buffer (grows as needed)
  • Efficient buffer management operations
  • Optimized ANSI escape sequence emission
  • Run-length encoding (RLE) support for compression
  • Color mode auto-selection (16-color, 256-color, truecolor)
  • Integer-to-string conversion utilities

BUFFER MANAGEMENT:

The output buffer automatically expands when space is needed:

  • Initial capacity is allocated on first reservation
  • Buffer doubles in size when capacity is exceeded
  • Memory is allocated on-demand (no upfront allocation)
  • Buffer ownership: caller must free buffer when done

ANSI ESCAPE SEQUENCES:

The system emits ANSI escape sequences for:

  • Color output (foreground and background)
  • Cursor control and positioning
  • Reset and formatting codes
  • Run-length encoding for repeated characters

COLOR MODE AUTO-SELECTION:

Color emission functions automatically select optimal mode:

  • 16-color: Uses standard ANSI color codes (0-15)
  • 256-color: Uses extended palette (16-255)
  • Truecolor: Uses 24-bit RGB escape sequences
Note
All buffer operations ensure null-terminated strings.
Buffer memory must be freed by caller using free() on buf pointer.
ANSI sequences are optimized for minimal terminal I/O.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

This module provides functions for working with ANSI RLE (Run-Length Encoding) escape sequences. The REP sequence (CSI Ps b) repeats the preceding graphic character Ps times.

RLE FORMAT:

The ANSI REP sequence format is: ESC [ N b

  • ESC (0x1b) - Escape character
  • [ - CSI introducer
  • N - Decimal repeat count (how many times to repeat)
  • b - REP command character

Example: "A\x1b[3b" means "A" followed by 3 more "A"s = "AAAA"

USE CASES:

  • Compression: Reduce bandwidth for ASCII art with repeated characters
  • Expansion: Convert RLE to plain text for file output or non-RLE terminals
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

This header provides scalar (non-SIMD) halfblock rendering functions for converting RGB images to ANSI-escaped halfblock characters with truecolor foreground and background colors.

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

This header provides SSE2 (Streaming SIMD Extensions 2) optimized functions for converting images to ASCII art on x86-64 CPUs.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
August 2025

This header provides SSSE3 (Supplemental Streaming SIMD Extensions 3) optimized functions for converting images to ASCII art on x86-64 CPUs.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
August 2025

This header provides SVE (Scalable Vector Extension) optimized functions for converting images to ASCII art on ARM processors with SVE support.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
August 2025

This module provides color filtering capabilities to apply monochromatic color tints to grayscale video feeds. The server processes color filters; clients see each user in their chosen filter color.

FEATURES:

  • 11 built-in color filters (matrix green, cyan, magenta, etc.)
  • ITU-R BT.601 grayscale conversion formula
  • Two colorization modes: "color on white" and "white on color"
  • Per-pixel colorization for maximum quality
  • Protocol integration via CLIENT_CAPABILITIES packet

COLOR FILTERS:

  1. none (no filtering)
  2. black (dark content on white background)
  3. white (white content on black background)
  4. green (#00FF41)
  5. magenta (#FF00FF)
  6. fuchsia (#FF00AA)
  7. orange (#FF8800)
  8. teal (#00DDDD)
  9. cyan (#00FFFF)
  10. pastel-pink (#FFB6C1)
  11. error-red (#FF3333)
  12. yellow (#FFEB99)

ARCHITECTURE:

  • color_filter_registry[]: Metadata for all 11 filters (name, CLI name, RGB values, mode)
  • rgb_to_grayscale(): ITU-R BT.601 conversion (efficient fixed-point math)
  • colorize_grayscale_pixel(): Single pixel colorization (inline for performance)
  • apply_color_filter(): Image-wide colorization (in-place operation)

USAGE:

// Convert image to grayscale and apply filter
if (filter != COLOR_FILTER_NONE) {
}
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
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.
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...

PROTOCOL INTEGRATION:

The color_filter field is included in the CLIENT_CAPABILITIES packet:

  • Client sends chosen filter to server during connection
  • Server applies filter to client's video before ASCII conversion
  • All clients see the filtered output
Note
All filter colors are applied using ITU-R BT.601 grayscale conversion
Filters automatically set –color-mode mono (monochromatic display)
"--color-filter foo --color-mode 256" is an error
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

This header provides comprehensive image data structures and operations for ascii-chat. Supports RGB images with standard and SIMD-optimized formats for efficient image processing and ASCII art conversion.

CORE FEATURES:

  • RGB image data structures (packed and SIMD-aligned)
  • Image allocation and memory management
  • buffer domain integration for video pipeline efficiency
  • Image-to-ASCII conversion with multiple color modes
  • Color quantization and palette generation
  • Image resizing (nearest-neighbor and bilinear interpolation)
  • ANSI color code generation and conversion
  • Dithering support for improved color accuracy

IMAGE FORMATS:

The system supports:

  • Standard RGB24 format (packed, 3 bytes per pixel)
  • SIMD-aligned RGB format (4-byte aligned for NEON/AVX optimization)
  • Maximum 4K resolution (3840x2160)
  • Memory-efficient buffer domain allocation

COLOR MODES:

ASCII conversion supports multiple color modes:

  • Monochrome: No color, character-based only
  • 16-color: Standard ANSI colors
  • 256-color: Extended ANSI palette
  • Truecolor: 24-bit RGB (terminal-dependent)
  • Dithering: Floyd-Steinberg dithering for color accuracy
Note
All image allocation functions must be matched with corresponding destroy functions (image_destroy() or image_destroy()).
ASCII conversion functions return allocated strings that must be freed by the caller.
Image structures are compatible with webcam capture (image_t).
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
September 2025

video README

The video module converts RGB image data into ASCII art suitable for terminal display, with SIMD-optimized processing for real-time video conversion at 60+ FPS.

Overview

ascii-chat renders live video as ASCII art in the terminal by:

  1. Capturing RGB frames from webcam (1920x1080 or configured resolution)
  2. Scaling frames to terminal dimensions (typically 80x24 to 200x60)
  3. Converting RGB pixels to grayscale luminance
  4. Mapping luminance values to ASCII characters from a palette
  5. Optionally preserving color information via ANSI escape sequences
  6. Generating optimized ANSI output for terminal rendering
  7. Minimizing escape sequences to reduce bandwidth and rendering time

The module is highly optimized using SIMD instructions, achieving:

  • 60+ FPS for 1920x1080 → 160x45 conversion
  • <5% CPU usage on modern processors
  • Sub-millisecond conversion latency

Features

Rendering Modes:

  • Full-block mode: One character per pixel (standard resolution)
  • Half-block mode: Two pixels per character using ▀ and ▄ (2x vertical resolution)
  • Color mode: Preserves RGB color via ANSI 24-bit true color escape sequences
  • Monochrome mode: Grayscale ASCII art using luminance only

SIMD Acceleration:

  • SSE2: 16-byte parallel processing (x86_64 baseline)
  • SSSE3: Enhanced shuffle operations for pixel reordering
  • AVX2: 32-byte parallel processing (2x throughput vs SSE2)
  • NEON: 16-byte parallel processing (ARM/ARM64)
  • SVE: Scalable vector processing (ARM v8.2+)
  • Runtime CPU detection: Automatically selects best SIMD level

Grid Layouts:

  • Multi-client video grid (2x2, 3x3, up to 9 clients)
  • Automatic aspect ratio correction for each grid cell
  • Border characters between grid cells
  • Client ID labels for each video stream

Palette Support:

  • Customizable ASCII character sets
  • UTF-8 multi-byte character support
  • Built-in palettes: standard, dense, blocks, custom
  • Brightness-based character selection

Aspect Ratio Correction:

  • Terminal characters are ~2:1 height:width ratio
  • Automatic scaling to maintain proper aspect ratio
  • Prevents stretched/squished video

Face tracking and stabilization:

  • The optional face-follow path detects faces on a small working image instead of spending detector time on the full camera frame.
  • The tracker keeps a normalized crop around the selected face and eases toward its next position. Short detection gaps therefore do not make the picture jump back and forth.
  • The renderer has a separate temporal history per stream. It remembers recent samples, glyphs, and colors so tiny changes do not cause visible character shimmer.

Rendering Pipeline

0. Optional face-follow preprocessing

Face following happens before scaling and ASCII conversion. Detection returns normalized rectangles in the original, unmirrored image. The state machine accepts a confident detection, chooses an anchor, and moves the crop toward that anchor over time. If a face disappears briefly, the last useful crop is retained; after enough misses the view relaxes back to the full frame.

The detector works on a bounded 320x240 BGR image and writes its temporary results into the caller-provided buffer. That keeps the expensive detector predictable while the final crop still uses the source frame's resolution.

size_t face_count = 0;
face_follow_detect(detector_results, bgr_320x240, 320, 240,
faces, FACE_FOLLOW_MAX_DETECTIONS, &face_count);
face_follow_observe(&follow, faces, face_count, monotonic_seconds);
face_follow_tick(&follow, monotonic_seconds, true);
// follow.crop is now the smoothed normalized crop for this frame.
void face_follow_detect(unsigned char *results, unsigned char *bgr, int width, int height, face_follow_detection_t *faces, size_t capacity, size_t *count)
void face_follow_tick(face_follow_state_t *state, double now, bool enabled)
void face_follow_init(face_follow_state_t *state)
Definition face_follow.c:13
void face_follow_observe(face_follow_state_t *state, const face_follow_detection_t *faces, size_t count, double now)
Definition face_follow.c:25
#define FACE_FOLLOW_MAX_DETECTIONS
Definition face_follow.h:7
face follow state keeps the values that move through the subsystem: crop, target, face,...
Definition face_follow.h:41

Face following is a composition aid, not a promise that a face is always visible. A frame with no usable detection remains a valid frame; disabling the feature simply lets the crop return to the full image.

1. Image Scaling

Resize RGB image from webcam resolution to terminal dimensions:

  • Input: RGB24 image (e.g., 1920x1080 = 6,220,800 bytes)
  • Output: Scaled RGB24 image (e.g., 160x45 = 21,600 bytes)
  • Algorithm: Bilinear interpolation for smooth scaling
  • SIMD: Process 16 pixels at a time (SSE2) or 32 pixels (AVX2)
  • Performance: ~200 µs for 1920x1080 → 160x45 on modern CPU

2. Brightness Calculation

Convert RGB pixels to luminance (grayscale):

  • Formula: Y = 0.299*R + 0.587*G + 0.114*B (BT.601 standard)
  • SIMD: Process 16 RGB triplets in parallel
  • Input: RGB24 array (3 bytes per pixel)
  • Output: Y8 array (1 byte per pixel)
  • Performance: ~50 µs for 160x45 image

SIMD implementation (SSE2 example):

// Load 16 RGB pixels (48 bytes)
__m128i r = _mm_loadu_si128((__m128i*)(rgb + 0)); // R values
__m128i g = _mm_loadu_si128((__m128i*)(rgb + 16)); // G values
__m128i b = _mm_loadu_si128((__m128i*)(rgb + 32)); // B values
// Apply BT.601 coefficients (0.299, 0.587, 0.114)
__m128i y = _mm_add_epi16(
_mm_mullo_epi16(r, _mm_set1_epi16(77)), // 0.299 * 256 ≈ 77
_mm_add_epi16(
_mm_mullo_epi16(g, _mm_set1_epi16(150)), // 0.587 * 256 ≈ 150
_mm_mullo_epi16(b, _mm_set1_epi16(29)) // 0.114 * 256 ≈ 29
)
);
// Shift right by 8 to get final Y values
y = _mm_srli_epi16(y, 8);

3. Palette Mapping

Map brightness values to ASCII characters:

  • Input: Luminance value (0-255)
  • Output: ASCII character from palette
  • Palette example: " .:-=+*#%@" (10 characters, dark to bright)
  • Mapping: luminance / (256 / palette_length)
  • SIMD: Lookup table with SSSE3 shuffle instruction

There are two useful ways to choose a glyph. The traditional luminance renderer measures brightness and indexes a 256-entry luminance palette. It is fast, predictable, and works with any complete UTF-8 palette. The glyph matcher instead evaluates the visual coverage of candidate glyphs and picks the glyph whose rendered shape best matches the source cell. It can preserve edges and texture better, but it needs a supported glyph palette and more work per cell. Fine scoring reuses the source cell's 8x8 luminance samples across shortlisted glyphs. Candidates are visited by tone distance with exact brightness bounds; original palette order breaks score ties. A bounded cache reuses fits within a frame when the coarse luminance, fine luminance, contributing chroma vectors, and prior glyph match. These scoring inputs can agree at different RGB hues; foreground color and temporal-history updates remain independent per cell. Full comparisons reject hash collisions and preserve fine spatial detail. Upscaled cells often repeat the same pixel across an entire sample row. After checking every pixel, the matcher samples those rows once and uses precomputed mask row sums for fine scoring. This is algebraically identical to scoring all 64 samples; textured rows retain the general path. Debug builds optimize the rendering and temporal-stabilization translation units while retaining debug information and the configured sanitizers.

// Brightness-only rendering: stable and broadly compatible.
char *frame = ascii_render(image, palette, ASCII_COLOR_TRUE,
true, false, &simd_ops);
// Shape-aware rendering: compare glyph coverage, then add color if desired.
&simd_ops, palette, true);
}
bool ascii_glyph_palette_supported(const char *palette)
#define ascii_render
char * ascii_render_glyph_match_mode(const image_t *image, ascii_color_t mode, const simd_cells_t *ops, const char *palette, bool background)

In practice, use luminance rendering for a conventional terminal palette or when throughput matters most. Use glyph matching for a deliberately chosen glyph set where the shape of the characters is part of the look. Both paths produce the same terminal-cell contract and can use the same temporal stabilization history.

3a. Temporal stabilization

Stabilization is deliberately local to a renderer-owned stream. It compares the current candidate with the previous cell history and only changes glyph or color when the improvement is worth the visible movement. A viewport or rendering contract change resets that history so old frames cannot leak into a new layout.

ascii_stabilizer_t history = {0};
ascii_stabilizer_prepare(&history, image->width, image->height, render_config);
char *stable = ascii_render(image, palette, ASCII_COLOR_TRUE,
true, false, &simd_ops);
#define ascii_stabilizer_prepare
#define ascii_stabilizer_reset
#define ascii_stabilizer_set_target

Half-block rendering uses special logic:

  • Combines two vertically adjacent pixels into one character
  • Uses ▀ (upper half block), ▄ (lower half block), or █ (full block)
  • Effectively doubles vertical resolution
  • Example: 80x48 terminal displays 80x96 effective resolution

4. ANSI Escape Sequence Generation

Generate optimized ANSI sequences for terminal:

  • Color changes only when pixel color changes (stateful tracking)
  • Cursor movement optimized (relative vs absolute positioning)
  • Typical escape sequence: \x1b[38;2;R;G;Bm (24-bit color)
  • Output buffering to minimize write() syscalls
  • Pre-allocated buffer domain to avoid malloc overhead

Optimization techniques:

  • Delta encoding: Only emit changes from previous frame
  • Run-length encoding: Combine consecutive identical characters
  • Color caching: Remember last foreground/background color
  • Escape sequence caching: Pre-compute common sequences

Example output:

\x1b[38;2;255;128;64m###\x1b[38;2;200;100;50m***\x1b[38;2;150;75;37m+++

5. Terminal Output

Write ANSI output to terminal:

  • Single write() call per frame (buffered output)
  • Double-buffering: Compose frame while displaying previous
  • Cursor hiding during frame update (reduces flicker)
  • Cursor positioning to (1,1) for each frame
  • Terminal raw mode for direct output control

SIMD vs Scalar Implementations

ascii-chat provides both scalar (non-SIMD) and SIMD implementations of video conversion, with automatic runtime selection based on CPU capabilities.

Scalar (Non-SIMD) Implementation

Purpose: Fallback for processors without SIMD support, reference implementation

File: lib/video/scalar/halfblock.c

Algorithm:

  • Processes one source pixel at a time
  • No vector instructions - standard integer arithmetic
  • Suitable for embedded systems and older CPUs

Performance Characteristics:

  • Single-threaded throughput: ~15 FPS for 1920x1080 → 160x45
  • Latency: 66 ms per frame (16.7 ms target for 60 FPS)
  • CPU usage: ~25% on single core (limited by core speed)
  • Memory bandwidth: Not optimized (scalar loads dominate)
  • Cache efficiency: Moderate (sequential memory access)

When to Use:

  • Baseline architecture where SIMD unavailable
  • Testing and validation (reference implementation)
  • Debugging (easier to trace scalar logic)
  • Embedded systems with no vector support

Trade-offs:

  • Advantage: Maximal portability, simpler code
  • Disadvantage: ~4-8x slower than SIMD, unsuitable for real-time video

SIMD vs Scalar Implementations

SSE2 (x86_64 Baseline)

Capabilities:

  • 128-bit vector registers (XMM0-XMM15)
  • Process 16 bytes or 8 int16 or 4 int32 simultaneously
  • Integer arithmetic, logic, compare operations
  • Available on all x86_64 CPUs

Performance:

  • RGB to luminance: ~4x speedup vs scalar
  • Palette lookup: ~8x speedup vs scalar
  • Frame conversion: ~60 FPS for 1920x1080 → 160x45

SSSE3 (Supplemental SSE3)

Additional capabilities beyond SSE2:

  • PSHUFB: Arbitrary byte shuffle within 128-bit vector
  • Enables fast palette lookup via table shuffle
  • Horizontal operations for pixel combining

Performance improvement:

  • Palette lookup: ~12x speedup vs scalar (1.5x vs SSE2)
  • Reduced instruction count for complex permutations

AVX2 (Advanced Vector Extensions 2)

Capabilities:

  • 256-bit vector registers (YMM0-YMM15)
  • Process 32 bytes or 16 int16 or 8 int32 simultaneously
  • Double throughput vs SSE2 for same operations
  • Available on Intel Haswell+ (2013), AMD Excavator+ (2015)

Performance:

  • RGB to luminance: ~8x speedup vs scalar (2x vs SSE2)
  • Frame conversion: ~90 FPS for 1920x1080 → 160x45
  • Reduced loop overhead (process 2x data per iteration)

NEON (ARM)

Capabilities:

  • 128-bit vector registers (Q0-Q15 or D0-D31)
  • Process 16 bytes or 8 int16 or 4 int32 simultaneously
  • Similar performance to SSE2 on equivalent clock speeds
  • Available on ARM Cortex-A series, Apple Silicon

Performance on Apple M1:

  • RGB to luminance: ~6x speedup vs scalar
  • Frame conversion: ~120 FPS for 1920x1080 → 160x45 (higher clock)

SVE (ARM Scalable Vector Extension)

Capabilities:

  • Scalable vectors: 128-bit to 2048-bit (implementation defined)
  • Future-proof: Code runs on any SVE vector length
  • Predicate registers for advanced masking
  • Available on ARM v8.2+ (AWS Graviton3, Fujitsu A64FX)

Performance potential:

  • 512-bit vectors: ~4x SSE2 throughput
  • Automatically scales with future CPU generations

Runtime CPU Detection

ascii-chat automatically detects and uses the best SIMD level:

// At startup, detect CPU capabilities
if (cpu_has_avx2()) {
ascii_convert = ascii_convert_avx2; // Best performance
} else if (cpu_has_ssse3()) {
ascii_convert = ascii_convert_ssse3;
} else if (cpu_has_sse2()) {
ascii_convert = ascii_convert_sse2; // Baseline x86_64
} else if (cpu_has_neon()) {
ascii_convert = ascii_convert_neon; // ARM
} else {
ascii_convert = ascii_convert_scalar; // Fallback
}
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

Usage Examples

Basic Conversion

// Initialize ASCII converter
ascii_context_t ascii_ctx;
ascii_config_t config = {
.width = 160,
.height = 45,
.palette = " .:-=+*#%@",
.color = true,
.half_blocks = false
};
ascii_init(&ascii_ctx, &config);
// Convert RGB frame to ASCII
uint8_t *rgb_data = ...; // From webcam (1920x1080 RGB24)
char *ascii_output;
size_t output_len;
ascii_convert(&ascii_ctx, rgb_data, &ascii_output, &output_len);
// Write to terminal
write(STDOUT_FILENO, "\x1b[2J\x1b[H", 7); // Clear screen, home cursor
write(STDOUT_FILENO, ascii_output, output_len);
// Cleanup
ascii_destroy(&ascii_ctx);
unsigned char uint8_t

Half-Block Mode

// Half-block mode for 2x vertical resolution
ascii_config_t config = {
.width = 80,
.height = 48, // Will show 80x96 effective resolution
.palette = " ▀▄█", // Special half-block characters
.color = true,
.half_blocks = true
};
ascii_init(&ascii_ctx, &config);
// Conversion combines vertical pixel pairs
ascii_convert(&ascii_ctx, rgb_data, &ascii_output, &output_len);

Multi-Client Grid

// 2x2 grid for 4 clients
ascii_grid_config_t grid_config = {
.grid_width = 2,
.grid_height = 2,
.cell_width = 80,
.cell_height = 24,
.border_char = '|',
.show_labels = true
};
ascii_grid_t grid;
ascii_grid_init(&grid, &grid_config);
// Render each client's frame to grid cell
for (int i = 0; i < 4; i++) {
ascii_grid_set_cell(&grid, i, client_frames[i], client_labels[i]);
}
// Composite final grid output
char *grid_output;
size_t grid_len;
ascii_grid_render(&grid, &grid_output, &grid_len);
write(STDOUT_FILENO, grid_output, grid_len);
ascii_grid_destroy(&grid);

Optimization Strategy

ascii-chat uses a multi-layered optimization approach to achieve real-time video conversion:

Architecture-Level Optimization

SIMD Instruction Selection:

  • Single implementation compiled per target (not runtime branches within loops)
  • Avoids branch prediction penalties in hot loops
  • CMake selects highest available SIMD level at build time

Build-Time vs Runtime Selection:

Build Time: CMake detects target CPU → Selects SIMD level → Compiles one variant
Runtime: CPU detection validates assumptions → Falls back if needed
Result: Optimal code without runtime dispatch overhead

Algorithm-Level Optimization

Parallel Data Processing:

  • SSE2/NEON: Process 16 bytes per instruction (16 RGB values or 4 RGBA pixels)
  • AVX2: Process 32 bytes per instruction (32 luminance values)
  • Reduces loop iterations by 4-8x vs scalar

Color Caching:

  • UTF-8 palette cache: 256 entries for monochrome, 64 for color
  • Eviction algorithm: LRU with frequency/recency scoring
  • ~5-10 MB cache to avoid repeated string lookups

ANSI Escape Sequence Optimization:

  • Stateful color tracking: Only emit color change when needed
  • Run-length encoding: Combine consecutive identical characters
  • Pre-allocated buffers avoid malloc per frame

Memory Hierarchy Optimization

Cache Line Awareness:

  • Process data in 64-byte chunks (typical L1 cache line)
  • Bilinear scaling: Process 2x2 pixel blocks with temporal locality
  • Luminance conversion: Sequential access patterns

Zero-Copy Techniques:

  • Webcam frames returned as direct memory pointers
  • Output buffers pre-allocated in buffer domain
  • Avoid malloc/memcpy in hot loops

SIMD Register Utilization:

  • Use all available vector registers (XMM0-15 for SSE2, YMM0-15 for AVX2)
  • Instruction-level parallelism: Multiple independent operations per cycle
  • Minimize register spills to stack

Spatial Locality

Bilinear Scaling: Process pixels in raster order

  • Sequential reads from source image
  • Sequential writes to scaled output
  • Prefetcher-friendly access patterns

Luminance Conversion: Stream processing

  • Read RGB triplets sequentially
  • Compute Y value immediately
  • Write Y value to output
  • Cache misses minimized by streaming pattern

Performance Benchmarks

Measured on Intel i7-10700K @ 3.8 GHz, 1920x1080 → 160x45 conversion:

Implementation FPS Latency CPU % Speedup vs Scalar
Scalar 15 66 ms 25% 1x (baseline)
SSE2 60 16 ms 6% 4x
SSSE3 75 13 ms 5% 5x
AVX2 90 11 ms 4% 6x

Measured on Apple M1 (ARM NEON):

  • NEON: 120 FPS, 8 ms latency, 5% CPU (8x speedup vs scalar)

Performance Analysis:

  • Scalar implementation bottlenecked by memory bandwidth (~25% CPU from single core)
  • SSE2 achieves 4x speedup with 16-byte parallel processing
  • AVX2 approaches 6x speedup limited by memory system (not ALU bound)
  • 60 FPS target achievable on all SIMD targets with <10% single-core CPU

Memory usage:

  • RGB frame buffer: 6 MB (1920x1080x3)
  • Scaled frame: 21 KB (160x45x3)
  • ASCII output: ~50 KB (with ANSI color codes)
  • Total: ~6.1 MB per frame

Performance Trade-offs Analysis

Scalar vs SIMD Trade-offs

Scalar Advantages:

  • Universal portability (any CPU)
  • Small binary size (<50 KB)
  • No CPU detection overhead
  • Easier to debug (serial execution model)

**Scalar Disadvantages**:

  • 4-8x slower than SIMD on typical CPUs
  • ~25% single-core CPU at 15 FPS (unsustainable for real-time)
  • Memory bandwidth underutilized
  • Not suitable for production video chat

**Decision Rationale**:

  • ascii-chat targets modern CPUs (post-2005) where SIMD is standard
  • Scalar kept as fallback for: testing, validation, exotic platforms
  • Production paths use SIMD to meet real-time requirements

SIMD Level Trade-offs

Level Year Speedup vs SSE2 Availability Recommendation
Scalar N/A 0.25x 100% Fallback only
SSE2 2001 1x (baseline) 99% x86_64 default
SSSE3 2006 1.25x 95% Nice-to-have
AVX2 2013 1.5x 80% Best for x86
NEON 2007 1.3-2x 100% ARM ARM default
SVE 2017 2-4x 5% Future use

Architecture Selection Logic:

At build time, CMake checks:
1. Target architecture (x86_64, ARM, ARM64, PowerPC)
2. Compiler support for intrinsics
3. Optional: Runtime detection preference
Best-fit selection:
- x86_64: Default SSE2 (baseline), enable AVX2 if compiler supports
- ARM: NEON (baseline for 32-bit), SVE if available
- Fallback: Always provide scalar for maximum compatibility

Compilation Strategy:

  • Single SIMD variant compiled per build (no runtime dispatch)
  • Avoids branch prediction penalty in hot loops
  • Smaller binary: Only one code path compiled
  • Cleaner CPU-specific code paths

Latency vs Throughput

64 FPS at 1920x1080:

  • Target latency: ~16 ms per frame (16.7 ms budget)
  • Scalar: 66 ms (4x over budget - unsuitable)
  • SSE2: 16 ms (meets target)
  • AVX2: 11 ms (headroom for other processing)

Strategy:

  • SIMD essential to stay within real-time deadline
  • Headroom (11 ms on AVX2) allows for:
    • Webcam capture (~1-2 ms)
    • Network transmission (~5-10 ms)
    • Terminal rendering (~2-3 ms)

Power Efficiency

Energy Per Frame:

Implementation Frames/sec Power Energy/Frame Relative
Scalar 15 FPS 25W 1.67 J 1.0x
SSE2 60 FPS 6W 0.10 J 0.06x
AVX2 90 FPS 4W 0.04 J 0.03x

Analysis:

  • SIMD dramatically reduces energy/frame (16-25x improvement)
  • Enables battery operation on mobile devices
  • Reduces thermal load and cooling requirements

Terminal Compatibility

ascii-chat supports various terminal features:

True Color (24-bit RGB):

  • Supported: iTerm2, Alacritty, Windows Terminal, GNOME Terminal 3.16+
  • Escape sequence: \x1b[38;2;R;G;Bm (foreground), \x1b[48;2;R;G;Bm (background)
  • Falls back to 256-color if true color unavailable

256-Color Mode:

  • Supported: Most modern terminals
  • Escape sequence: \x1b[38;5;Nm where N is 0-255
  • Color palette approximation for RGB values

UTF-8 Support:

  • Required for half-block characters (▀▄█)
  • Required for custom Unicode palettes
  • Automatic detection via $LANG and $LC_ALL

Terminal Size Detection:

  • Uses TIOCGWINSZ ioctl on POSIX through libplatform
  • Uses GetConsoleScreenBufferInfo on Windows through libplatform
  • Falls back to $COLUMNS and $LINES environment variables
  • Default: 80x24 if detection fails
See also
video/ascii.h
video/ansi_fast.h
video/simd/ascii_simd.h
video/output_buffer.h
palette.h

Macro Definition Documentation

◆ ANSI_BG_PREFIX

#define ANSI_BG_PREFIX   "\033[48;2;"

#include <include/ascii-chat/video/ascii/ascii.h>

ANSI background color prefix (truecolor mode).

ANSI escape sequence prefix for 24-bit truecolor background colors. Format: ESC[48;2;r;g;bm (where r, g, b are RGB values).

Note
Use with ANSI_COLOR_SUFFIX to form complete escape sequence.
Example: ANSI_BG_PREFIX "255;0;0" ANSI_COLOR_SUFFIX (red background).

Definition at line 482 of file ascii.h.

◆ ANSI_COLOR_SUFFIX

#define ANSI_COLOR_SUFFIX   "m"

#include <include/ascii-chat/video/ascii/ascii.h>

ANSI color suffix.

ANSI escape sequence suffix for color escape sequences. Used with ANSI_FG_PREFIX or ANSI_BG_PREFIX to form complete escape sequences.

Note
Format: prefix + RGB + suffix = complete ANSI sequence.
Example: "\033[38;2;255;0;0m" (red foreground).

Definition at line 496 of file ascii.h.

◆ ANSI_FG_PREFIX

#define ANSI_FG_PREFIX   "\033[38;2;"

#include <include/ascii-chat/video/ascii/ascii.h>

ANSI foreground color prefix (truecolor mode).

ANSI escape sequence prefix for 24-bit truecolor foreground colors. Format: ESC[38;2;r;g;bm (where r, g, b are RGB values).

Note
Use with ANSI_COLOR_SUFFIX to form complete escape sequence.
Example: ANSI_FG_PREFIX "255;0;0" ANSI_COLOR_SUFFIX (red foreground).

Definition at line 469 of file ascii.h.

◆ ascii_clear_screen

#define ascii_clear_screen ( fd)

#include <include/ascii-chat/video/ascii/ascii.h>

Value:

Clear terminal screen.

Parameters
fdFile descriptor for terminal

Clears terminal screen without moving cursor. Equivalent to terminal_clear_screen().

Definition at line 557 of file ascii.h.

◆ ASCII_LUMINANCE_LEVELS [1/2]

#define ASCII_LUMINANCE_LEVELS   256

#include <include/ascii-chat/video/ascii/ascii.h>

Number of luminance levels supported (256).

Number of luminance levels used for character mapping. Each pixel's brightness value (0-255) maps to a character in the luminance palette.

Note
256 levels correspond to 8-bit pixel brightness values.
Luminance palette must have 256 elements.

Definition at line 438 of file ascii.h.

Referenced by ascii_convert(), build_client_luminance_palette(), build_utf8_ramp64_cache(), build_utf8_ramp64_cache(), convert_pixels_scalar(), convert_pixels_scalar_with_newlines(), initialize_client_palette(), precalc_rgb_palettes(), and term_renderer_feed().

◆ ASCII_LUMINANCE_LEVELS [2/2]

#define ASCII_LUMINANCE_LEVELS   256

◆ ASCII_PALETTE_BUFFER_SIZE

#define ASCII_PALETTE_BUFFER_SIZE   256

◆ ASCII_SLEEP_NS

#define ASCII_SLEEP_NS   50000L

#include <include/ascii-chat/video/ascii/ascii.h>

Sleep duration in nanoseconds between frames (50000 ns = 50 μs).

Sleep duration between frame outputs for frame rate limiting. Used to prevent excessive terminal I/O and control frame rate.

Note
50000 nanoseconds = 50 microseconds = 0.05 milliseconds
Used for frame rate limiting in video playback.

Definition at line 451 of file ascii.h.

◆ ascii_zzz

#define ascii_zzz ( )

#include <include/ascii-chat/video/ascii/ascii.h>

Value:
void time_sleep_ns(uint64_t ns)
Configuration for adaptive sleep behavior.
Definition time.c:107
#define ASCII_SLEEP_NS
Sleep duration in nanoseconds between frames (50000 ns = 50 μs).
Definition ascii.h:451

Sleep for frame rate limiting.

Sleeps for a short duration (50 microseconds) to limit frame rate and prevent excessive terminal I/O. Uses time_sleep_ns() for precise nanosecond-precision timing control with the unified timing API.

Note
Sleep duration: 50000 nanoseconds (50 microseconds)
Used between frame outputs for rate limiting.

Definition at line 576 of file ascii.h.

◆ CACHE_FREQUENCY_DECAY_TIME

#define CACHE_FREQUENCY_DECAY_TIME   10000

◆ CACHE_MAX_LIFETIME

#define CACHE_MAX_LIFETIME   3600

◆ CACHE_RECENCY_SCALE

#define CACHE_RECENCY_SCALE   100

◆ console_clear

#define console_clear ( fd)

#include <include/ascii-chat/video/ascii/ascii.h>

Value:

Clear console and move cursor to home position.

Parameters
fdFile descriptor for terminal

Clears terminal screen and moves cursor to home position (top-left). Equivalent to terminal_clear_screen() followed by terminal_cursor_home().

Definition at line 535 of file ascii.h.

◆ cursor_reset

#define cursor_reset ( fd)

#include <include/ascii-chat/video/ascii/ascii.h>

Value:

Reset cursor to home position.

Parameters
fdFile descriptor for terminal

Moves cursor to home position (top-left, row 1, column 1). Equivalent to terminal_cursor_home().

Definition at line 546 of file ascii.h.

◆ DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED

#define DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED   1.0f

#include <include/ascii-chat/video/anim/digital_rain.h>

Default animation speed multiplier.

Overall animation speed. 1.0 = normal speed.

Definition at line 141 of file digital_rain.h.

Referenced by digital_rain_init().

◆ DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY

#define DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY   0.1f

#include <include/ascii-chat/video/anim/digital_rain.h>

Default brightness decay factor.

Controls how quickly brightness transitions occur (0-1). Higher values = more immediate transitions, lower = smoother.

Definition at line 134 of file digital_rain.h.

Referenced by digital_rain_init().

◆ DIGITAL_RAIN_DEFAULT_COLOR_B

#define DIGITAL_RAIN_DEFAULT_COLOR_B   80

◆ DIGITAL_RAIN_DEFAULT_COLOR_G

#define DIGITAL_RAIN_DEFAULT_COLOR_G   255

◆ DIGITAL_RAIN_DEFAULT_COLOR_R

#define DIGITAL_RAIN_DEFAULT_COLOR_R   0

#include <include/ascii-chat/video/anim/digital_rain.h>

Default Matrix green color (R, G, B).

Classic Matrix green: (0, 255, 80)

Definition at line 148 of file digital_rain.h.

Referenced by digital_rain_init(), and digital_rain_set_color_from_filter().

◆ DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS

#define DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS   2.0f

#include <include/ascii-chat/video/anim/digital_rain.h>

Cursor brightness multiplier.

How much brighter the cursor should be compared to regular characters.

Definition at line 157 of file digital_rain.h.

Referenced by digital_rain_init().

◆ DIGITAL_RAIN_DEFAULT_FALL_SPEED

#define DIGITAL_RAIN_DEFAULT_FALL_SPEED   10.0f

#include <include/ascii-chat/video/anim/digital_rain.h>

Default fall speed for raindrops.

Controls how fast the brightness wave moves down each column. Higher values = faster falling rain.

Definition at line 118 of file digital_rain.h.

Referenced by digital_rain_init().

◆ DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH

#define DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH   12.0f

#include <include/ascii-chat/video/anim/digital_rain.h>

Default raindrop length.

Controls the length of each raindrop in grid cells. Smaller values = shorter, more frequent raindrops.

Definition at line 126 of file digital_rain.h.

Referenced by digital_rain_init().

◆ IMAGE_MAX_HEIGHT

#define IMAGE_MAX_HEIGHT   2160

#include <include/ascii-chat/video/rgba/image.h>

Maximum image height (4K resolution).

Maximum supported image height in pixels. Set to 2160 pixels (4K UHD height) to support high-resolution video capture.

Note
Larger images may exceed memory limits.
Video pipeline may enforce lower limits for performance.

Definition at line 173 of file video/rgba/image.h.

Referenced by ascii_convert_with_buffers_stabilized(), image_validate_dimensions(), and mirror_convert_frame().

◆ IMAGE_MAX_PIXELS_SIZE

#define IMAGE_MAX_PIXELS_SIZE   (IMAGE_MAX_WIDTH * IMAGE_MAX_HEIGHT * sizeof(rgb_pixel_t))

#include <include/ascii-chat/video/rgba/image.h>

Maximum pixel data size in bytes.

Maximum size in bytes for pixel data array. Calculated as: IMAGE_MAX_WIDTH * IMAGE_MAX_HEIGHT * sizeof(rgb_pixel_t) Used for buffer allocation and validation.

Note
This is approximately 24.88 MB for 4K RGB images.
Actual memory usage may be higher due to alignment.

Definition at line 187 of file video/rgba/image.h.

Referenced by frame_validate_new(), image_new(), and image_validate_buffer_size().

◆ IMAGE_MAX_WIDTH

#define IMAGE_MAX_WIDTH   3840

#include <include/ascii-chat/video/rgba/image.h>

An owned RGB image with dimensions and row-major pixel storage.

Maximum image width (4K resolution)

Maximum supported image width in pixels. Set to 3840 pixels (4K UHD width) to support high-resolution video capture.

Note
Larger images may exceed memory limits.
Video pipeline may enforce lower limits for performance.

Definition at line 160 of file video/rgba/image.h.

Referenced by ascii_convert_with_buffers_stabilized(), image_validate_dimensions(), and mirror_convert_frame().

◆ LUMA_BLUE

#define LUMA_BLUE   29

#include <include/ascii-chat/video/ascii/common.h>

Luminance blue coefficient (0.114 * 256 = 29).

Definition at line 103 of file include/ascii-chat/video/ascii/common.h.

Referenced by simd_luminance_neon(), simd_luminance_ssse3(), and simd_luminance_sve().

◆ LUMA_GREEN

#define LUMA_GREEN   150

#include <include/ascii-chat/video/ascii/common.h>

Luminance green coefficient (0.587 * 256 = 150).

Definition at line 101 of file include/ascii-chat/video/ascii/common.h.

Referenced by simd_luminance_neon(), simd_luminance_ssse3(), and simd_luminance_sve().

◆ LUMA_RED

#define LUMA_RED   77

#include <include/ascii-chat/video/ascii/common.h>

Luminance red coefficient (0.299 * 256 = 77).

Definition at line 99 of file include/ascii-chat/video/ascii/common.h.

Referenced by simd_luminance_neon(), simd_luminance_sse2(), simd_luminance_ssse3(), and simd_luminance_sve().

◆ LUMA_THRESHOLD

#define LUMA_THRESHOLD   128

#include <include/ascii-chat/video/ascii/common.h>

Luminance threshold for rounding.

Definition at line 105 of file include/ascii-chat/video/ascii/common.h.

Referenced by simd_luminance_ssse3(), and simd_luminance_sve().

◆ print

#define print ( s)

#include <include/ascii-chat/video/ascii/ascii.h>

Value:
fwrite(s, 1, sizeof(s) / sizeof((s)[0]), stdout)

Print string to stdout.

Parameters
sString literal to print

Utility macro for printing string literals to stdout. Uses fwrite() for efficient output without null terminator requirement.

Note
This is a macro that expands to fwrite() call.
Only works with string literals (compile-time known size).
Use fputs() or printf() for runtime strings.

Definition at line 516 of file ascii.h.

◆ RAMP64_SIZE

#define RAMP64_SIZE   64

#include <include/ascii-chat/video/ascii/common.h>

UTF-8 character palette cache.

Definition at line 489 of file include/ascii-chat/video/ascii/common.h.

Referenced by build_ramp64().

Typedef Documentation

◆ digital_rain_t

typedef struct digital_rain digital_rain_t

#include <include/ascii-chat/video/anim/digital_rain.h>

Digital rain effect context.

Maintains state for the entire digital rain effect across frames. Tracks column states and effect parameters.

◆ image_t

typedef struct image image_t

#include <include/ascii-chat/video/rgba/image.h>

SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the layout aligned for vector loads; it is normally embedded in renderer buffers, not individually allocated.

An owned RGB image with dimensions and row-major pixel storage

Complete image structure containing dimensions and pixel data. Pixel data is stored as a contiguous array of RGB pixels in row-major order. Compatible with webcam capture and image processing pipeline.

MEMORY LAYOUT:

  • structure and pixels share one allocation, with pixels aligned to 64 bytes
  • pixels array size: width * height * sizeof(rgb_pixel_t)
  • Pixel access: pixels[row * width + col]
  • Row-major order (first row, then second row, etc.)
Note
Pixel array must be allocated (by image_new()).
Only image_destroy() releases an owned image; pixels are a borrowed view.
Compatible with webcam capture functions (webcam_read_context()).

◆ utf8_palette_cache_t

Function Documentation

◆ alloc_image()

ImageRGB alloc_image ( int w,
int h )

#include <include/ascii-chat/video/ascii/common.h>

Allocate a new ImageRGB (RGB8 format).

Parameters
wImage width
hImage height
Returns
Allocated ImageRGB structure
Note
Aborts on out-of-memory condition.

◆ ansi_compress_rle()

char * ansi_compress_rle ( const char * input,
size_t input_len )

#include <include/ascii-chat/video/ascii/rle.h>

Compress repeated characters using RLE escape sequences.

Parameters
inputInput string (may contain ANSI escape codes)
input_lenLength of input string
Returns
Newly allocated string with RLE compression (caller must free)

Compresses runs of repeated printable characters using ANSI RLE sequences. Only compresses when profitable (run length > RLE overhead). Preserves all existing escape sequences.

Note
The returned string must be freed by the caller using free().
Returns NULL if input is NULL or allocation fails.
Only compresses runs where RLE saves bytes (typically 4+ chars).
Example
const char *frame = "AAAAAAA\x1b[31mBBBBB\n";
char *compressed = ansi_compress_rle(frame, strlen(frame));
// compressed = "A\x1b[6b\x1b[31mB\x1b[4b\n"
free(compressed);
char * ansi_compress_rle(const char *input, size_t input_len)
Compress repeated characters using RLE escape sequences.
Definition rle.c:99

Definition at line 99 of file rle.c.

99 {
100 if (!input || input_len == 0) {
101 return NULL;
102 }
103
104 outbuf_t ob = {0};
105 ob_reserve(&ob, input_len);
106
107 size_t i = 0;
108 while (i < input_len) {
109 // Check for ESC character (start of ANSI sequence)
110 if (input[i] == '\x1b' && i + 1 < input_len && input[i + 1] == '[') {
111 size_t seq_start = i;
112 i += 2; // Skip ESC[
113
114 // Skip parameter bytes
115 while (i < input_len && ((input[i] >= '0' && input[i] <= '9') || input[i] == ';')) {
116 i++;
117 }
118
119 // Skip final byte
120 if (i < input_len) {
121 i++;
122 }
123
124 // Copy entire escape sequence as-is
125 ob_write(&ob, input + seq_start, i - seq_start);
126 } else {
127 // Regular character - check for runs
128 char c = input[i];
129
130 // Only compress printable characters (not newlines, not control chars)
131 if (c >= 0x20 && c != 0x7F) {
132 // Count run length
133 size_t run_len = 1;
134 i++;
135
136 while (i < input_len && input[i] == c) {
137 run_len++;
138 i++;
139 }
140
141 // Emit first character
142 ob_putc(&ob, c);
143
144 // Use RLE if profitable (run > overhead of ESC[Nb)
145 if (run_len > 1 && rep_is_profitable((uint32_t)run_len)) {
146 emit_rep(&ob, (uint32_t)(run_len - 1));
147 } else {
148 // Emit remaining characters directly
149 for (size_t k = 1; k < run_len; k++) {
150 ob_putc(&ob, c);
151 }
152 }
153 } else {
154 // Non-compressible character (newline, etc.)
155 ob_putc(&ob, c);
156 i++;
157 }
158 }
159 }
160
161 ob_term(&ob);
162 return ob.buf;
163}
unsigned int uint32_t
void ob_term(outbuf_t *ob)
Append null terminator to buffer.
void ob_putc(outbuf_t *ob, char c)
Append a character to buffer.
bool rep_is_profitable(uint32_t runlen)
Check if run-length encoding is profitable.
void ob_reserve(outbuf_t *ob, size_t need)
Dynamic output buffer (auto-expanding).
void emit_rep(outbuf_t *ob, uint32_t extra)
Emit run-length encoded sequence.
void ob_write(outbuf_t *ob, const void *s, size_t n)
Append a string to buffer.
Dynamic output buffer (auto-expanding).
char * buf
Buffer pointer (allocated, owned by caller, must be freed).

References outbuf_t::buf, emit_rep(), ob_putc(), ob_reserve(), ob_term(), ob_write(), and rep_is_profitable().

◆ ansi_expand_rle()

char * ansi_expand_rle ( const char * input,
size_t input_len )

#include <include/ascii-chat/video/ascii/rle.h>

Expand RLE escape sequences in a string.

Parameters
inputInput string containing ANSI escape codes
input_lenLength of input string
Returns
Newly allocated string with RLE expanded (caller must free)

Expands ANSI RLE (REP) sequences while preserving all other escape codes:

  • RLE sequences (ESC[Nb) are expanded: previous character repeated N times
  • All other escape sequences (colors, cursor, etc.) are preserved as-is

This is useful when outputting to files/pipes where terminals can't interpret RLE, but you still want to preserve color codes.

Note
The returned string must be freed by the caller using free().
Returns NULL if input is NULL or allocation fails.
Example
const char *frame = "A\x1b[3b\x1b[31mB\n"; // A + repeat 3 + red + B
char *expanded = ansi_expand_rle(frame, strlen(frame));
// expanded = "AAAA\x1b[31mB\n" (RLE expanded, color preserved)
free(expanded);
char * ansi_expand_rle(const char *input, size_t input_len)
Expand RLE escape sequences in a string.
Definition rle.c:14

Definition at line 14 of file rle.c.

14 {
15 if (!input || input_len == 0) {
16 return NULL;
17 }
18
19 // RLE expansion can make output larger than input, start with 2x capacity
20 outbuf_t ob = {0};
21 ob_reserve(&ob, input_len * 2);
22
23 // Track the last character/grapheme for RLE expansion
24 // UTF-8 characters can be up to 4 bytes
25 char last_char[ASCII_CHAT_UTF8_BUFFER_SIZE] = " ";
26 size_t last_char_len = 1;
27
28 size_t i = 0;
29 while (i < input_len) {
30 // Check for ESC character (start of ANSI sequence)
31 if (input[i] == '\x1b' && i + 1 < input_len && input[i + 1] == '[') {
32 size_t seq_start = i;
33 i += 2; // Skip ESC[
34
35 // Parse parameter bytes (digits and semicolons)
36 uint32_t param = 0;
37 while (i < input_len && ((input[i] >= '0' && input[i] <= '9') || input[i] == ';')) {
38 if (input[i] >= '0' && input[i] <= '9') {
39 param = param * 10 + (uint32_t)(input[i] - '0');
40 } else if (input[i] == ';') {
41 param = 0; // Reset for next parameter
42 }
43 i++;
44 }
45
46 // Check for final byte
47 if (i < input_len) {
48 char final_byte = input[i];
49 i++;
50
51 // Handle RLE: ESC[Nb repeats previous character N times
52 if (final_byte == 'b' && param > 0) {
53 for (uint32_t r = 0; r < param; r++) {
54 ob_write(&ob, last_char, last_char_len);
55 }
56 } else {
57 // Not RLE - copy the entire escape sequence as-is
58 ob_write(&ob, input + seq_start, i - seq_start);
59 }
60 }
61 } else {
62 // Regular character - copy to output and track for RLE
63 unsigned char c = (unsigned char)input[i];
64 size_t char_len = 1;
65
66 // Determine UTF-8 character length from first byte
67 if ((c & 0x80) == 0) {
68 char_len = 1; // ASCII
69 } else if ((c & 0xE0) == 0xC0) {
70 char_len = 2; // 2-byte UTF-8
71 } else if ((c & 0xF0) == 0xE0) {
72 char_len = 3; // 3-byte UTF-8
73 } else if ((c & 0xF8) == 0xF0) {
74 char_len = 4; // 4-byte UTF-8
75 }
76
77 // Make sure we don't read past end of input
78 if (i + char_len > input_len) {
79 char_len = input_len - i;
80 }
81
82 // Copy full UTF-8 character to output
83 ob_write(&ob, input + i, char_len);
84
85 // Track last printable character for RLE (skip control chars)
86 if (c >= 0x20 && c != 0x7F) {
87 SAFE_MEMCPY(last_char, sizeof(last_char), input + i, char_len);
88 last_char[char_len] = '\0';
89 last_char_len = char_len;
90 }
91 i += char_len;
92 }
93 }
94
95 ob_term(&ob);
96 return ob.buf;
97}
#define ASCII_CHAT_UTF8_BUFFER_SIZE
#define SAFE_MEMCPY(dest, dest_size, src, count)

References ASCII_CHAT_UTF8_BUFFER_SIZE, outbuf_t::buf, ob_reserve(), ob_term(), ob_write(), and SAFE_MEMCPY.

Referenced by session_display_write_ascii_frame(), and zalgo_apply().

◆ apply_color_filter()

int apply_color_filter ( uint8_t * pixels,
uint32_t width,
uint32_t height,
uint32_t stride,
color_filter_t filter,
float time )

#include <include/ascii-chat/video/rgba/color_filter.h>

Apply color filter to entire image in-place.

Parameters
pixelsImage pixel buffer (modified in-place)
widthImage width in pixels
heightImage height in pixels
strideBytes per row (typically width * 3 for RGB24)
filterColor filter to apply (COLOR_FILTER_NONE = no-op)
timeCurrent time in seconds (used for COLOR_FILTER_RAINBOW animation)
Returns
0 on success, -1 on error (invalid parameters)

Applies the specified color filter to an RGB image. The operation:

  1. Converts each RGB pixel to grayscale (ITU-R BT.601)
  2. Scales grayscale by the filter's RGB color values
  3. Modifies pixels in-place

For "color on white" mode (black-on-white only): Dark pixels get full color, light pixels become white

For "white on color" mode (all other filters): Grayscale value scales the color intensity

For COLOR_FILTER_RAINBOW: Uses time parameter to cycle through RGB spectrum (3.5s period)

Note
This function modifies the image in-place
If filter == COLOR_FILTER_NONE, this is a no-op
Expected stride is typically width * 3 for RGB24 format

Definition at line 279 of file color_filter.c.

279 {
280 if (!pixels || width == 0 || height == 0 || stride == 0) {
281 return -1;
282 }
283
284 if (filter == COLOR_FILTER_NONE) {
285 return 0; // No-op for none filter
286 }
287
288 // Special handling for rainbow filter
289 if (filter == COLOR_FILTER_RAINBOW) {
290 uint8_t rainbow_r, rainbow_g, rainbow_b;
291 color_filter_calculate_rainbow(time, &rainbow_r, &rainbow_g, &rainbow_b);
292
293 // Create temporary filter def with current rainbow color
294 color_filter_def_t rainbow_filter = {
295 .name = "rainbow",
296 .cli_name = "rainbow",
297 .r = rainbow_r,
298 .g = rainbow_g,
299 .b = rainbow_b,
300 .foreground_on_bg = false,
301 };
302
303 // Process each pixel with minimum brightness to prevent black
304 // Minimum brightness is 70% to ensure rainbow colors stay vibrant even for dark input
305 const uint8_t min_brightness = 179; // 70% of 255
306
307 for (uint32_t y = 0; y < height; y++) {
308 uint8_t *row = pixels + y * stride;
309 for (uint32_t x = 0; x < width; x++) {
310 uint8_t *pixel = row + x * 3;
311 uint8_t r = pixel[0];
312 uint8_t g = pixel[1];
313 uint8_t b = pixel[2];
314 uint8_t gray = rgb_to_grayscale(r, g, b);
315
316 // Boost grayscale to maintain minimum brightness for rainbow
317 // Formula: adjusted = min + gray * (1 - min/255)
318 // This ensures: black pixels -> min_brightness, white pixels -> 255
319 uint8_t adjusted_gray = min_brightness + (uint8_t)((gray * (255U - min_brightness)) / 255U);
320
321 colorize_grayscale_pixel(adjusted_gray, &rainbow_filter, &pixel[0], &pixel[1], &pixel[2]);
322 }
323 }
324 return 0;
325 }
326
327 const color_filter_def_t *filter_def = color_filter_get_metadata(filter);
328 if (!filter_def) {
329 return -1; // Invalid filter
330 }
331
332 // Process each pixel in the image
333 for (uint32_t y = 0; y < height; y++) {
334 uint8_t *row = pixels + y * stride;
335 for (uint32_t x = 0; x < width; x++) {
336 uint8_t *pixel = row + x * 3; // Assume RGB24 (3 bytes per pixel)
337 uint8_t r = pixel[0];
338 uint8_t g = pixel[1];
339 uint8_t b = pixel[2];
340
341 // Convert RGB to grayscale using ITU-R BT.601
342 uint8_t gray = rgb_to_grayscale(r, g, b);
343
344 // Colorize the grayscale value
345 colorize_grayscale_pixel(gray, filter_def, &pixel[0], &pixel[1], &pixel[2]);
346 }
347 }
348
349 return 0;
350}
const color_filter_def_t * color_filter_get_metadata(color_filter_t filter)
Get color filter metadata by enum value.
void color_filter_calculate_rainbow(float time, uint8_t *r, uint8_t *g, uint8_t *b)
Calculate rainbow color from time (3.5s cycle).
For color filter def, this is the live record that ties name, cli_name, r, g together....

References color_filter_calculate_rainbow(), color_filter_get_metadata(), height, and width.

Referenced by ascii_convert_with_buffers_stabilized(), and mirror_convert_frame().

◆ ascii_convert()

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] )

#include <include/ascii-chat/video/ascii/ascii.h>

Convert image to ASCII art.

Parameters
originalSource image (must not be NULL)
widthTarget width in characters (must be > 0)
heightTarget height in characters (must be > 0)
colorEnable color output (true for color, false for monochrome)
aspect_ratioPreserve aspect ratio (true to maintain proportions, false to fill dimensions)
stretchStretch to fit (if aspect_ratio is false, true to fill exactly, false to fit within)
palette_charsCharacter palette to use (or NULL for default ASCII palette)
luminance_paletteLuminance-to-character mapping palette (must not be NULL, 256 elements)
Returns
Allocated ASCII frame string (caller must free), or NULL on error

Converts an image to ASCII art with specified dimensions and color mode. Uses character palette to map pixel luminance to ASCII characters and optionally applies color output using ANSI escape sequences.

CONVERSION PROCESS:

  • Resizes image to target dimensions (with aspect ratio preservation if enabled)
  • Maps each pixel's luminance to ASCII character using palette
  • Optionally applies color output using ANSI escape sequences
  • Returns null-terminated string containing ASCII frame
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Aspect ratio preservation uses terminal character correction.
Color output requires terminal color support for proper display.

Definition at line 154 of file ascii.c.

155 {
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}
const simd_cells_t * simd_cells_backend(void)
Definition cells.c:61
terminal_render_mode_t render_mode
Definition fft.c:27
#define SAFE_FREE(ptr)
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define GET_OPTION(field)
Definition options.h:1333
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 * image_print(const image_t *image, const char *palette)
Print image as ASCII art (monochrome).
Definition foreground.c:12
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
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
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
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.
#define ascii_render_halfblocks
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).

References ASCII_COLOR_TRUE, ASCII_LUMINANCE_LEVELS, ascii_pad_frame_height(), ascii_pad_frame_width(), ascii_render_halfblocks, aspect_ratio(), GET_OPTION, image::h, height, image_clear(), image_destroy(), image_new(), image_print(), image_print_color_simd(), image_resize(), log_error, image::pixels, render_mode, SAFE_FREE, simd_cells_backend(), image::w, and width.

◆ ascii_convert_with_capabilities()

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 )

#include <include/ascii-chat/video/ascii/ascii.h>

Convert image to ASCII art with terminal capability awareness.

Parameters
originalSource image (must not be NULL)
widthTarget width in characters (must be > 0)
heightTarget height in characters (must be > 0)
capsTerminal capabilities structure (must not be NULL)
use_aspect_ratioPreserve aspect ratio (true to maintain proportions, false to fill dimensions)
stretchStretch to fit (if use_aspect_ratio is false, true to fill exactly, false to fit within)
palette_charsCharacter palette to use (or NULL for default ASCII palette)
luminance_paletteLuminance-to-character mapping palette (must not be NULL, 256 elements)
Returns
Allocated ASCII frame string (caller must free), or NULL on error

Converts an image to ASCII art with automatic color mode selection based on terminal capabilities. Automatically chooses the best color mode (16-color, 256-color, or truecolor) for optimal display.

CAPABILITY-AWARE CONVERSION:

  • Detects terminal color capabilities from structure
  • Selects optimal color mode (truecolor > 256-color > 16-color > monochrome)
  • Applies terminal character aspect ratio correction
  • Uses capability-specific conversion algorithms
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Color mode is selected automatically based on terminal capabilities.
This is the recommended function for capability-aware ASCII conversion.

Definition at line 259 of file ascii.c.

260 {
261
262 return ascii_convert_with_capabilities_fit(original, width, height, caps, use_aspect_ratio, stretch, palette_chars, false);
263}
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

References ascii_convert_with_capabilities_fit(), height, and width.

◆ ascii_create_grid()

char * ascii_create_grid ( ascii_frame_source_t * sources,
int source_count,
int width,
int height,
size_t * out_size )

#include <include/ascii-chat/video/ascii/ascii.h>

Create a grid layout from multiple ASCII frames.

Parameters
sourcesArray of frame sources (must not be NULL, must have source_count elements)
source_countNumber of frame sources (must be > 0)
widthGrid width in characters per frame (must be > 0)
heightGrid height in characters per frame (must be > 0)
out_sizePointer to store output size in bytes (can be NULL)
Returns
Allocated grid frame string (caller must free), or NULL on error

Combines multiple ASCII frames into a single grid layout. Arranges frames in a grid pattern suitable for multi-user display. Each frame is positioned in the grid according to its index in the sources array.

GRID LAYOUT:

  • Frames are arranged in grid pattern (rows and columns)
  • Each frame has specified width and height in characters
  • Grid dimensions are calculated based on source_count
  • Output frame contains all frames arranged in grid
Note
Returns NULL on error (invalid sources, memory allocation failure).
Grid frame string must be freed by caller using free().
Frame sources must have valid frame_data and frame_size.
Grid layout is useful for multi-user video display.
Example
// Initialize sources...
char *grid = ascii_create_grid(sources, 4, 80, 40, NULL);
if (grid) {
ascii_write(grid);
free(grid);
}
asciichat_error_t ascii_write(const char *frame)
Write ASCII frame to terminal.
Definition ascii.c:506
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
Frame source structure for grid layout.
Definition ascii.h:350

Creates a grid layout from multiple ASCII frame sources with | and _ separators.

Parameters: sources Array of ASCII frame sources to combine source_count Number of sources in the array width Target width of the output grid height Target height of the output grid out_size Output parameter for the size of the returned buffer

Returns: A newly allocated, null-terminated string containing the grid layout, or NULL on error. Caller must free the returned buffer.

Definition at line 708 of file ascii.c.

708 {
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}
asciichat_error_t ascii_grid_layout(int source_count, int width, int height, int *grid_cols, int *grid_rows)
Definition ascii.c:625
#define SET_ERRNO(code,...)
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.
struct frame_buffer frame_buffer_t
Opaque frame buffer handle.
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
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
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
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

References ascii_grid_layout(), ASCIICHAT_OK, ERROR_INVALID_PARAM, frame_buffer_append(), frame_buffer_create(), frame_buffer_destroy(), frame_buffer_get_content(), frame_buffer_get_length(), ascii_frame_source_t::frame_data, ascii_frame_source_t::frame_size, height, SAFE_CALLOC, SAFE_FREE, SAFE_MALLOC, SAFE_MEMCPY, SET_ERRNO, utf8_display_width_n(), utf8_prefix_bytes_for_width(), and width.

Referenced by mirror_convert_frame().

◆ ascii_pad_frame_height()

char * ascii_pad_frame_height ( const char * frame,
size_t pad_top )

#include <include/ascii-chat/video/ascii/ascii.h>

Add blank lines (vertical padding) to center a frame vertically.

Parameters
frameASCII frame string (must not be NULL)
pad_topNumber of blank lines to add at top (must be >= 0)
Returns
Allocated padded frame string (caller must free with free()), or NULL on error

Adds blank lines (vertical padding) to the top of an ASCII frame. Useful for centering frames vertically or creating margins. Blank lines are added at the top of the frame.

Note
Returns NULL on error (invalid frame, memory allocation failure).
Padded frame string must be freed by caller using free().
Frame width is preserved (characters per line unchanged).
Frame height is increased by 'pad_top' lines.

Adds vertical padding (blank lines) to center a frame vertically.

Parameters: frame The input ASCII frame to pad vertically. pad_top Number of blank lines to add at the top.

Returns: A newly allocated, null-terminated string with vertical padding, or NULL if frame is NULL.

NOTE: Uses plain newlines instead of ANSI escape sequences to support both TTY and piped/redirected output. TTY flicker prevention is handled by the display layer (e.g., display.c) when appropriate.

Definition at line 831 of file ascii.c.

831 {
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}

References SAFE_MALLOC, and SAFE_MEMCPY.

Referenced by ascii_convert().

◆ ascii_pad_frame_width()

char * ascii_pad_frame_width ( const char * frame,
size_t pad )

#include <include/ascii-chat/video/ascii/ascii.h>

Add leading spaces (left-padding) to each line of a frame.

Parameters
frameASCII frame string (must not be NULL)
padNumber of spaces to pad on left (must be >= 0)
Returns
Allocated padded frame string (caller must free with free()), or NULL on error

Adds leading spaces (left-padding) to each line of an ASCII frame. Useful for centering frames horizontally or creating margins. Each line in the frame is padded with the specified number of spaces.

Note
Returns NULL on error (invalid frame, memory allocation failure).
Padded frame string must be freed by caller using free().
Frame height is preserved (number of lines unchanged).
Frame width is increased by 'pad' characters.

Definition at line 563 of file ascii.c.

563 {
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}
#define SAFE_MEMSET(dest, dest_size, ch, count)

References ERROR_INVALID_PARAM, SAFE_MALLOC, SAFE_MEMCPY, SAFE_MEMSET, and SET_ERRNO.

Referenced by ascii_convert().

◆ ascii_simd_init()

void ascii_simd_init ( void )

#include <include/ascii-chat/video/ascii/common.h>

Initialize SIMD subsystem.

Initializes all SIMD subsystems and caches. Must be called once at startup.

Definition at line 618 of file video/ascii/common.c.

618 {
619 init_dec3();
621}
void init_dec3(void)
Initialize decimal-to-ASCII cache (0-255 → "0" to "255").
void init_default_luminance_palette(void)
Initialize default luminance palette.

References init_dec3(), and init_default_luminance_palette().

Referenced by ansi_fast_init(), server_main(), and session_host_start_render().

◆ ascii_write()

asciichat_error_t ascii_write ( const char * frame)

#include <include/ascii-chat/video/ascii/ascii.h>

Write ASCII frame to terminal.

Parameters
frameASCII frame string to write (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Writes an ASCII frame string to the terminal output. Frame string may contain ANSI escape sequences for color output and cursor positioning. Output is written to the file descriptor configured during ascii_write_init().

Note
Frame string should be null-terminated.
ANSI escape sequences in frame string are processed by terminal.
Output is written immediately (no buffering).

Definition at line 506 of file ascii.c.

506 {
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}
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
bool terminal_should_use_control_sequences(int fd, bool user_setting)
#define UI_MEDIA_MIN_COLS
Definition too_small.h:9
#define UI_MEDIA_MIN_ROWS
Definition too_small.h:10
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

References ERROR_INVALID_PARAM, ERROR_MEMORY, GET_OPTION, log_warn, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, terminal_should_use_control_sequences(), ui_controller_present(), ui_controller_write(), UI_MEDIA_MIN_COLS, UI_MEDIA_MIN_ROWS, and UI_SCREEN_MEDIA.

◆ ascii_write_destroy()

void ascii_write_destroy ( int fd,
bool reset_terminal )

#include <include/ascii-chat/video/ascii/ascii.h>

Destroy ASCII write subsystem.

Parameters
fdFile descriptor that was used for writing (must be valid)
reset_terminalWhether to reset terminal on cleanup (true to restore state, false to preserve)

Cleans up the ASCII write subsystem and restores terminal state. Restores cursor visibility, clears screen, and resets terminal attributes if reset_terminal is true.

TERMINAL CLEANUP:

  • Restores cursor visibility (if reset_terminal is true)
  • Resets terminal attributes (if reset_terminal is true)
  • Clears screen (if reset_terminal is true)
  • Restores terminal to default state
Note
Safe to call multiple times (no-op after first call).
Reset terminal restores terminal to default state.
After cleanup, terminal output functions may fail until re-initialized.

Definition at line 525 of file ascii.c.

525 {
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}
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
int terminal_set_echo(bool enabled)

References ASCIICHAT_OK, GET_OPTION, log_debug, log_warn, terminal_set_echo(), terminal_should_use_control_sequences(), and ui_controller_write().

Referenced by session_display_destroy().

◆ ascii_write_init()

asciichat_error_t ascii_write_init ( int fd,
bool reset_terminal )

#include <include/ascii-chat/video/ascii/ascii.h>

Initialize ASCII write subsystem.

Parameters
fdFile descriptor to write to (must be valid file descriptor)
reset_terminalWhether to reset terminal on initialization (true to reset, false to preserve state)
Returns
ASCIICHAT_OK on success, error code on failure

Initializes the ASCII write subsystem for terminal output. Configures terminal for ASCII art display including cursor hiding, screen clearing, and terminal state management.

TERMINAL INITIALIZATION:

  • Hides cursor (if reset_terminal is true)
  • Clears screen (if reset_terminal is true)
  • Configures terminal for raw output
  • Prepares terminal for ASCII art display
Note
Must call ascii_write_destroy() when done.
Reset terminal clears screen and hides cursor for clean display.
File descriptor is used for terminal output (stdout, stderr, etc.).

Definition at line 127 of file ascii.c.

127 {
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}
@ ERROR_TERMINAL
Definition error_codes.h:68
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
void ui_controller_redraw(void)

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_TERMINAL, GET_OPTION, log_dev, log_error, log_warn, terminal_set_echo(), terminal_should_use_control_sequences(), ui_controller_redraw(), and ui_controller_write().

Referenced by session_display_create().

◆ benchmark_simd_color_conversion()

simd_benchmark_t benchmark_simd_color_conversion ( int width,
int height,
int iterations,
bool background_mode )

#include <include/ascii-chat/video/ascii/common.h>

Benchmark SIMD color conversion methods.

Parameters
widthImage width in pixels
heightImage height in pixels
iterationsNumber of benchmark iterations
background_modeUse background colors
Returns
Benchmark results structure

References height, and width.

◆ benchmark_simd_color_conversion_with_source()

simd_benchmark_t benchmark_simd_color_conversion_with_source ( int width,
int height,
int iterations,
bool background_mode,
const image_t * source_image,
bool use_256color )

#include <include/ascii-chat/video/ascii/common.h>

Benchmark SIMD color conversion with source image.

Parameters
widthImage width in pixels
heightImage height in pixels
iterationsNumber of benchmark iterations
background_modeUse background colors
source_imageSource image for conversion
use_256colorUse 256-color mode
Returns
Benchmark results structure

References height, and width.

◆ benchmark_simd_conversion()

simd_benchmark_t benchmark_simd_conversion ( int width,
int height,
int iterations )

#include <include/ascii-chat/video/ascii/common.h>

Benchmark SIMD conversion methods (monochrome).

Parameters
widthImage width in pixels
heightImage height in pixels
iterationsNumber of benchmark iterations
Returns
Benchmark results structure

References height, and width.

◆ benchmark_simd_conversion_with_source()

simd_benchmark_t benchmark_simd_conversion_with_source ( int width,
int height,
int iterations,
bool background_mode,
const image_t * source_image,
bool use_256color )

#include <include/ascii-chat/video/ascii/common.h>

Benchmark SIMD conversion with source image.

Parameters
widthImage width in pixels
heightImage height in pixels
iterationsNumber of benchmark iterations
background_modeUse background colors
source_imageSource image for conversion
use_256colorUse 256-color mode
Returns
Benchmark results structure

References height, and width.

◆ build_utf8_luminance_cache()

void build_utf8_luminance_cache ( const char * ascii_chars,
utf8_char_t cache[256] )

#include <include/ascii-chat/video/ascii/common.h>

Build UTF-8 luminance cache for all 256 levels.

Definition at line 394 of file video/ascii/common.c.

394 {
395 if (!ascii_chars || !cache)
396 return;
397
398 // Parse characters
399 typedef struct {
400 const char *start;
401 int byte_len;
402 } char_info_t;
403
404 char_info_t char_infos[256];
405 int char_count = 0;
406 const char *p = ascii_chars;
407
408 while (*p && char_count < 255) {
409 char_infos[char_count].start = p;
410
411 if ((*p & 0xE0) == 0xC0) {
412 char_infos[char_count].byte_len = 2;
413 p += 2;
414 } else if ((*p & 0xF0) == 0xE0) {
415 char_infos[char_count].byte_len = 3;
416 p += 3;
417 } else if ((*p & 0xF8) == 0xF0) {
418 char_infos[char_count].byte_len = 4;
419 p += 4;
420 } else {
421 // ASCII characters (0x00-0x7F) and invalid sequences: treat as single byte
422 char_infos[char_count].byte_len = 1;
423 p++;
424 }
425 char_count++;
426 }
427
428 // Handle empty string case
429 if (char_count == 0)
430 return;
431
432 // Build 256-entry cache
433 for (int i = 0; i < 256; i++) {
434 int char_idx = char_count > 1 ? (i * (char_count - 1) + 127) / 255 : 0;
435 if (char_idx >= char_count)
436 char_idx = char_count - 1;
437
438 cache[i].byte_len = char_infos[char_idx].byte_len;
439 memcpy(cache[i].utf8_bytes, char_infos[char_idx].start, char_infos[char_idx].byte_len);
440 if (cache[i].byte_len < 4) {
441 cache[i].utf8_bytes[cache[i].byte_len] = '\0';
442 }
443 }
444}

References utf8_char_t::byte_len, and utf8_char_t::utf8_bytes.

Referenced by get_utf8_palette_cache().

◆ build_utf8_ramp64_cache()

void build_utf8_ramp64_cache ( const char * ascii_chars,
utf8_char_t cache64[64],
uint8_t char_index_ramp[256] )

#include <include/ascii-chat/video/ascii/common.h>

Build UTF-8 ramp64 cache and character index ramp.

References ASCII_LUMINANCE_LEVELS.

◆ color_filter_calculate_rainbow()

void color_filter_calculate_rainbow ( float time,
uint8_t * r,
uint8_t * g,
uint8_t * b )

#include <include/ascii-chat/video/rgba/color_filter.h>

Calculate rainbow color from time (3.5s cycle).

Parameters
timeCurrent time in seconds
rOutput red component (0-255)
gOutput green component (0-255)
bOutput blue component (0-255)

Centralized rainbow color calculation used by both –matrix and –color-filter rainbow. Cycles through full RGB spectrum over 3.5 seconds.

Calculate rainbow color from time Cycles through full spectrum over 3.5 seconds This is the centralized rainbow implementation used by both matrix and color filter

Definition at line 175 of file color_filter.c.

175 {
176 // Cycle period: 3.5 seconds
177 const float cycle_period = 3.5f;
178
179 // Normalize time to [0, 1] range within cycle
180 float phase = fmodf(time, cycle_period) / cycle_period;
181
182 // Convert to hue angle [0, 360)
183 float hue = phase * 360.0f;
184
185 // HSV to RGB conversion (S=1, V=1 for full saturation and brightness)
186 // Hue divided into 6 segments
187 float h = hue / 60.0f;
188 int i = (int)floorf(h);
189 float f = h - (float)i;
190
191 // Calculate RGB based on hue segment
192 float q = 1.0f - f;
193 float t = f;
194
195 switch (i % 6) {
196 case 0:
197 *r = 255;
198 *g = (uint8_t)(t * 255.0f + 0.5f);
199 *b = 0;
200 break; // Red to Yellow
201 case 1:
202 *r = (uint8_t)(q * 255.0f + 0.5f);
203 *g = 255;
204 *b = 0;
205 break; // Yellow to Green
206 case 2:
207 *r = 0;
208 *g = 255;
209 *b = (uint8_t)(t * 255.0f + 0.5f);
210 break; // Green to Cyan
211 case 3:
212 *r = 0;
213 *g = (uint8_t)(q * 255.0f + 0.5f);
214 *b = 255;
215 break; // Cyan to Blue
216 case 4:
217 *r = (uint8_t)(t * 255.0f + 0.5f);
218 *g = 0;
219 *b = 255;
220 break; // Blue to Magenta
221 case 5:
222 *r = 255;
223 *g = 0;
224 *b = (uint8_t)(q * 255.0f + 0.5f);
225 break; // Magenta to Red
226 default:
227 *r = 255;
228 *g = 0;
229 *b = 0;
230 break; // Fallback to red
231 }
232
233 // Ensure minimum perceived brightness by boosting luminance
234 // Pure blue (0,0,255) has luminance ~18, which appears very dark
235 // We need minimum luminance of ~120 for bright, vibrant colors
236 const float min_luminance = 120.0f;
237
238 // Calculate current luminance using ITU-R BT.709 coefficients
239 float luminance = 0.2126f * *r + 0.7152f * *g + 0.0722f * *b;
240
241 if (luminance < min_luminance) {
242 // Boost luminance by adding white (increasing all channels proportionally)
243 // This desaturates the color but makes it much brighter
244 float boost = (min_luminance - luminance) / 3.0f;
245 *r = (uint8_t)fminf(255.0f, *r + boost);
246 *g = (uint8_t)fminf(255.0f, *g + boost);
247 *b = (uint8_t)fminf(255.0f, *b + boost);
248 }
249}

Referenced by animation_apply(), apply_color_filter(), digital_rain_render_at(), and rainbow_render_ansi_at().

◆ color_filter_from_cli_name()

color_filter_t color_filter_from_cli_name ( const char * cli_name)

#include <include/ascii-chat/video/rgba/color_filter.h>

Convert color filter CLI name to enum value.

Parameters
cli_nameCLI argument name (e.g., "matrix-green")
Returns
Filter enum value, or COLOR_FILTER_NONE if not found

Converts a CLI argument name (like "matrix-green") to the corresponding color_filter_t enum value.

Note
CLI names are case-insensitive
Returns COLOR_FILTER_NONE for unknown filter names

Definition at line 156 of file color_filter.c.

156 {
157 if (!cli_name) {
158 return COLOR_FILTER_NONE;
159 }
160
161 for (int i = 0; i < COLOR_FILTER_COUNT; i++) {
162 if (platform_strcasecmp(color_filter_registry[i].cli_name, cli_name) == 0) {
163 return (color_filter_t)i;
164 }
165 }
166
167 return COLOR_FILTER_NONE;
168}
int platform_strcasecmp(const char *s1, const char *s2)

References platform_strcasecmp().

Referenced by parse_color_filter().

◆ color_filter_get_metadata()

const color_filter_def_t * color_filter_get_metadata ( color_filter_t filter)

#include <include/ascii-chat/video/rgba/color_filter.h>

Get color filter metadata by enum value.

Parameters
filterFilter enum value (color_filter_t)
Returns
Pointer to filter metadata, or NULL if invalid filter

Returns the metadata definition for a color filter including its name, RGB values, and rendering mode.

Note
The returned pointer is statically allocated and valid for program lifetime
Returns NULL for COLOR_FILTER_NONE

Definition at line 149 of file color_filter.c.

149 {
150 if (filter <= COLOR_FILTER_NONE || filter >= COLOR_FILTER_COUNT) {
151 return NULL;
152 }
153 return &color_filter_registry[filter];
154}

Referenced by apply_color_filter(), and digital_rain_set_color_from_filter().

◆ convert_pixels_scalar()

void convert_pixels_scalar ( const rgb_pixel_t * pixels,
char * ascii_chars,
int count,
const char luminance_palette[256] )

#include <include/ascii-chat/video/ascii/common.h>

Convert pixels to ASCII (scalar fallback).

Parameters
pixelsRGB pixel array
ascii_charsOutput buffer for ASCII characters
countNumber of pixels to convert
luminance_paletteLuminance-to-character mapping palette

References ASCII_LUMINANCE_LEVELS.

◆ convert_pixels_scalar_with_newlines()

char * convert_pixels_scalar_with_newlines ( image_t * image,
const char luminance_palette[256] )

#include <include/ascii-chat/video/ascii/common.h>

Convert image to ASCII with newlines (scalar fallback).

Parameters
imageSource image
luminance_paletteLuminance-to-character mapping palette
Returns
Allocated ASCII string (caller must free), or NULL on error

References ASCII_LUMINANCE_LEVELS.

◆ digital_rain_apply()

char * digital_rain_apply ( digital_rain_t * rain,
const char * frame,
float delta_time )

#include <include/ascii-chat/video/anim/digital_rain.h>

Apply digital rain effect to ASCII frame.

Parameters
rainDigital rain context (must not be NULL)
frameInput ASCII frame (must not be NULL, must be null-terminated)
delta_timeTime elapsed since last frame in seconds
Returns
Allocated frame with digital rain effect applied, or NULL on error

Applies the digital rain effect to an ASCII frame by analyzing character positions and injecting ANSI color codes to modulate brightness. The effect:

  1. Parses the frame to identify grid positions
  2. Calculates per-cell brightness using sawtooth wave pattern
  3. Detects cursor positions (brightness increases)
  4. Injects ANSI color codes to darken/brighten characters
  5. Returns new frame with effect applied

FRAME FORMAT:

  • Input can be plain ASCII or contain existing ANSI codes
  • Output contains ANSI color codes for brightness modulation
  • Frame dimensions must match num_columns x num_rows
  • Newlines are preserved in output
Note
Caller must free returned frame string
Input frame is not modified
Works with both color and monochrome frames
Preserves existing ANSI codes (may override colors)

Definition at line 359 of file digital_rain.c.

359 {
360 if (!rain || !frame || !isfinite(delta_time) || delta_time < 0 || (double)delta_time * 1e9 >= (double)(UINT64_MAX - rain->animation_timestamp_ns))
361 return NULL;
363 return NULL;
364 uint64_t now = rain->animation_timestamp_ns + (uint64_t)((double)delta_time * 1e9);
365 animation_sample_t sample;
366 if (animation_update(&rain->animation, now, &sample) != ASCIICHAT_OK)
367 return NULL;
368 rain->animation_timestamp_ns = now;
369 char *output = NULL;
370 animation_target_t target = {.type = ANIMATION_TARGET_ANSI, .ansi = {.input = frame, .out = &output, .rain = rain}};
371 if (animation_apply(&sample, &target) != ASCIICHAT_OK)
372 return NULL;
373 return output;
374}
unsigned long long uint64_t
For animation config, this is the live record that ties type, fps, speed, hidden_policy together....
animation_t animation
Producer-owned animation clock.
float animation_speed
Overall animation speed multiplier.
uint64_t animation_timestamp_ns
asciichat_error_t animation_update(animation_t *a, uint64_t now, animation_sample_t *out)
asciichat_error_t animation_set_speed(animation_t *a, double speed)
asciichat_error_t animation_apply(const animation_sample_t *s, animation_target_t *t)
@ ANIMATION_TARGET_ANSI

References digital_rain::animation, animation_apply(), animation_set_speed(), digital_rain::animation_speed, ANIMATION_TARGET_ANSI, digital_rain::animation_timestamp_ns, animation_update(), and ASCIICHAT_OK.

Referenced by mirror_convert_frame(), and session_display_write_ascii_frame().

◆ digital_rain_destroy()

void digital_rain_destroy ( digital_rain_t * rain)

#include <include/ascii-chat/video/anim/digital_rain.h>

Destroy digital rain effect context.

Parameters
rainDigital rain context to destroy (can be NULL)

Frees all resources associated with the digital rain context. Safe to call with NULL pointer.

Definition at line 172 of file digital_rain.c.

172 {
173 if (!rain) {
174 return;
175 }
176
178 SAFE_FREE(rain->columns);
180 SAFE_FREE(rain);
181}
float * previous_brightness
Previous frame brightness (for smoothing).
digital_rain_column_t * columns
Per-column state array.
void animation_destroy(animation_t *a)

References digital_rain::animation, animation_destroy(), digital_rain::columns, digital_rain::previous_brightness, and SAFE_FREE.

Referenced by cleanup_client_media_buffers(), mirror_convert_frame(), mirror_render_context_reset(), and session_display_destroy().

◆ digital_rain_glyph_group()

int digital_rain_glyph_group ( uint32_t codepoint)

#include <include/ascii-chat/video/anim/digital_rain.h>

Approximate ink-coverage group for printable ASCII, or -1 for an unmapped glyph.

Definition at line 82 of file digital_rain.c.

82 {
83 if (codepoint > 126 || codepoint <= 32)
84 return -1;
85 for (size_t i = 0; i < sizeof(glyph_groups) / sizeof(glyph_groups[0]); i++)
86 if (strchr(glyph_groups[i], (int)codepoint))
87 return (int)i;
88 return -1;
89}

◆ digital_rain_init()

digital_rain_t * digital_rain_init ( int num_columns,
int num_rows )

#include <include/ascii-chat/video/anim/digital_rain.h>

Initialize digital rain effect context.

Parameters
num_columnsNumber of columns in the ASCII grid
num_rowsNumber of rows in the ASCII grid
Returns
Allocated digital rain context, or NULL on error

Creates and initializes a digital rain effect context for the specified grid dimensions. Allocates per-column state and initializes random offsets.

Note
Caller must call digital_rain_destroy() to free resources
Returns NULL on memory allocation failure

Definition at line 110 of file digital_rain.c.

110 {
111 if (num_columns <= 0 || num_rows <= 0) {
112 log_error("invalid dimensions %dx%d", num_columns, num_rows);
113 return NULL;
114 }
115
117 if (!rain) {
118 log_error("failed to allocate context");
119 return NULL;
120 }
121 defer_named(release_rain, SAFE_FREE(rain));
122
123 rain->num_columns = num_columns;
124 rain->num_rows = num_rows;
125
126 // Allocate column state array
127 rain->columns = SAFE_CALLOC((size_t)num_columns, sizeof(digital_rain_column_t), digital_rain_column_t *);
128 if (!rain->columns) {
129 log_error("failed to allocate column array");
130 return NULL;
131 }
132 defer_named(release_columns, SAFE_FREE(rain->columns));
133
134 // Allocate previous brightness array
135 size_t grid_size = (size_t)num_columns * (size_t)num_rows;
136 rain->previous_brightness = SAFE_CALLOC(grid_size, sizeof(float), float *);
137 if (!rain->previous_brightness) {
138 log_error("failed to allocate brightness array");
139 return NULL;
140 }
141
142 // Initialize per-column random offsets
143 for (int col = 0; col < num_columns; col++) {
144 digital_rain_column_t *column = &rain->columns[col];
145 column->time_offset = random_float((float)col, 0.0f) * 1000.0f;
146 column->speed_multiplier = random_float((float)col + 0.1f, 0.0f) * 0.5f + 0.5f;
147 column->phase_offset = random_float((float)col + 0.2f, 0.0f) * (float)M_PI * 2.0f;
148 }
149
150 // Set default parameters
159 rain->rainbow_mode = false;
160 rain->first_frame = true;
161 rain->time = 0.0f;
162
163 animation_init(&rain->animation, "digital_rain", (animation_config_t){.type = ANIMATION_DIGITAL_RAIN, .fps = 60, .speed = 1, .hidden_policy = ANIMATION_HIDDEN_CONTINUE});
164 animation_sample_t initial;
165 animation_update(&rain->animation, 0, &initial);
166 log_info("Digital rain initialized: %dx%d grid", num_columns, num_rows);
167 defer_cancel(release_columns);
168 defer_cancel(release_rain);
169 return rain;
170}
#define M_PI
Definition effects.c:6
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS
Cursor brightness multiplier.
#define DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY
Default brightness decay factor.
#define DIGITAL_RAIN_DEFAULT_COLOR_B
#define DIGITAL_RAIN_DEFAULT_COLOR_R
Default Matrix green color (R, G, B).
#define DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED
Default animation speed multiplier.
#define DIGITAL_RAIN_DEFAULT_FALL_SPEED
Default fall speed for raindrops.
struct digital_rain digital_rain_t
Digital rain effect context.
#define DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH
Default raindrop length.
#define DIGITAL_RAIN_DEFAULT_COLOR_G
digital rain column keeps the values that move through the subsystem: time_offset,...
float phase_offset
Phase offset for wobble variation.
float time_offset
Random time offset for this column (prevents synchronization).
float speed_multiplier
Speed variation multiplier (0.5 to 1.0).
uint8_t color_g
Matrix green G component.
float fall_speed
Base fall speed multiplier.
uint8_t color_b
Matrix green B component.
int num_rows
Number of rows in grid.
float brightness_decay
Brightness smoothing factor (0-1).
float time
Current simulation time (accumulated).
float raindrop_length
Length of each raindrop (in cells).
uint8_t color_r
Matrix green R component.
bool first_frame
True if this is the first frame.
float cursor_brightness
Cursor brightness multiplier.
bool rainbow_mode
True if rainbow color cycling is enabled.
int num_columns
Number of columns in grid.
asciichat_error_t animation_init(animation_t *a, const char *name, animation_config_t config)

References digital_rain::animation, animation_init(), digital_rain::animation_speed, animation_update(), digital_rain::brightness_decay, digital_rain::color_b, digital_rain::color_g, digital_rain::color_r, digital_rain::columns, digital_rain::cursor_brightness, DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED, DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY, DIGITAL_RAIN_DEFAULT_COLOR_B, DIGITAL_RAIN_DEFAULT_COLOR_G, DIGITAL_RAIN_DEFAULT_COLOR_R, DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS, DIGITAL_RAIN_DEFAULT_FALL_SPEED, DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH, digital_rain::fall_speed, digital_rain::first_frame, log_error, log_info, M_PI, digital_rain::num_columns, digital_rain::num_rows, digital_rain_column_t::phase_offset, digital_rain::previous_brightness, digital_rain::rainbow_mode, digital_rain::raindrop_length, SAFE_CALLOC, SAFE_FREE, digital_rain_column_t::speed_multiplier, digital_rain::time, and digital_rain_column_t::time_offset.

Referenced by mirror_convert_frame(), and session_display_create().

◆ digital_rain_reset()

void digital_rain_reset ( digital_rain_t * rain)

#include <include/ascii-chat/video/anim/digital_rain.h>

Reset digital rain effect state.

Parameters
rainDigital rain context (must not be NULL)

Resets the digital rain effect to its initial state, clearing all timing and brightness history. Useful when switching frames or restarting the effect.

Definition at line 183 of file digital_rain.c.

183 {
184 if (!rain) {
185 return;
186 }
187
189 rain->animation_timestamp_ns = 0;
190 animation_sample_t initial;
191 animation_update(&rain->animation, 0, &initial);
192 rain->time = 0.0f;
193 rain->first_frame = true;
194
195 // Clear previous brightness
196 size_t grid_size = (size_t)rain->num_columns * (size_t)rain->num_rows;
197 memset(rain->previous_brightness, 0, grid_size * sizeof(float));
198}
void animation_reset(animation_t *a)

References digital_rain::animation, animation_reset(), digital_rain::animation_timestamp_ns, animation_update(), digital_rain::first_frame, digital_rain::num_columns, digital_rain::num_rows, digital_rain::previous_brightness, and digital_rain::time.

◆ digital_rain_set_color()

void digital_rain_set_color ( digital_rain_t * rain,
uint8_t r,
uint8_t g,
uint8_t b )

#include <include/ascii-chat/video/anim/digital_rain.h>

Set digital rain color.

Parameters
rainDigital rain context (must not be NULL)
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)

Definition at line 216 of file digital_rain.c.

216 {
217 if (rain) {
218 rain->color_r = r;
219 rain->color_g = g;
220 rain->color_b = b;
221 }
222}

References digital_rain::color_b, digital_rain::color_g, and digital_rain::color_r.

Referenced by digital_rain_set_color_from_filter().

◆ digital_rain_set_color_from_filter()

void digital_rain_set_color_from_filter ( digital_rain_t * rain,
color_filter_t filter )

#include <include/ascii-chat/video/anim/digital_rain.h>

Set digital rain color from color filter.

Parameters
rainDigital rain context (must not be NULL)
filterColor filter to use for rain color

Automatically sets the rain color based on the active color filter. If filter is COLOR_FILTER_NONE, uses default Matrix green.

Definition at line 224 of file digital_rain.c.

224 {
225 if (!rain) {
226 return;
227 }
228
229 // If no filter is set, use default Matrix green
230 if (filter == COLOR_FILTER_NONE) {
231 rain->rainbow_mode = false;
233 return;
234 }
235
236 // Rainbow mode: enable dynamic color cycling
237 if (filter == COLOR_FILTER_RAINBOW) {
238 rain->rainbow_mode = true;
239 // Set initial color to red (will be overridden during rendering)
240 digital_rain_set_color(rain, 255, 0, 0);
241 return;
242 }
243
244 // Get color from filter metadata
245 rain->rainbow_mode = false;
246 const color_filter_def_t *filter_def = color_filter_get_metadata(filter);
247 if (filter_def) {
248 digital_rain_set_color(rain, filter_def->r, filter_def->g, filter_def->b);
249 }
250}
void digital_rain_set_color(digital_rain_t *rain, uint8_t r, uint8_t g, uint8_t b)
Set digital rain color.
uint8_t b
RGB color values for this filter.

References color_filter_def_t::b, color_filter_get_metadata(), DIGITAL_RAIN_DEFAULT_COLOR_B, DIGITAL_RAIN_DEFAULT_COLOR_G, DIGITAL_RAIN_DEFAULT_COLOR_R, digital_rain_set_color(), color_filter_def_t::g, color_filter_def_t::r, and digital_rain::rainbow_mode.

Referenced by mirror_convert_frame(), session_display_create(), and session_display_write_ascii_frame().

◆ digital_rain_set_fall_speed()

void digital_rain_set_fall_speed ( digital_rain_t * rain,
float speed )

#include <include/ascii-chat/video/anim/digital_rain.h>

Set digital rain fall speed.

Parameters
rainDigital rain context (must not be NULL)
speedFall speed multiplier (suggested range: 0.1 to 5.0)

Definition at line 204 of file digital_rain.c.

204 {
205 if (rain) {
206 rain->fall_speed = speed;
207 }
208}

References digital_rain::fall_speed.

◆ digital_rain_set_raindrop_length()

void digital_rain_set_raindrop_length ( digital_rain_t * rain,
float length )

#include <include/ascii-chat/video/anim/digital_rain.h>

Set digital rain raindrop length.

Parameters
rainDigital rain context (must not be NULL)
lengthRaindrop length in cells (suggested range: 5.0 to 50.0)

Definition at line 210 of file digital_rain.c.

210 {
211 if (rain) {
212 rain->raindrop_length = length;
213 }
214}

References digital_rain::raindrop_length.

◆ emit_rep()

void emit_rep ( outbuf_t * ob,
uint32_t extra )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit run-length encoded sequence.

Parameters
obOutput buffer structure (must not be NULL)
extraAdditional characters to repeat (must be > 0)

Emits an ANSI run-length encoding sequence that repeats the last character in the buffer 'extra' times. Format: ESC[extram (where 'extra' is the repeat count and the last character is repeated).

Note
This function repeats the character at buffer[len-1].
Useful for compressing repeated characters (spaces, blocks, etc.).
Only profitable for runs exceeding threshold (see rep_is_profitable()).
Example
ob_putc(ob, ' '); // Append space
emit_rep(ob, 49); // Repeat space 49 more times (total 50)
}

Definition at line 145 of file output_buffer.c.

145 {
146 if (!ob)
147 return;
148 // ESC [ extra b
149 ob_putc(ob, 0x1b);
150 ob_putc(ob, '[');
151 ob_u32(ob, extra);
152 ob_putc(ob, 'b');
153}
void ob_u32(outbuf_t *ob, uint32_t v)
Append unsigned 32-bit integer as decimal string.

References ob_putc(), and ob_u32().

Referenced by ansi_compress_rle(), and emit_glyph_run().

◆ emit_reset()

void emit_reset ( outbuf_t * ob)

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit ANSI reset sequence.

Parameters
obOutput buffer structure (must not be NULL)

Emits ANSI escape sequence to reset all terminal attributes to defaults. Format: ESC[0m or ESC[m. Resets colors, bold, underline, and other formatting attributes.

Note
This resets both foreground and background colors to default.
Sequence length: 3 bytes (ESC[0m).
Useful for resetting terminal state between frames.

Definition at line 128 of file output_buffer.c.

128 {
129 if (!out)
130 return;
131 ob_reserve(out, 4);
132 append_sgr_reset(out->buf + out->len);
133 out->len += 4;
134}
static bool size_t gotel_query_t * out
Definition queries.h:8
char * append_sgr_reset(char *dst)
Definition sgr.c:122

References append_sgr_reset(), ob_reserve(), and out.

Referenced by ascii_emit_prepared_row(), and emit_row_end().

◆ emit_set_256_color_bg()

void emit_set_256_color_bg ( outbuf_t * ob,
uint8_t color_idx )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit 256-color background ANSI sequence.

Parameters
obOutput buffer structure (must not be NULL)
color_idx256-color palette index (0-255)

Emits ANSI escape sequence for 256-color background color. Format: ESC[48;5;idxm (where idx is palette index 0-255). Uses extended ANSI color palette for 256-color mode.

Note
Requires terminal 256-color support for proper display.
Sequence length: ~9 bytes (ESC[48;5;255m).
Palette indices 0-15 are standard ANSI colors.
Palette indices 16-255 are extended palette.

Definition at line 166 of file output_buffer.c.

166 {
167 if (!ob)
168 return;
169 // Use pre-cached color sequence instead of building on-demand
170 uint8_t seq_len;
171 const char *seq = get_sgr256_bg_string(color_idx, &seq_len);
172 ob_write(ob, seq, seq_len);
173}
char * get_sgr256_bg_string(uint8_t bg, uint8_t *len_out)
Get 256-color background ANSI sequence string.
Definition sgr.c:108

References get_sgr256_bg_string(), and ob_write().

◆ emit_set_256_color_fg()

void emit_set_256_color_fg ( outbuf_t * ob,
uint8_t color_idx )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit 256-color foreground ANSI sequence.

Parameters
obOutput buffer structure (must not be NULL)
color_idx256-color palette index (0-255)

Emits ANSI escape sequence for 256-color foreground color. Format: ESC[38;5;idxm (where idx is palette index 0-255). Uses extended ANSI color palette for 256-color mode.

Note
Requires terminal 256-color support for proper display.
Sequence length: ~9 bytes (ESC[38;5;255m).
Palette indices 0-15 are standard ANSI colors.
Palette indices 16-255 are extended palette.

Definition at line 156 of file output_buffer.c.

156 {
157 if (!ob)
158 return;
159 // Use pre-cached color sequence instead of building on-demand
160 uint8_t seq_len;
161 const char *seq = get_sgr256_fg_string(color_idx, &seq_len);
162 ob_write(ob, seq, seq_len);
163}
char * get_sgr256_fg_string(uint8_t fg, uint8_t *len_out)
Get 256-color foreground ANSI sequence string.
Definition sgr.c:100

References get_sgr256_fg_string(), and ob_write().

◆ emit_set_bg()

void emit_set_bg ( outbuf_t * ob,
uint8_t r,
uint8_t g,
uint8_t b )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit background color sequence (auto-select mode).

Parameters
obOutput buffer structure (must not be NULL)
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)

Emits background color ANSI sequence using the optimal color mode based on terminal capabilities. Automatically selects:

  • Truecolor mode (if supported): 24-bit RGB
  • 256-color mode (if supported): Quantized to 256-color palette
  • 16-color mode (fallback): Quantized to standard ANSI colors
Note
Color mode is selected based on terminal_capabilities_t configuration.
This function uses the best available color mode for the terminal.
Color quantization is applied when truecolor is not available.

Definition at line 179 of file output_buffer.c.

179 {
180 emit_set_truecolor_bg(ob, r, g, b);
181}
void emit_set_truecolor_bg(outbuf_t *out, uint8_t r, uint8_t g, uint8_t b)
Emit truecolor background ANSI sequence.

References emit_set_truecolor_bg().

◆ emit_set_fg()

void emit_set_fg ( outbuf_t * ob,
uint8_t r,
uint8_t g,
uint8_t b )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit foreground color sequence (auto-select mode).

Parameters
obOutput buffer structure (must not be NULL)
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)

Emits foreground color ANSI sequence using the optimal color mode based on terminal capabilities. Automatically selects:

  • Truecolor mode (if supported): 24-bit RGB
  • 256-color mode (if supported): Quantized to 256-color palette
  • 16-color mode (fallback): Quantized to standard ANSI colors
Note
Color mode is selected based on terminal_capabilities_t configuration.
This function uses the best available color mode for the terminal.
Color quantization is applied when truecolor is not available.

Definition at line 175 of file output_buffer.c.

175 {
176 emit_set_truecolor_fg(ob, r, g, b);
177}
void emit_set_truecolor_fg(outbuf_t *out, uint8_t r, uint8_t g, uint8_t b)
Emit truecolor foreground ANSI sequence.

References emit_set_truecolor_fg().

◆ emit_set_truecolor_bg()

void emit_set_truecolor_bg ( outbuf_t * ob,
uint8_t r,
uint8_t g,
uint8_t b )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit truecolor background ANSI sequence.

Parameters
obOutput buffer structure (must not be NULL)
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)

Emits ANSI escape sequence for 24-bit truecolor background color. Format: ESC[48;2;r;g;bm (where r, g, b are RGB values). Uses 24-bit RGB color values for optimal color accuracy.

Note
Requires terminal truecolor support for proper display.
Sequence length: ~15 bytes (ESC[48;2;255;255;255m).

Definition at line 124 of file output_buffer.c.

124 {
125 emit_truecolor(out, true, r, g, b);
126}

References out.

Referenced by emit_set_bg().

◆ emit_set_truecolor_fg()

void emit_set_truecolor_fg ( outbuf_t * ob,
uint8_t r,
uint8_t g,
uint8_t b )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Emit truecolor foreground ANSI sequence.

Parameters
obOutput buffer structure (must not be NULL)
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)

Emits ANSI escape sequence for 24-bit truecolor foreground color. Format: ESC[38;2;r;g;bm (where r, g, b are RGB values). Uses 24-bit RGB color values for optimal color accuracy.

Note
Requires terminal truecolor support for proper display.
Sequence length: ~15 bytes (ESC[38;2;255;255;255m).

Definition at line 120 of file output_buffer.c.

120 {
121 emit_truecolor(out, false, r, g, b);
122}

References out.

Referenced by emit_set_fg().

◆ get_256_color_fast_path()

bool get_256_color_fast_path ( void )

#include <include/ascii-chat/video/ascii/common.h>

Get 256-color fast path setting.

Returns
true if 256-color mode is enabled, false for truecolor

◆ get_lum_palette()

char * get_lum_palette ( void )

#include <include/ascii-chat/video/ascii/ascii.h>

Get luminance palette for character mapping.

Returns
Pointer to luminance palette array (256 elements, do not free)

Returns the default luminance-to-character mapping palette. The palette contains 256 characters ordered by luminance (dark to light) for mapping pixel brightness values (0-255) to ASCII characters.

Note
Returns pointer to static array (do not free).
Palette has 256 elements (one for each luminance level).
Palette is used for monochrome ASCII conversion.

◆ get_sgr256_bg_string()

char * get_sgr256_bg_string ( uint8_t bg,
uint8_t * len_out )

#include <include/ascii-chat/video/ascii/common.h>

Get 256-color background ANSI sequence string.

Parameters
bgBackground palette index (0-255)
len_outOutput parameter for sequence length
Returns
Pointer to ANSI sequence string (cached)

Definition at line 108 of file sgr.c.

108 {
109 if (!sgr256_cache_initialized) {
110 init_sgr256_cache();
111 }
112 *len_out = sgr256_bg_cache[bg].len;
113 return sgr256_bg_cache[bg].seq;
114}

◆ get_sgr256_fg_bg_string()

char * get_sgr256_fg_bg_string ( uint8_t fg,
uint8_t bg,
uint8_t * len_out )

#include <include/ascii-chat/video/ascii/common.h>

Get 256-color foreground/background ANSI sequence string.

Parameters
fgForeground palette index (0-255)
bgBackground palette index (0-255)
len_outOutput parameter for sequence length
Returns
Pointer to ANSI sequence string (cached)

Definition at line 116 of file sgr.c.

116 {
117 // For FG+BG, still build on-demand since we'd need 256*256 cache
118 static __thread char buf[VIDEO_ASCII_SGR_BUF_BUFFER_SIZE];
119 return build_sgr256_fgbg(buf, fg, bg, len_out);
120}
#define VIDEO_ASCII_SGR_BUF_BUFFER_SIZE
Definition sgr.c:7

◆ get_sgr256_fg_string()

char * get_sgr256_fg_string ( uint8_t fg,
uint8_t * len_out )

#include <include/ascii-chat/video/ascii/common.h>

Get 256-color foreground ANSI sequence string.

Parameters
fg256-color palette index (0-255)
len_outOutput parameter for sequence length
Returns
Pointer to ANSI sequence string (cached)

Definition at line 100 of file sgr.c.

100 {
101 if (!sgr256_cache_initialized) {
102 init_sgr256_cache();
103 }
104 *len_out = sgr256_fg_cache[fg].len;
105 return sgr256_fg_cache[fg].seq;
106}

◆ get_utf8_palette_cache()

utf8_palette_cache_t * get_utf8_palette_cache ( const char * ascii_chars)

#include <include/ascii-chat/video/ascii/common.h>

Get UTF-8 palette cache for a character set.

Definition at line 284 of file video/ascii/common.c.

284 {
285 if (!ascii_chars)
286 return NULL;
287
288 // Check for empty string
289 if (ascii_chars[0] == '\0')
290 return NULL;
291
292 // Create hash of palette for cache key
293 uint32_t palette_hash = hash_palette_string(ascii_chars);
294
295 // Ensure the cache system is initialized
296 if (!init_utf8_cache_system())
297 return NULL;
298
299 // First try: read lock for cache lookup (allows multiple concurrent readers)
300 rwlock_rdlock(&g_utf8_cache_rwlock);
301
302 // Check if cache exists
303 utf8_palette_cache_t *cache = NULL;
304 HASH_FIND_INT(g_utf8_cache_table, &palette_hash, cache);
305 if (cache) {
306 // Cache hit: Update access tracking (atomics are thread-safe under rdlock)
307 uint64_t current_time = time_get_ns();
308 atomic_store_u64(&cache->last_access_time, current_time);
309 uint32_t new_access_count = atomic_fetch_add_u64(&cache->access_count, 1) + 1;
310
311 // Every 10th access: Update heap position (requires write lock)
312 if (new_access_count % 10 == 0) {
313 // Save the key before releasing read lock
314 uint32_t saved_key = cache->key;
315
316 // Release read lock and upgrade to write lock
317 rwlock_rdunlock(&g_utf8_cache_rwlock);
318 rwlock_wrlock(&g_utf8_cache_rwlock);
319
320 // Re-lookup cache entry after lock upgrade
321 // Another thread could have evicted this entry while we were upgrading locks
322 utf8_palette_cache_t *cache_relookup = NULL;
323 HASH_FIND_INT(g_utf8_cache_table, &saved_key, cache_relookup);
324 if (cache_relookup) {
325 // Cache entry still exists - safe to update heap position
326 uint64_t last_access = atomic_load_u64(&cache_relookup->last_access_time);
327 uint32_t access_count = atomic_load_u64(&cache_relookup->access_count);
328 double new_score = calculate_cache_eviction_score(last_access, access_count, cache_relookup->creation_time, current_time);
329 utf8_heap_update_score(cache_relookup, new_score);
330 }
331 // If cache_relookup is NULL, entry was evicted - skip update (not an error)
332
333 rwlock_wrunlock(&g_utf8_cache_rwlock);
334 } else {
335 rwlock_rdunlock(&g_utf8_cache_rwlock);
336 }
337
338 return cache;
339 }
340
341 // Cache miss: Need to create new entry
342 // Release read lock and acquire write lock
343 rwlock_rdunlock(&g_utf8_cache_rwlock);
344 rwlock_wrlock(&g_utf8_cache_rwlock);
345
346 // Double-check: another thread might have created it while we upgraded locks
347 cache = NULL;
348 HASH_FIND_INT(g_utf8_cache_table, &palette_hash, cache);
349 if (cache) {
350 // Found it! Just update access tracking and return
351 uint64_t current_time = time_get_ns();
352 atomic_store_u64(&cache->last_access_time, current_time);
354 rwlock_wrunlock(&g_utf8_cache_rwlock);
355 return cache;
356 }
357
358 // Create new cache entry (holding write lock)
360 if (!cache) {
361 rwlock_wrunlock(&g_utf8_cache_rwlock);
362 return NULL;
363 }
364 memset(cache, 0, sizeof(utf8_palette_cache_t));
365
366 // Set the key for uthash
367 cache->key = palette_hash;
368
369 // Build both cache types
370 build_utf8_luminance_cache(ascii_chars, cache->cache);
371 build_utf8_ramp64_cache(ascii_chars, cache->cache64, cache->char_index_ramp);
372
373 // Store palette hash for validation
374 SAFE_STRNCPY(cache->palette_hash, ascii_chars, sizeof(cache->palette_hash));
375 cache->is_valid = true;
376
377 // Initialize eviction tracking
378 uint64_t current_time = time_get_ns();
379 atomic_store_u64(&cache->last_access_time, current_time);
380 atomic_store_u64(&cache->access_count, 1); // First access
381 cache->creation_time = current_time;
382
383 // Store in hash table with guaranteed eviction support
384 try_insert_with_eviction_utf8(palette_hash, cache);
385
386 // WASM: Skip debug log to avoid blocking render loop on main thread
387 // log_debug("UTF8_CACHE: Created new cache for palette='%s' (hash=0x%x)", ascii_chars, palette_hash);
388
389 rwlock_wrunlock(&g_utf8_cache_rwlock);
390 return cache;
391}
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_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
#define SAFE_STRNCPY(dst, src, size)
void build_utf8_luminance_cache(const char *ascii_chars, utf8_char_t cache[256])
Build UTF-8 luminance cache for all 256 levels.
struct utf8_palette_cache utf8_palette_cache_t
double calculate_cache_eviction_score(uint64_t last_access_time, uint32_t access_count, uint64_t creation_time, uint64_t current_time)
void build_utf8_ramp64_cache(const char *ascii_chars, utf8_char_t cache64[64], uint8_t char_index_ramp[ASCII_LUMINANCE_LEVELS])

References utf8_palette_cache::access_count, atomic_fetch_add_u64(), atomic_load_u64(), atomic_store_u64(), build_utf8_luminance_cache(), build_utf8_ramp64_cache(), utf8_palette_cache::cache, utf8_palette_cache::cache64, calculate_cache_eviction_score(), utf8_palette_cache::char_index_ramp, utf8_palette_cache::creation_time, utf8_palette_cache::is_valid, utf8_palette_cache::key, utf8_palette_cache::last_access_time, utf8_palette_cache::palette_hash, SAFE_MALLOC, and SAFE_STRNCPY.

Referenced by ascii_frame_init(), ascii_legacy_frame_init(), and session_display_create().

◆ image_clear()

void image_clear ( image_t * p)

#include <include/ascii-chat/video/rgba/image.h>

Clear image (set all pixels to black).

Parameters
pImage to clear (must not be NULL)

Sets all pixels in the image to black (RGB = 0, 0, 0). Useful for resetting image state before filling with new data.

Note
Image dimensions are not modified (only pixel data is cleared).
This is equivalent to memset() of pixels array to zero.

Definition at line 61 of file video/rgba/image.c.

61 {
62 if (!p || !p->pixels) {
63 SET_ERRNO(ERROR_INVALID_PARAM, "p or p->pixels is NULL");
64 return;
65 }
66 // Check for integer overflow before multiplication.
67 unsigned long w_ul = (unsigned long)p->w;
68 unsigned long h_ul = (unsigned long)p->h;
69 if (w_ul > 0 && h_ul > ULONG_MAX / w_ul) {
70 SET_ERRNO(ERROR_INVALID_PARAM, "dimensions overflow: %d x %d", p->w, p->h);
71 return;
72 }
73 unsigned long pixel_count = w_ul * h_ul;
74 if (pixel_count > ULONG_MAX / sizeof(rgb_pixel_t)) {
75 SET_ERRNO(ERROR_INVALID_PARAM, "buffer size overflow");
76 return;
77 }
78 size_t clear_size = pixel_count * sizeof(rgb_pixel_t);
79 SAFE_MEMSET(p->pixels, clear_size, 0, clear_size);
80}

References ERROR_INVALID_PARAM, image::h, image::pixels, SAFE_MEMSET, SET_ERRNO, and image::w.

Referenced by ascii_convert(), and ascii_convert_with_buffers_stabilized().

◆ image_destroy()

void image_destroy ( image_t * p)

#include <include/ascii-chat/video/rgba/image.h>

Destroy an image allocated with image_new().

Parameters
pImage to destroy (can be NULL, no-op if NULL)

Frees an image structure and its associated pixel data array allocated by image_new(). Frees both the image structure and the pixels array.

Note
Safe to call with NULL pointer (no-op).
Must NOT be used for images allocated with image_new().
Use image_destroy() for pool-allocated images.

Definition at line 57 of file video/rgba/image.c.

57 {
59}
#define buffer_release(data)
Definition buffer.h:99

References buffer_release.

Referenced by ascii_convert(), ascii_convert_with_buffers_stabilized(), create_mixed_ascii_frame_for_client(), face_follow_image_destroy(), face_follow_image_process(), ffmpeg_decoder_destroy(), http_renderer_render_file(), session_capture_destroy(), session_capture_process_for_transmission_into(), session_display_destroy(), session_host_add_client(), session_host_add_memory_participant(), session_host_destroy(), session_host_inject_frame(), session_host_receive_packet(), session_host_remove_client(), test_pattern_destroy(), and test_pattern_resize().

◆ image_new()

image_t * image_new ( size_t width,
size_t height )

#include <include/ascii-chat/video/rgba/image.h>

Create a new image with standard allocation.

Parameters
widthImage width in pixels (must be > 0 and <= IMAGE_MAX_WIDTH)
heightImage height in pixels (must be > 0 and <= IMAGE_MAX_HEIGHT)
Returns
Allocated image structure, or NULL on error

Allocates a new image structure and pixel data array using standard malloc() allocation. Image is initialized with specified dimensions and all pixels set to black (0, 0, 0).

Note
Caller must free with image_destroy() when done.
Returns NULL on error (invalid dimensions, memory allocation failure).
Pixel data is allocated separately and freed automatically on destroy.
Example
image_t *img = image_new(1920, 1080);
if (img) {
// Use image...
}
struct image image_t
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...

Definition at line 38 of file video/rgba/image.c.

38 {
40 return NULL;
41 size_t pixels_size;
42 if (checked_size_mul3(width, height, sizeof(rgb_pixel_t), &pixels_size) != ASCIICHAT_OK || pixels_size > IMAGE_MAX_PIXELS_SIZE)
43 return NULL;
44 const size_t offset = (sizeof(image_t) + BUFFER_DEFAULT_ALIGNMENT - 1) & ~(size_t)(BUFFER_DEFAULT_ALIGNMENT - 1);
45 size_t total;
46 if (checked_size_add(offset, pixels_size, &total) != ASCIICHAT_OK)
47 return NULL;
48 image_t *image = buffer_alloc(NULL, total);
49 if (!image)
50 return NULL;
51 image->w = (int)width;
52 image->h = (int)height;
53 image->pixels = (rgb_pixel_t *)((uint8_t *)image + offset);
54 return image;
55}
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
#define BUFFER_DEFAULT_ALIGNMENT
Definition buffer.h:30
#define IMAGE_MAX_PIXELS_SIZE
Maximum pixel data size in bytes.
asciichat_error_t image_validate_dimensions(size_t width, size_t height)
Validate image dimensions (non-zero, within limits).
Definition util/image.c:97

References ASCIICHAT_OK, buffer_alloc(), BUFFER_DEFAULT_ALIGNMENT, image::h, height, IMAGE_MAX_PIXELS_SIZE, image_validate_dimensions(), image::pixels, image::w, and width.

Referenced by ascii_convert(), ascii_convert_with_buffers_stabilized(), face_follow_image_process(), ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), image_new_copy(), session_capture_process_for_transmission_into(), session_host_add_client(), session_host_add_memory_participant(), session_host_inject_frame(), session_host_receive_packet(), and test_pattern_resize().

◆ image_new_copy()

image_t * image_new_copy ( const image_t * source)

#include <include/ascii-chat/video/rgba/image.h>

Create a copy of an existing image.

Parameters
sourceSource image to copy (must not be NULL)
Returns
Newly allocated copy of the image, or NULL on error

Creates a deep copy of an image, allocating new memory for the copy. The source and destination images are completely independent - modifying one does not affect the other. Useful for creating snapshots to prevent concurrent modification issues.

Note
Returns NULL on error (invalid image, memory allocation failure).
Caller must free the returned image with image_destroy().
Copy is allocated with standard malloc() allocation.
Pixels are fully copied (not shared with source).

Definition at line 82 of file video/rgba/image.c.

82 {
83 if (!source) {
84 SET_ERRNO(ERROR_INVALID_PARAM, "source is NULL");
85 return NULL;
86 }
87
88 // Create new image with same dimensions
89 image_t *copy = image_new((size_t)source->w, (size_t)source->h);
90 if (!copy) {
91 return NULL;
92 }
93
94 // Copy pixel data from source to copy
95 if (source->pixels && copy->pixels) {
96 size_t pixel_count = (size_t)source->w * (size_t)source->h;
97 size_t pixels_size = pixel_count * sizeof(rgb_pixel_t);
98 memcpy(copy->pixels, source->pixels, pixels_size);
99 }
100
101 return copy;
102}
audio_visualization_source_t source
Definition fft.c:25

References ERROR_INVALID_PARAM, image_new(), image::pixels, SET_ERRNO, and source.

Referenced by create_mixed_ascii_frame_for_client().

◆ image_print()

char * image_print ( const image_t * p,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image as ASCII art (monochrome).

Parameters
pImage to print (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string (caller must free), or NULL on error

Converts an image to ASCII art without color output. Uses character palette to map pixel luminance to ASCII characters. Returns a null-terminated string containing the ASCII art frame.

Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Character palette is used to map luminance to characters.
ASCII output has width*height characters (one character per pixel).

Definition at line 12 of file foreground.c.

12 {
13 return ascii_render(image, palette, ASCII_COLOR_NONE, false, false, simd_cells_backend());
14}

References ASCII_COLOR_NONE, ascii_render, and simd_cells_backend().

Referenced by ascii_convert(), and image_print_with_capabilities().

◆ image_print_16color()

char * image_print_16color ( const image_t * image,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image using 16-color ANSI mode.

Parameters
imageImage to print (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string with 16-color ANSI codes (caller must free), or NULL on error

Converts an image to ASCII art using 16-color ANSI mode. Uses standard ANSI color palette (0-15) for color output. Colors are quantized to 16-color palette.

Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Requires terminal 16-color support for proper display.
Colors are quantized to 16-color palette automatically.

Definition at line 28 of file foreground.c.

28 {
29 return ascii_render(image, palette, ASCII_COLOR_16, false, false, simd_cells_backend());
30}

References ASCII_COLOR_16, ascii_render, and simd_cells_backend().

◆ image_print_16color_dithered()

char * image_print_16color_dithered ( const image_t * image,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image using 16-color ANSI mode with dithering.

Parameters
imageImage to print (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string with dithered 16-color ANSI codes (caller must free), or NULL on error

Converts an image to ASCII art using 16-color ANSI mode with Floyd-Steinberg dithering. Dithering improves color accuracy by distributing quantization errors across neighboring pixels.

DITHERING:

  • Floyd-Steinberg error diffusion algorithm
  • Distributes quantization errors to adjacent pixels
  • Improves perceived color accuracy in 16-color mode
  • Slight performance overhead compared to non-dithered mode
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Dithering improves color accuracy but may add noise.
Requires terminal 16-color support for proper display.

Definition at line 32 of file foreground.c.

32 {
33 return ascii_render(image, palette, ASCII_COLOR_16, false, true, simd_cells_backend());
34}

References ASCII_COLOR_16, ascii_render, and simd_cells_backend().

◆ image_print_16color_dithered_with_background()

char * image_print_16color_dithered_with_background ( const image_t * image,
bool use_background,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image using 16-color ANSI mode with dithering and background colors.

Parameters
imageImage to print (must not be NULL)
use_backgroundWhether to use background colors (true) or foreground colors only (false)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string with dithered 16-color ANSI codes (caller must free), or NULL on error

Converts an image to ASCII art using 16-color ANSI mode with Floyd-Steinberg dithering and optional background color support. Background colors provide better color coverage for block-style rendering.

RENDERING MODES:

  • Foreground colors: Character color is set (text color)
  • Background colors: Character background is set (block color)
  • Background mode provides better color coverage for block characters
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Background colors require terminal background color support.
Dithering improves color accuracy but may add noise.

Definition at line 36 of file foreground.c.

36 {
37 return ascii_render(image, palette, ASCII_COLOR_16, background, true, simd_cells_backend());
38}

References ASCII_COLOR_16, ascii_render, and simd_cells_backend().

◆ image_print_256color()

char * image_print_256color ( const image_t * image,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image using 256-color ANSI mode.

Parameters
imageImage to print (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string with 256-color ANSI codes (caller must free), or NULL on error

Converts an image to ASCII art using 256-color ANSI mode. Uses extended ANSI color palette (0-255) for color output. Colors are quantized to 256-color palette.

Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Requires terminal 256-color support for proper display.
Colors are quantized to 256-color palette automatically.

Definition at line 24 of file foreground.c.

24 {
25 return ascii_render(image, palette, ASCII_COLOR_256, false, false, simd_cells_backend());
26}

References ASCII_COLOR_256, ascii_render, and simd_cells_backend().

◆ image_print_color()

char * image_print_color ( const image_t * p,
const char * palette )

#include <include/ascii-chat/video/rgba/image.h>

Print image as ASCII art with color.

Parameters
pImage to print (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
Returns
Allocated ASCII string with ANSI color codes (caller must free), or NULL on error

Converts an image to ASCII art with color output. Uses character palette for character mapping and ANSI color codes for color output. Returns a null-terminated string containing the ASCII art frame with embedded ANSI escape sequences.

Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
ANSI color codes are embedded in the output string.
Color output requires terminal color support for proper display.

Definition at line 16 of file foreground.c.

16 {
17 return ascii_render(image, palette, ASCII_COLOR_TRUE, false, false, simd_cells_backend());
18}

References ASCII_COLOR_TRUE, ascii_render, and simd_cells_backend().

◆ image_print_color_simd()

char * image_print_color_simd ( image_t * image,
bool use_background_mode,
bool use_256color,
const char * ascii_chars )

#include <include/ascii-chat/video/ascii/common.h>

Print image as ASCII with color using SIMD.

Parameters
imageSource image
use_background_modeUse background colors
use_256colorUse 256-color mode (vs truecolor)
ascii_charsCharacter palette
Returns
Allocated ASCII string with ANSI codes (caller must free), or NULL on error

Definition at line 159 of file sgr.c.

159 {
160 return ascii_render(image, palette, indexed ? ASCII_COLOR_256 : ASCII_COLOR_TRUE, background, false, simd_cells_backend());
161}

References ASCII_COLOR_256, ASCII_COLOR_TRUE, ascii_render, and simd_cells_backend().

Referenced by ascii_convert(), and image_print_with_capabilities().

◆ image_print_with_capabilities()

char * image_print_with_capabilities ( const image_t * image,
const terminal_capabilities_t * caps,
const char * palette )

#include <include/ascii-chat/video/ascii/ascii.h>

Convert image to ASCII art with terminal capabilities.

Print image with terminal capability awareness.

Parameters
imageImage to convert (must not be NULL)
capsTerminal capabilities structure
palettePalette characters to use for conversion
Returns
ASCII art string, or NULL on error

Converts an image to ASCII art using the provided terminal capabilities. Automatically selects the best rendering method based on terminal capabilities.

Note
Returns dynamically allocated string that must be freed by caller.
Parameters
imageImage to print (must not be NULL)
capsTerminal capabilities structure (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
luminance_paletteLuminance-to-character mapping palette (must not be NULL, 256 elements)
Returns
Allocated ASCII string (caller must free), or NULL on error

Converts an image to ASCII art with automatic color mode selection based on terminal capabilities. Automatically chooses the best color mode (16-color, 256-color, or truecolor) for the terminal.

COLOR MODE SELECTION:

  • Truecolor: If terminal supports 24-bit RGB colors
  • 256-color: If terminal supports extended ANSI palette
  • 16-color: Fallback to standard ANSI colors
  • Monochrome: If terminal has no color support
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Color mode is selected automatically based on terminal capabilities.
This is the recommended function for capability-aware ASCII conversion.

Print image with terminal capability awareness.

Parameters
imageImage to convert (must not be NULL)
capsTerminal capabilities structure
palettePalette characters to use for conversion
Returns
ASCII art string, or NULL on error

Converts an image to ASCII art using the provided terminal capabilities. Automatically selects the best rendering method based on terminal capabilities.

Note
Returns dynamically allocated string that must be freed by caller.
Parameters
imageImage to print (must not be NULL)
capsTerminal capabilities structure (must not be NULL)
paletteCharacter palette to use (or NULL for default ASCII palette)
luminance_paletteLuminance-to-character mapping palette (must not be NULL, 256 elements)
Returns
Allocated ASCII string (caller must free), or NULL on error

Converts an image to ASCII art with automatic color mode selection based on terminal capabilities. Automatically chooses the best color mode (16-color, 256-color, or truecolor) for the terminal.

COLOR MODE SELECTION:

  • Truecolor: If terminal supports 24-bit RGB colors
  • 256-color: If terminal supports extended ANSI palette
  • 16-color: Fallback to standard ANSI colors
  • Monochrome: If terminal has no color support
Note
Returns NULL on error (invalid image, memory allocation failure).
ASCII string must be freed by caller using free().
Color mode is selected automatically based on terminal capabilities.
This is the recommended function for capability-aware ASCII conversion.

Definition at line 884 of file ascii.c.

884 {
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}

References ASCII_COLOR_16, ASCII_COLOR_256, ASCII_COLOR_NONE, ASCII_COLOR_TRUE, ascii_render, ascii_render_halfblocks, image::h, image_print(), image_print_color_simd(), image::pixels, render_mode, simd_cells_backend(), and image::w.

Referenced by ascii_convert_with_buffers_stabilized().

◆ image_resize()

void image_resize ( const image_t * source,
image_t * dest )

#include <include/ascii-chat/video/rgba/image.h>

Resize image using nearest-neighbor interpolation.

Parameters
sourceSource image (must not be NULL)
destDestination image (must be allocated and have valid dimensions)

Resizes an image using nearest-neighbor interpolation. Fast but may produce aliasing artifacts. Source pixels are sampled to nearest destination pixel positions.

NEAREST-NEIGHBOR INTERPOLATION:

  • Fast algorithm (no interpolation calculations)
  • May produce aliasing artifacts
  • Pixel values are copied directly (no averaging)
  • Suitable for integer scaling (2x, 3x, etc.)
Note
Destination image dimensions must be set before calling.
Source and destination images must be valid (not NULL).
Fast algorithm suitable for real-time resizing.

Definition at line 112 of file video/rgba/image.c.

112 {
113 if (!s || !d) {
114 SET_ERRNO(ERROR_INVALID_PARAM, "s or d is NULL");
115 return;
116 }
117
119}
void image_resize_interpolation(const image_t *source, image_t *dest)
Resize image using bilinear interpolation.

References ERROR_INVALID_PARAM, image_resize_interpolation(), and SET_ERRNO.

Referenced by ascii_convert(), ascii_convert_with_buffers_stabilized(), and session_capture_process_for_transmission_into().

◆ image_resize_interpolation()

void image_resize_interpolation ( const image_t * source,
image_t * dest )

#include <include/ascii-chat/video/rgba/image.h>

Resize image using bilinear interpolation.

Parameters
sourceSource image (must not be NULL)
destDestination image (must be allocated and have valid dimensions)

Resizes an image using bilinear interpolation. Produces smoother results than nearest-neighbor but slower. Pixel values are interpolated from four nearest source pixels.

BILINEAR INTERPOLATION:

  • Slower algorithm (interpolation calculations required)
  • Produces smoother results (reduced aliasing)
  • Pixel values are interpolated from 4 nearest neighbors
  • Suitable for fractional scaling (1.5x, 2.3x, etc.)
Note
Destination image dimensions must be set before calling.
Source and destination images must be valid (not NULL).
Slower algorithm but produces better quality.

Definition at line 123 of file video/rgba/image.c.

123 {
124 if (!source || !dest || !source->pixels || !dest->pixels) {
125 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
126 return;
127 }
128
129 const int src_w = source->w;
130 const int src_h = source->h;
131 const int dst_w = dest->w;
132 const int dst_h = dest->h;
133
134 // Handle edge cases
135 if (src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0) {
136 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid image dimensions for resize: src=%dx%d dst=%dx%d", src_w, src_h, dst_w, dst_h);
137 return;
138 }
139
140 // Defensive checks to prevent invalid shift (UBSan protection)
141 if (src_w < 1 || src_h < 1 || dst_w < 1 || dst_h < 1) {
142 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid dimensions detected after first check");
143 return;
144 }
145
146 // Use fixed-point arithmetic for better performance
147 // Use uint64_t intermediate to prevent overflow when shifting large dimensions
148 const uint32_t x_ratio = (uint32_t)((((uint64_t)src_w << 16) / (uint64_t)dst_w) + 1);
149 const uint32_t y_ratio = (uint32_t)((((uint64_t)src_h << 16) / (uint64_t)dst_h) + 1);
150
151 const rgb_pixel_t *src_pixels = source->pixels;
152 rgb_pixel_t *dst_pixels = dest->pixels;
153
154 for (int y = 0; y < dst_h; y++) {
155 const uint32_t src_y = ((uint32_t)(unsigned int)y * y_ratio) >> 16;
156 // Explicitly clamp to valid range [0, src_h-1]
157 const uint32_t safe_src_y = src_y >= (uint32_t)(unsigned int)src_h ? (uint32_t)(src_h - 1) : src_y;
158
159 // Bounds check: ensure safe_src_y is valid
160 if (safe_src_y >= (uint32_t)(unsigned int)src_h) {
161 SET_ERRNO(ERROR_INVALID_PARAM, "safe_src_y out of bounds: %u >= %d", safe_src_y, src_h);
162 return;
163 }
164
165 const rgb_pixel_t *src_row = src_pixels + (safe_src_y * (size_t)src_w);
166
167 rgb_pixel_t *dst_row = dst_pixels + ((size_t)y * (size_t)dst_w);
168
169 for (int x = 0; x < dst_w; x++) {
170 const uint32_t src_x = ((uint32_t)(unsigned int)x * x_ratio) >> 16;
171 // Explicitly clamp to valid range [0, src_w-1]
172 const uint32_t safe_src_x = src_x >= (uint32_t)(unsigned int)src_w ? (uint32_t)(src_w - 1) : src_x;
173
174 // Bounds check: ensure safe_src_x is valid
175 if (safe_src_x >= (uint32_t)(unsigned int)src_w) {
176 SET_ERRNO(ERROR_INVALID_PARAM, "safe_src_x out of bounds: %u >= %d", safe_src_x, src_w);
177 return;
178 }
179
180 dst_row[x] = src_row[safe_src_x];
181 }
182 }
183}

References ERROR_INVALID_PARAM, image::h, image::pixels, SET_ERRNO, source, and image::w.

Referenced by image_resize().

◆ init_dec3()

void init_dec3 ( void )

#include <include/ascii-chat/video/ascii/common.h>

Initialize decimal lookup table.

Must be called before using any SIMD conversion functions.

Initialize decimal lookup table.

Pre-builds a cache of ASCII representations for all byte values. Used by color code generation to avoid repeated int-to-string conversions.

Definition at line 563 of file video/ascii/common.c.

563 {
564 if (g_dec3_cache.dec3_initialized)
565 return;
566 for (int v = 0; v < 256; ++v) {
567 int d2 = v / 100; // 0..2
568 int r = v - d2 * 100; // 0..99
569 int d1 = r / 10; // 0..9
570 int d0 = r - d1 * 10; // 0..9
571
572 if (d2) {
573 g_dec3_cache.dec3_table[v].len = 3;
574 g_dec3_cache.dec3_table[v].s[0] = '0' + d2;
575 g_dec3_cache.dec3_table[v].s[1] = '0' + d1;
576 g_dec3_cache.dec3_table[v].s[2] = '0' + d0;
577 } else if (d1) {
578 g_dec3_cache.dec3_table[v].len = 2;
579 g_dec3_cache.dec3_table[v].s[0] = '0' + d1;
580 g_dec3_cache.dec3_table[v].s[1] = '0' + d0;
581 } else {
582 g_dec3_cache.dec3_table[v].len = 1;
583 g_dec3_cache.dec3_table[v].s[0] = '0' + d0;
584 }
585 }
586 g_dec3_cache.dec3_initialized = true;
587}
global_dec3_cache_t g_dec3_cache
Global decimal cache instance.

References g_dec3_cache.

Referenced by ascii_simd_init().

◆ init_default_luminance_palette()

void init_default_luminance_palette ( void )

#include <include/ascii-chat/video/ascii/common.h>

Initialize default luminance palette.

Definition at line 606 of file video/ascii/common.c.

606 {
607 if (!lifecycle_init(&g_default_palette_lc, "default_palette")) {
608 return; // Already initialized
609 }
610 do_init_default_luminance_palette();
611}

Referenced by ascii_simd_init().

◆ ob_putc()

void ob_putc ( outbuf_t * ob,
char c )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Append a character to buffer.

Parameters
obOutput buffer structure (must not be NULL)
cCharacter to append

Appends a single character to the output buffer. Automatically expands the buffer if necessary. Buffer remains null-terminated after append.

Note
Buffer is automatically expanded if needed.
Length is incremented by 1 after append.
Null terminator is updated automatically.

Definition at line 47 of file output_buffer.c.

47 {
48 if (!ob)
49 return;
50 ob_reserve(ob, 1);
51 ob->buf[ob->len++] = c;
52}
size_t len
Current length in bytes (excluding null terminator).

References outbuf_t::buf, outbuf_t::len, and ob_reserve().

Referenced by ansi_compress_rle(), emit_rep(), emit_row_end(), and ob_u8().

◆ ob_reserve()

void ob_reserve ( outbuf_t * ob,
size_t need )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Dynamic output buffer (auto-expanding).

Reserve buffer space for upcoming writes

Parameters
obOutput buffer structure (must not be NULL)
needMinimum bytes needed (zero initializes an unallocated buffer)

Ensures the buffer has at least 'need' bytes of available space. Automatically expands the buffer if necessary. Buffer grows exponentially (doubles in size) to minimize reallocation overhead.

Note
Buffer is automatically allocated on first reservation.
Buffer doubles in size when capacity is exceeded.
This function does not modify buffer length (only capacity).

Definition at line 26 of file output_buffer.c.

26 {
27 if (!ob)
28 return;
29 if (need > SIZE_MAX - ob->len)
30 FATAL(ERROR_MEMORY, "Output buffer size overflow");
31 size_t required = ob->len + need;
32 if (ob->cap && required <= ob->cap)
33 return;
34 size_t capacity = ob->cap ? ob->cap : 4096;
35 while (capacity < required) {
36 size_t increment = capacity / 2 + 1;
37 if (capacity > SIZE_MAX - increment) {
38 capacity = required;
39 break;
40 }
41 capacity += increment;
42 }
43 ob->buf = SAFE_REALLOC(ob->buf, capacity, char *);
44 ob->cap = capacity;
45}
#define SAFE_REALLOC(ptr, size, cast)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
size_t cap
Buffer capacity in bytes (maximum length before reallocation).

References outbuf_t::buf, outbuf_t::cap, ERROR_MEMORY, FATAL, outbuf_t::len, and SAFE_REALLOC.

Referenced by ansi_compress_rle(), ansi_expand_rle(), emit_reset(), ob_putc(), ob_term(), ob_u32(), and ob_write().

◆ ob_term()

void ob_term ( outbuf_t * ob)

#include <include/ascii-chat/video/ascii/output_buffer.h>

Append null terminator to buffer.

Parameters
obOutput buffer structure (must not be NULL)

Ensures the buffer is null-terminated by appending a null character. Does not increment length counter (null terminator is not counted). Useful for ensuring buffer is a valid C string.

Note
This function ensures buffer[len] == '\0'.
Length counter is not modified (null terminator excluded from length).

Definition at line 62 of file output_buffer.c.

62 {
63 if (!ob)
64 return;
65 // Reserve space for null terminator if needed
66 if (ob->len >= ob->cap) {
67 ob_reserve(ob, 1);
68 }
69 // Append null terminator WITHOUT incrementing length
70 // (null terminator is not part of the string length)
71 ob->buf[ob->len] = '\0';
72}

References outbuf_t::buf, outbuf_t::cap, outbuf_t::len, and ob_reserve().

Referenced by ansi_compress_rle(), ansi_expand_rle(), ascii_frame_finish(), and ascii_legacy_frame_finish().

◆ ob_u32()

void ob_u32 ( outbuf_t * ob,
uint32_t v )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Append unsigned 32-bit integer as decimal string.

Parameters
obOutput buffer structure (must not be NULL)
vValue to append (0 to 4294967295)

Converts an unsigned 32-bit integer to decimal string representation and appends it to the buffer. Useful for formatting numeric values (dimensions, counts, timestamps, etc.).

Note
Buffer is automatically expanded if needed.
String representation is appended (1-10 characters for 0-4294967295).

Definition at line 96 of file output_buffer.c.

96 {
97 if (!ob)
98 return;
100 int i = 0;
101 do {
102 tmp[i++] = '0' + (v % 10u);
103 v /= 10u;
104 } while (v);
105 ob_reserve(ob, (size_t)i);
106 while (i--)
107 ob->buf[ob->len++] = tmp[i];
108}
#define VIDEO_ASCII_OUTPUT_BUFFER_TMP_BUFFER_SIZE

References outbuf_t::buf, outbuf_t::len, ob_reserve(), and VIDEO_ASCII_OUTPUT_BUFFER_TMP_BUFFER_SIZE.

Referenced by emit_rep().

◆ ob_u8()

void ob_u8 ( outbuf_t * ob,
uint8_t v )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Append unsigned 8-bit integer as decimal string.

Parameters
obOutput buffer structure (must not be NULL)
vValue to append (0-255)

Converts an unsigned 8-bit integer to decimal string representation and appends it to the buffer. Useful for formatting small numeric values (color indices, counts, etc.).

Note
Buffer is automatically expanded if needed.
String representation is appended (1-3 characters for 0-255).

Definition at line 75 of file output_buffer.c.

75 {
76 if (!ob)
77 return;
78 if (v >= 100) {
79 uint8_t d0 = v / 100;
80 uint8_t r = v % 100;
81 uint8_t d1 = r / 10;
82 uint8_t d2 = r % 10;
83 ob_putc(ob, '0' + d0);
84 ob_putc(ob, '0' + d1);
85 ob_putc(ob, '0' + d2);
86 } else if (v >= 10) {
87 uint8_t d1 = v / 10;
88 uint8_t d2 = v % 10;
89 ob_putc(ob, '0' + d1);
90 ob_putc(ob, '0' + d2);
91 } else {
92 ob_putc(ob, '0' + v);
93 }
94}

References ob_putc().

◆ ob_write()

void ob_write ( outbuf_t * ob,
const void * s,
size_t n )

#include <include/ascii-chat/video/ascii/output_buffer.h>

Append a string to buffer.

Parameters
obOutput buffer structure (must not be NULL)
sString to append (must not be NULL)
nNumber of bytes to append (must be > 0)

Appends n bytes from string s to the output buffer. Automatically expands the buffer if necessary. Buffer remains null-terminated after append.

Note
Buffer is automatically expanded if needed.
Length is incremented by n after append.
Null terminator is updated automatically.
This function copies n bytes (may include embedded nulls).

Definition at line 54 of file output_buffer.c.

54 {
55 if (!ob || n == 0)
56 return;
57 ob_reserve(ob, n);
58 SAFE_MEMCPY(ob->buf + ob->len, ob->cap - ob->len, s, n);
59 ob->len += n;
60}

References outbuf_t::buf, outbuf_t::cap, outbuf_t::len, ob_reserve(), and SAFE_MEMCPY.

Referenced by ansi_compress_rle(), ansi_expand_rle(), emit_glyph_run(), emit_set_256_color_bg(), and emit_set_256_color_fg().

◆ precalc_rgb_palettes()

void precalc_rgb_palettes ( const float red,
const float green,
const float blue )

#include <include/ascii-chat/video/rgba/image.h>

Precalculate RGB palettes with color adjustment.

Parameters
redRed adjustment factor (1.0 = no adjustment, >1.0 = increase, <1.0 = decrease)
greenGreen adjustment factor (1.0 = no adjustment, >1.0 = increase, <1.0 = decrease)
blueBlue adjustment factor (1.0 = no adjustment, >1.0 = increase, <1.0 = decrease)

Precalculates RGB color palettes with color adjustment factors. Color adjustment allows brightness, contrast, and color balance adjustments to be applied efficiently during ASCII conversion.

COLOR ADJUSTMENT:

  • Adjustment factors are multiplied with color components
  • Factors > 1.0 increase color intensity
  • Factors < 1.0 decrease color intensity
  • Precalculated palettes improve conversion performance
Note
Precalculated palettes are cached for efficient conversion.
Color adjustment is applied during ASCII conversion.
Useful for brightness/contrast control.

Definition at line 187 of file video/rgba/image.c.

187 {
188 // Validate input parameters to prevent overflow
189 // Luminance weights should typically be in range 0.0-1.0
190 // But allow slightly larger values for brightness adjustment
191 const float max_weight = 255.0f; // Maximum value that won't overflow when multiplied by 255
192 const float min_weight = -255.0f; // Allow negative for color correction
193
194 // Note: isfinite() checks are skipped in Release builds due to -ffinite-math-only flag
195 // which disables NaN/infinity support for performance. Range checks below are sufficient.
196#if !defined(NDEBUG) && !defined(__FAST_MATH__)
197 if (!isfinite(red) || !isfinite(green) || !isfinite(blue)) {
198 log_error("Invalid weight values (non-finite): red=%f, green=%f, blue=%f", red, green, blue);
199 SET_ERRNO(ERROR_INVALID_PARAM, "non-finite weight values");
200 return;
201 }
202#endif
203
204 if (red < min_weight || red > max_weight || green < min_weight || green > max_weight || blue < min_weight || blue > max_weight) {
205 log_warn("Weight values out of expected range: red=%f, green=%f, blue=%f (clamping to safe range)", red, green, blue);
206 }
207
208 // A corrupted startup value must not turn into a black/invalid palette.
209 // Restore the canonical luminance weights instead of clamping it to +/-255.
210 const bool invalid_weight = red < min_weight || red > max_weight || green < min_weight || green > max_weight || blue < min_weight || blue > max_weight;
211 const float effective_red = invalid_weight ? 0.2989f : red;
212 const float effective_green = invalid_weight ? 0.5866f : green;
213 const float effective_blue = invalid_weight ? 0.1145f : blue;
214
215 // Clamp weights to safe range to prevent overflow
216 const float safe_red = (effective_red < min_weight) ? min_weight : ((effective_red > max_weight) ? max_weight : effective_red);
217 const float safe_green = (effective_green < min_weight) ? min_weight : ((effective_green > max_weight) ? max_weight : effective_green);
218 const float safe_blue = (effective_blue < min_weight) ? min_weight : ((effective_blue > max_weight) ? max_weight : effective_blue);
219
220 const unsigned short max_ushort = 65535;
221 const unsigned short min_ushort = 0;
222
223 for (int n = 0; n < ASCII_LUMINANCE_LEVELS; ++n) {
224 // Compute with float, then clamp to unsigned short range
225 float red_val = (float)n * safe_red;
226 float green_val = (float)n * safe_green;
227 float blue_val = (float)n * safe_blue;
228
229 // Clamp to unsigned short range before assignment
230 if (red_val < (float)min_ushort) {
231 red_val = (float)min_ushort;
232 } else if (red_val > (float)max_ushort) {
233 red_val = (float)max_ushort;
234 }
235
236 if (green_val < (float)min_ushort) {
237 green_val = (float)min_ushort;
238 } else if (green_val > (float)max_ushort) {
239 green_val = (float)max_ushort;
240 }
241
242 if (blue_val < (float)min_ushort) {
243 blue_val = (float)min_ushort;
244 } else if (blue_val > (float)max_ushort) {
245 blue_val = (float)max_ushort;
246 }
247
248 RED[n] = (unsigned short)red_val;
249 GREEN[n] = (unsigned short)green_val;
250 BLUE[n] = (unsigned short)blue_val;
251 GRAY[n] = (unsigned short)n;
252 }
253}
unsigned short int GRAY[256]
Grayscale lookup table.
unsigned short int BLUE[256]
Blue channel lookup table.
unsigned short int GREEN[256]
Green channel lookup table.
unsigned short int RED[256]
Red channel lookup table.
#define ASCII_LUMINANCE_LEVELS
Number of luminance levels supported (256).
Definition ascii.h:438

References ASCII_LUMINANCE_LEVELS, BLUE, ERROR_INVALID_PARAM, GRAY, GREEN, log_error, log_warn, RED, and SET_ERRNO.

Referenced by server_main().

◆ prewarm_sgr256_cache()

void prewarm_sgr256_cache ( void )

#include <include/ascii-chat/video/ascii/common.h>

Prewarm 256-color foreground/background cache for benchmarks.

Prevents first-frame performance penalty in benchmarks.

Definition at line 95 of file sgr.c.

95 {
96 init_sgr256_cache();
97}

◆ prewarm_sgr256_fg_cache()

void prewarm_sgr256_fg_cache ( void )

#include <include/ascii-chat/video/ascii/common.h>

Prewarm 256-color foreground cache for benchmarks.

Prevents first-frame performance penalty in benchmarks.

Definition at line 91 of file sgr.c.

91 {
92 init_sgr256_cache();
93}

◆ print_simd_capabilities()

void print_simd_capabilities ( void )

#include <include/ascii-chat/video/ascii/common.h>

Print detected SIMD capabilities.

Prints available SIMD instruction sets to stdout.

◆ quantize_color()

void quantize_color ( int * r,
int * g,
int * b,
int levels )

#include <include/ascii-chat/video/rgba/image.h>

Quantize color to specified number of levels.

Parameters
rRed component (input/output, must not be NULL, range 0-255)
gGreen component (input/output, must not be NULL, range 0-255)
bBlue component (input/output, must not be NULL, range 0-255)
levelsNumber of quantization levels (must be > 0)

Quantizes RGB color components to a specified number of levels. Reduces color precision for color palette mapping. Input colors are modified in-place to quantized values.

QUANTIZATION:

  • Divides color range (0-255) into 'levels' bins
  • Maps each component to nearest bin center
  • Reduces color precision for palette mapping
  • Used for 16-color and 256-color mode conversion
Note
Input/output parameters are modified in-place.
Quantization reduces color accuracy but enables palette mapping.
Typical values: 2 levels for 16-color, 6 levels for 256-color.

Definition at line 40 of file foreground.c.

40 {
41 if (!r || !g || !b) {
42 SET_ERRNO(ERROR_INVALID_PARAM, "r, g, or b is NULL");
43 return;
44 }
45
46 if (levels <= 0) {
47 SET_ERRNO(ERROR_INVALID_PARAM, "levels must be positive, got %d", levels);
48 return;
49 }
50
51 int step = 256 / levels;
52 *r = (*r / step) * step;
53 *g = (*g / step) * step;
54 *b = (*b / step) * step;
55}

References ERROR_INVALID_PARAM, and SET_ERRNO.

◆ rainbow_replace_ansi_colors()

char * rainbow_replace_ansi_colors ( const char * ansi_string,
float time_seconds )

#include <include/ascii-chat/video/rgba/color_filter.h>

Replace all RGB ANSI codes with rainbow color.

Parameters
ansi_stringInput string with ANSI escape sequences
time_secondsCurrent time in seconds (for rainbow animation)
Returns
New string with rainbow colors, or NULL if no changes needed

Replaces all RGB foreground color codes (\x1b[38;2;R;G;Bm) in the input string with a single rainbow color calculated from the current time. This preserves ASCII character selection while applying rainbow colors.

The function:

  1. Calculates rainbow color from time using color_filter_calculate_rainbow()
  2. Builds replacement ANSI code string
  3. Scans input for \x1b[38;2; sequences
  4. Replaces each RGB code with rainbow code
  5. Returns new string (caller must SAFE_FREE)
Note
Returns NULL if no ANSI codes found (use original string)
Caller must free returned string with SAFE_FREE()
Input string is not modified
Usable in both terminal apps (lib/session) and WASM apps (src/web)

Definition at line 352 of file color_filter.c.

352 {
353 animation_sample_t sample;
354 animation_config_t config = {.type = ANIMATION_RAINBOW_FILTER, .fps = 60, .speed = 1};
355 if (animation_sample_at(config, time_seconds, &sample) != ASCIICHAT_OK)
356 return NULL;
357 char *output = NULL;
358 animation_target_t target = {.type = ANIMATION_TARGET_ANSI, .ansi = {.input = ansi_string, .out = &output}};
359 if (animation_apply(&sample, &target) != ASCIICHAT_OK)
360 return NULL;
361 return output;
362}
asciichat_error_t animation_sample_at(animation_config_t config, double seconds, animation_sample_t *out)
@ ANIMATION_RAINBOW_FILTER

References animation_apply(), ANIMATION_RAINBOW_FILTER, animation_sample_at(), ANIMATION_TARGET_ANSI, and ASCIICHAT_OK.

Referenced by mirror_convert_frame().

◆ rep_is_profitable()

bool rep_is_profitable ( uint32_t runlen)

#include <include/ascii-chat/video/ascii/output_buffer.h>

Check if run-length encoding is profitable.

Parameters
runlenRun length to check (number of repeated characters)
Returns
true if RLE is profitable, false otherwise

Determines whether run-length encoding (RLE) would reduce output size compared to emitting individual characters. RLE is profitable when the overhead of the repeat sequence is less than the characters it replaces.

RLE PROFITABILITY:

  • RLE uses format: ESC[runs (e.g., ESC[100X repeats 'X' 100 times)
  • Overhead: ~6-8 bytes for repeat sequence
  • Profit: runlen - overhead bytes saved
  • Profitable when runlen > ~10-15 characters
Note
Returns true if runlen exceeds RLE overhead threshold.
Threshold is tuned for typical ASCII art character runs.

Definition at line 137 of file output_buffer.c.

137 {
138 if (runlen <= 2)
139 return false;
140 uint32_t k = runlen - 1; // Extra repetitions beyond the first character
141 uint32_t rep_cost = (uint32_t)(digits_u32(k) + 3); // ESC [ digits b
142 return k > rep_cost; // Manual repetition cost vs REP cost
143}

Referenced by ansi_compress_rle().

◆ rgb_to_16color_halfblocks_scalar()

char * rgb_to_16color_halfblocks_scalar ( const uint8_t * rgb,
int width,
int height,
int stride_bytes,
const char * palette )

#include <include/ascii-chat/video/ascii/scalar/halfblock.h>

Convert RGB to 16-color half-blocks using scalar code.

Parameters
rgbRGB pixel data (RGB24 format, 3 bytes per pixel)
widthImage width in pixels
heightImage height in pixels
stride_bytesRow stride in bytes (if 0, calculated as width * 3)
paletteCharacter palette (unused, for API consistency)
pad_heightTop padding height (number of newlines to output before frame)
Returns
Allocated ASCII string with half-block characters (caller must free), or NULL on error

Renders an RGB image using halfblock characters with 16-color ANSI codes. Processes 2 rows of source pixels per 1 output line with foreground and background color selection from 16-color palette.

Note
Caller must free the returned buffer with free().

Definition at line 11 of file scalar/halfblock.c.

11 {
12 (void)palette;
14}
const simd_cells_t simd_cells_scalar
Definition cells.c:60

References ASCII_COLOR_16, ascii_render_halfblocks, height, simd_cells_scalar, and width.

◆ rgb_to_256color_halfblocks_scalar()

char * rgb_to_256color_halfblocks_scalar ( const uint8_t * rgb,
int width,
int height,
int stride_bytes,
const char * palette )

#include <include/ascii-chat/video/ascii/scalar/halfblock.h>

Convert RGB to 256-color half-blocks using scalar code.

Parameters
rgbRGB pixel data (RGB24 format, 3 bytes per pixel)
widthImage width in pixels
heightImage height in pixels
stride_bytesRow stride in bytes (if 0, calculated as width * 3)
paletteCharacter palette (unused, for API consistency)
pad_heightTop padding height (number of newlines to output before frame)
Returns
Allocated ASCII string with half-block characters (caller must free), or NULL on error

Renders an RGB image using halfblock characters with 256-color ANSI codes. Processes 2 rows of source pixels per 1 output line with foreground and background color selection from 256-color palette.

Note
Caller must free the returned buffer with free().

Definition at line 7 of file scalar/halfblock.c.

7 {
8 (void)palette;
10}

References ASCII_COLOR_256, ascii_render_halfblocks, height, simd_cells_scalar, and width.

◆ rgb_to_ansi_8bit()

void rgb_to_ansi_8bit ( int r,
int g,
int b,
int * fg_code,
int * bg_code )

#include <include/ascii-chat/video/rgba/image.h>

Convert RGB to 8-bit ANSI color codes.

Parameters
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)
fg_codeOutput foreground color code (must not be NULL, range 0-255)
bg_codeOutput background color code (must not be NULL, range 0-255)

Converts RGB color values to 8-bit ANSI color codes (256-color palette). Quantizes RGB colors to 256-color palette indices for foreground and background colors. Output codes are indices into 256-color ANSI palette.

COLOR QUANTIZATION:

  • RGB colors are quantized to 256-color palette
  • Quantization uses standard 6x6x6 color cube
  • Output codes are palette indices (0-255)
  • Foreground and background codes may differ
Note
Output parameters are modified to contain palette indices.
Color codes are indices into 256-color ANSI palette.
Quantization reduces color accuracy but enables 256-color mode.

Definition at line 69 of file foreground.c.

69 {
70 if (!fg_code || !bg_code) {
71 SET_ERRNO(ERROR_INVALID_PARAM, "fg_code or bg_code is NULL");
72 return;
73 }
74
75 // Convert RGB to 8-bit color code (216 color cube + 24 grayscale)
76 if (r == g && g == b) {
77 // Grayscale
78 if (r < 8) {
79 *fg_code = 16;
80 } else if (r > 248) {
81 *fg_code = 231;
82 } else {
83 *fg_code = 232 + (r - 8) / 10;
84 }
85 } else {
86 // Color cube: 16 + 36*r + 6*g + b where r,g,b are 0-5
87 int r_level = (r * 5) / 255;
88 int g_level = (g * 5) / 255;
89 int b_level = (b * 5) / 255;
90 *fg_code = 16 + 36 * r_level + 6 * g_level + b_level;
91 }
92 *bg_code = *fg_code; // Same logic for background
93}

References ERROR_INVALID_PARAM, and SET_ERRNO.

◆ rgb_to_ansi_bg()

char * rgb_to_ansi_bg ( int r,
int g,
int b )

#include <include/ascii-chat/video/rgba/image.h>

Convert RGB to ANSI background color code.

Parameters
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)
Returns
Allocated ANSI color code string (caller must free), or NULL on error

Converts RGB color values to ANSI background color escape sequence. Returns a string containing the ANSI escape sequence for background color (e.g., "\033[48;2;255;0;0m" for red background).

Note
Returns NULL on error (memory allocation failure).
ANSI string must be freed by caller using free().
ANSI sequence format: ESC[48;2;r;g;bm (truecolor mode).
Color components are clamped to 0-255 range automatically.

Definition at line 63 of file foreground.c.

63 {
64 _Thread_local static char color_code[VIDEO_ASCII_SCALAR_FOREGROUND_COLOR_CODE_BUFFER_SIZE]; // \033[48;2;255;255;255m + \0 = 20 bytes max
65 SAFE_SNPRINTF(color_code, sizeof(color_code), "\033[48;2;%d;%d;%dm", r, g, b);
66 return color_code;
67}
#define VIDEO_ASCII_SCALAR_FOREGROUND_COLOR_CODE_BUFFER_SIZE
Definition foreground.c:6
#define SAFE_SNPRINTF(buffer, buffer_size,...)

References SAFE_SNPRINTF, and VIDEO_ASCII_SCALAR_FOREGROUND_COLOR_CODE_BUFFER_SIZE.

◆ rgb_to_ansi_fg()

char * rgb_to_ansi_fg ( int r,
int g,
int b )

#include <include/ascii-chat/video/rgba/image.h>

Convert RGB to ANSI foreground color code.

Parameters
rRed component (0-255)
gGreen component (0-255)
bBlue component (0-255)
Returns
Allocated ANSI color code string (caller must free), or NULL on error

Converts RGB color values to ANSI foreground color escape sequence. Returns a string containing the ANSI escape sequence for foreground color (e.g., "\033[38;2;255;0;0m" for red).

Note
Returns NULL on error (memory allocation failure).
ANSI string must be freed by caller using free().
ANSI sequence format: ESC[38;2;r;g;bm (truecolor mode).
Color components are clamped to 0-255 range automatically.

Definition at line 57 of file foreground.c.

57 {
58 _Thread_local static char color_code[VIDEO_ASCII_SCALAR_FOREGROUND_COLOR_CODE_BUFFER_SIZE]; // \033[38;2;255;255;255m + \0 = 20 bytes max
59 SAFE_SNPRINTF(color_code, sizeof(color_code), "\033[38;2;%d;%d;%dm", r, g, b);
60 return color_code;
61}

References SAFE_SNPRINTF, and VIDEO_ASCII_SCALAR_FOREGROUND_COLOR_CODE_BUFFER_SIZE.

◆ rgb_to_halfblocks_scalar()

char * rgb_to_halfblocks_scalar ( const uint8_t * rgb,
int width,
int height,
int stride_bytes,
const char * palette )

#include <include/ascii-chat/video/ascii/scalar/halfblock.h>

Convert RGB to monochrome (grayscale) half-blocks using scalar code.

Parameters
rgbRGB pixel data (RGB24 format, 3 bytes per pixel)
widthImage width in pixels
heightImage height in pixels
stride_bytesRow stride in bytes (if 0, calculated as width * 3)
paletteCharacter palette for luminance mapping
Returns
Allocated ASCII string with half-block characters (caller must free), or NULL on error

Renders an RGB image using halfblock characters without color codes. Uses ITU-R BT.601 luminance formula for grayscale conversion.

Note
Caller must free the returned buffer with free().

Definition at line 15 of file scalar/halfblock.c.

15 {
16 (void)palette;
18}

References ASCII_COLOR_NONE, ascii_render_halfblocks, height, simd_cells_scalar, and width.

◆ rgb_to_truecolor_halfblocks_scalar()

char * rgb_to_truecolor_halfblocks_scalar ( const uint8_t * rgb,
int width,
int height,
int stride_bytes )

#include <include/ascii-chat/video/ascii/scalar/halfblock.h>

Convert RGB to truecolor half-blocks using scalar code.

Parameters
rgbRGB pixel data (RGB24 format, 3 bytes per pixel)
widthImage width in pixels
heightImage height in pixels
stride_bytesRow stride in bytes (if 0, calculated as width * 3)
Returns
Allocated ASCII string with half-block characters (caller must free), or NULL on error

Renders an RGB image using halfblock characters (▀) with truecolor foreground and background colors. Processes 2 rows of source pixels per 1 output line:

  • Top pixel: foreground color for halfblock
  • Bottom pixel: background color for halfblock
  • Last row (odd height): duplicates top row as bottom

Features:

  • Run-length encoding (RLE) for repeated halfblocks
  • Transparent area detection (fully black pixels)
  • Color state tracking to minimize ANSI sequences
  • Proper vertical resolution (height / 2 output rows)
Note
Caller must free the returned buffer with free().
Returns empty string for invalid dimensions (width <= 0 or height <= 0).
Stride of 0 defaults to width * 3 (tightly packed RGB24).

Definition at line 4 of file scalar/halfblock.c.

References ASCII_COLOR_TRUE, ascii_render_halfblocks, height, simd_cells_scalar, and width.

◆ set_color_quality_mode()

void set_color_quality_mode ( bool high_quality)

#include <include/ascii-chat/video/ascii/common.h>

Set color quality mode.

Parameters
high_qualitytrue for 24-bit truecolor, false for 256-color

Controls tradeoff between color fidelity and rendering speed.

◆ simd_caches_destroy_all()

void simd_caches_destroy_all ( void )

#include <include/ascii-chat/video/ascii/common.h>

Destroy all SIMD caches (palette and other caches).

Called during shutdown to clean up resources.

Definition at line 511 of file video/ascii/common.c.

511 {
512 log_dev("SIMD_CACHE: Starting cleanup of all SIMD caches");
513
514 // Only destroy caches if they were ever initialized
515 if (lifecycle_is_initialized(&g_utf8_cache_lc)) {
516 // Destroy shared UTF-8 palette cache (write lock for cleanup)
517 rwlock_wrlock(&g_utf8_cache_rwlock);
518 if (g_utf8_cache_table) {
519 // Free all UTF-8 cache entries using HASH_ITER
520 utf8_palette_cache_t *cache, *tmp;
521 HASH_ITER(hh, g_utf8_cache_table, cache, tmp) {
522 HASH_DEL(g_utf8_cache_table, cache);
523 SAFE_FREE(cache);
524 }
525 g_utf8_cache_table = NULL;
526 // WASM: Skip debug log to avoid blocking
527 // log_debug("UTF8_CACHE: Destroyed shared UTF-8 palette cache");
528 }
529 // Clean up heap arrays
530 if (g_utf8_heap) {
531 SAFE_FREE(g_utf8_heap);
532 g_utf8_heap = NULL;
533 g_utf8_heap_size = 0;
534 }
535 rwlock_wrunlock(&g_utf8_cache_rwlock);
536 // Shutdown lifecycle and destroy rwlock together
537 lifecycle_shutdown(&g_utf8_cache_lc);
538 }
539
540 // Cleanup executes only on CPUs that can enter the corresponding object file.
541#if SIMD_SUPPORT_SSSE3
542 if (platform_cpu_features() & CPU_FEATURE_SSSE3)
543 ssse3_caches_destroy();
544#endif
545#if SIMD_SUPPORT_SSE2
546 if (platform_cpu_features() & CPU_FEATURE_SSE2)
547 sse2_caches_destroy();
548#endif
549#if SIMD_SUPPORT_SVE
550 if (platform_cpu_features() & CPU_FEATURE_SVE)
551 sve_caches_destroy();
552#endif
553
554 log_dev("SIMD_CACHE: All SIMD caches destroyed");
555}

References log_dev, and SAFE_FREE.

Referenced by asciichat_shared_destroy().

◆ str_append_bytes()

void str_append_bytes ( Str * s,
const void * src,
size_t n )

#include <include/ascii-chat/video/ascii/common.h>

Append bytes to string buffer.

Parameters
sString buffer structure
srcSource data
nNumber of bytes to append

◆ str_append_c()

void str_append_c ( Str * s,
char c )

#include <include/ascii-chat/video/ascii/common.h>

Append character to string buffer.

Parameters
sString buffer structure
cCharacter to append

◆ str_destroy()

void str_destroy ( Str * s)

#include <include/ascii-chat/video/ascii/common.h>

Free string buffer.

Parameters
sString buffer structure

◆ str_init()

void str_init ( Str * s)

#include <include/ascii-chat/video/ascii/common.h>

Initialize string buffer.

Parameters
sString buffer structure

◆ str_printf()

void str_printf ( Str * s,
const char * fmt,
... )

#include <include/ascii-chat/video/ascii/common.h>

Append formatted string to buffer.

Parameters
sString buffer structure
fmtFormat string
...Variable arguments

◆ str_reserve()

void str_reserve ( Str * s,
size_t need )

#include <include/ascii-chat/video/ascii/common.h>

Reserve space in string buffer.

Parameters
sString buffer structure
needMinimum bytes needed

◆ write_row_rep_from_arrays_enhanced()

size_t write_row_rep_from_arrays_enhanced ( const uint8_t * fg_r,
const uint8_t * fg_g,
const uint8_t * fg_b,
const uint8_t * bg_r,
const uint8_t * bg_g,
const uint8_t * bg_b,
const uint8_t * fg_idx,
const uint8_t * bg_idx,
const char * ascii_chars,
int width,
char * dst,
size_t cap,
bool is_truecolor )

#include <include/ascii-chat/video/ascii/common.h>

Enhanced REP compression writer.

Parameters
fg_rForeground red array
fg_gForeground green array
fg_bForeground blue array
bg_rBackground red array
bg_gBackground green array
bg_bBackground blue array
fg_idxForeground color indices
bg_idxBackground color indices
ascii_charsCharacter palette
widthImage width in pixels
dstOutput buffer
capOutput buffer capacity
is_truecolorUse truecolor mode
Returns
Number of bytes written

Used by scalar fallbacks and declared in NEON implementation.

References width.

Variable Documentation

◆ _pad

uint8_t utf8_char_t::_pad

Padding for alignment

Definition at line 498 of file include/ascii-chat/video/ascii/common.h.

◆ access_count

atomic_t utf8_palette_cache::access_count

Total access count

Definition at line 506 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ ascii_palette

char ascii_palette[]
extern

#include <include/ascii-chat/video/ascii/ascii.h>

Non-owning source reference used when laying out an ASCII frame. frame_data points to the source text and frame_size tells the compositor how many bytes are valid; the source must remain alive until layout and copy-out finish.

Default ASCII palette characters

Default character palette for ASCII art conversion. Contains characters ordered by luminance (dark to light) for mapping pixel brightness to ASCII characters.

Note
External variable (defined in ascii.c).
Default palette: " .:-=+*#%@$" (common ASCII art palette).

◆ avx2_time

double simd_benchmark_t::avx2_time

AVX2 implementation time (seconds)

Definition at line 306 of file include/ascii-chat/video/ascii/common.h.

◆ best_method

const char* simd_benchmark_t::best_method

Name of fastest method

Definition at line 310 of file include/ascii-chat/video/ascii/common.h.

◆ byte_len

uint8_t utf8_char_t::byte_len

◆ cache

utf8_char_t utf8_palette_cache::cache[256]

Cache of all 256 luminance levels

Definition at line 502 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ cache64

utf8_char_t utf8_palette_cache::cache64[64]

Cache of 64 most common characters

Definition at line 503 of file include/ascii-chat/video/ascii/common.h.

Referenced by ascii_frame_init(), ascii_legacy_frame_init(), and get_utf8_palette_cache().

◆ cached_score

double utf8_palette_cache::cached_score

Eviction score (higher = keep longer)

Definition at line 509 of file include/ascii-chat/video/ascii/common.h.

◆ cap

size_t Str::cap

Total bytes allocated

Definition at line 178 of file include/ascii-chat/video/ascii/common.h.

◆ cBB

int RLEState::cBB

Current background RGB

Definition at line 244 of file include/ascii-chat/video/ascii/common.h.

◆ cBG

int RLEState::cBG

Definition at line 244 of file include/ascii-chat/video/ascii/common.h.

◆ cBR

int RLEState::cBR

Definition at line 244 of file include/ascii-chat/video/ascii/common.h.

◆ cFB

int RLEState::cFB

Current foreground RGB

Definition at line 243 of file include/ascii-chat/video/ascii/common.h.

◆ cFG

int RLEState::cFG

Definition at line 243 of file include/ascii-chat/video/ascii/common.h.

◆ cFR

int RLEState::cFR

Definition at line 243 of file include/ascii-chat/video/ascii/common.h.

◆ char_index_ramp

uint8_t utf8_palette_cache::char_index_ramp[256]

Luminance to character index mapping

Definition at line 504 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ creation_time

uint64_t utf8_palette_cache::creation_time

When this cache was created

Definition at line 508 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ data

char* Str::data

Pointer to allocated buffer

Definition at line 176 of file include/ascii-chat/video/ascii/common.h.

◆ dec3_initialized

bool global_dec3_cache_t::dec3_initialized

Whether cache is initialized

Definition at line 126 of file include/ascii-chat/video/ascii/common.h.

◆ dec3_table

dec3_t global_dec3_cache_t::dec3_table[256]

Lookup table for 0-255

Definition at line 125 of file include/ascii-chat/video/ascii/common.h.

◆ g_dec3_cache

global_dec3_cache_t g_dec3_cache
extern

#include <include/ascii-chat/video/ascii/common.h>

Global decimal cache instance.

Definition at line 38 of file video/ascii/common.c.

38{0};

Referenced by init_dec3().

◆ g_default_luminance_palette

char g_default_luminance_palette[256]
extern

#include <include/ascii-chat/video/ascii/common.h>

Default luminance palette (256 characters).

Definition at line 39 of file video/ascii/common.c.

39{0};

◆ h

int ImageRGB::h

Image height in pixels

Definition at line 258 of file include/ascii-chat/video/ascii/common.h.

◆ heap_index

size_t utf8_palette_cache::heap_index

Index in the eviction min-heap

Definition at line 510 of file include/ascii-chat/video/ascii/common.h.

◆ hh

UT_hash_handle utf8_palette_cache::hh

uthash handle

Definition at line 517 of file include/ascii-chat/video/ascii/common.h.

◆ initialized

bool utf8_palette_cache::initialized

Whether cache is initialized

Definition at line 513 of file include/ascii-chat/video/ascii/common.h.

◆ is_valid

bool utf8_palette_cache::is_valid

Whether cache has valid data

Definition at line 514 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ key

uint32_t utf8_palette_cache::key

Palette string hash (uthash key)

Definition at line 511 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ last_access_time

atomic_t utf8_palette_cache::last_access_time

Last access timestamp

Definition at line 505 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ len [1/2]

uint8_t dec3_t::len

Number of digits (1-3)

Definition at line 115 of file include/ascii-chat/video/ascii/common.h.

◆ len [2/2]

size_t Str::len

Number of bytes currently used

Definition at line 177 of file include/ascii-chat/video/ascii/common.h.

◆ neon_time

double simd_benchmark_t::neon_time

NEON implementation time (seconds)

Definition at line 307 of file include/ascii-chat/video/ascii/common.h.

◆ palette_hash

char utf8_palette_cache::palette_hash[256]

Original palette string for validation

Definition at line 512 of file include/ascii-chat/video/ascii/common.h.

Referenced by get_utf8_palette_cache().

◆ pixels

uint8_t* ImageRGB::pixels

RGB data: w * h * 3 bytes

Definition at line 259 of file include/ascii-chat/video/ascii/common.h.

◆ runLen

int RLEState::runLen

Current run length

Definition at line 245 of file include/ascii-chat/video/ascii/common.h.

◆ s

char dec3_t::s[3]

Digit string (no null terminator)

Definition at line 116 of file include/ascii-chat/video/ascii/common.h.

◆ scalar_time

double simd_benchmark_t::scalar_time

Scalar implementation time (seconds)

Definition at line 303 of file include/ascii-chat/video/ascii/common.h.

◆ seeded

int RLEState::seeded

Whether state is initialized

Definition at line 246 of file include/ascii-chat/video/ascii/common.h.

◆ speedup_best

double simd_benchmark_t::speedup_best

Best speedup ratio

Definition at line 309 of file include/ascii-chat/video/ascii/common.h.

◆ sse2_time

double simd_benchmark_t::sse2_time

SSE2 implementation time (seconds)

Definition at line 304 of file include/ascii-chat/video/ascii/common.h.

◆ ssse3_time

double simd_benchmark_t::ssse3_time

SSSE3 implementation time (seconds)

Definition at line 305 of file include/ascii-chat/video/ascii/common.h.

◆ sve_time

double simd_benchmark_t::sve_time

SVE implementation time (seconds)

Definition at line 308 of file include/ascii-chat/video/ascii/common.h.

◆ total_age_seconds

uint32_t utf8_palette_cache::total_age_seconds

Total age in seconds

Definition at line 507 of file include/ascii-chat/video/ascii/common.h.

◆ utf8_bytes

uint8_t utf8_char_t::utf8_bytes[4]

◆ w

int ImageRGB::w

Image width in pixels

Definition at line 257 of file include/ascii-chat/video/ascii/common.h.

◆ width

uint8_t utf8_char_t::width

Character display width (1 or 2)

Definition at line 495 of file include/ascii-chat/video/ascii/common.h.