ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
glyph.c
Go to the documentation of this file.
1#include <ascii-chat/otel.h>
2#include <ascii-chat/common.h>
8#include <string.h>
9#include <limits.h>
10
11#include "glyph.h"
12
13/* Compare a small spatial image patch against glyph coverage masks.
14 * The source is fitted at 8x8 samples per output cell, then averaged to 4x4.
15 * ASCII coverage comes from DejaVu Sans Mono; real terminal fonts may differ. */
16#include "../glyph_masks.h"
17
18#define GLYPH_ASCII_COUNT 95
19#define GLYPH_BLOCK_COUNT 20
20#define GLYPH_COUNT (GLYPH_ASCII_COUNT + GLYPH_BLOCK_COUNT)
21
22static int glyph_palette_index(const uint8_t *p, size_t *length) {
23 if (*p >= 32 && *p <= 126) {
24 *length = 1;
25 return (int)*p - 32;
26 }
27 if (*p == 0xe2 && p[1] == 0x96 && p[2] >= 0x80 && p[2] <= 0x93) {
28 *length = 3;
29 return GLYPH_ASCII_COUNT + (int)(p[2] - 0x80);
30 }
31 return -1;
32}
33
34static uint8_t glyph_block_pixel(int block, int x, int y) {
35 if (block >= 17)
36 return (uint8_t)((block - 16) * 255 / 4);
37 bool set = block == 0 ? y < 4 : block <= 7 ? y >= 8 - block : block == 8 ? true : block <= 15 ? x < 16 - block : x >= 4;
38 return set ? 255 : 0;
39}
40
41// Block elements have font-independent geometry. Coverage is the area of
42// each quarter-cell covered by the block, including eighth-cell boundaries.
43static void glyph_block_mask(int block, uint8_t mask[16]) {
44 for (int y = 0; y < 4; ++y) {
45 for (int x = 0; x < 4; ++x) {
46 int coverage = 0;
47 for (int sy = 0; sy < 2; ++sy) {
48 for (int sx = 0; sx < 2; ++sx) {
49 int px = 2 * x + sx, py = 2 * y + sy;
50 coverage += glyph_block_pixel(block, px, py) == 255 ? 1 : 0;
51 }
52 }
53 mask[y * 4 + x] = block >= 17 ? (uint8_t)((block - 16) * 255 / 4) : (uint8_t)(coverage * 255 / 4);
54 }
55 }
56}
57
58static uint32_t glyph_key(int index) {
60 return (uint32_t)(index + 32);
61 uint32_t cp = 0x2580u + (uint32_t)(index - GLYPH_ASCII_COUNT);
62 const uint8_t bytes[4] = {(uint8_t)(0xe0u | (cp >> 12)), (uint8_t)(0x80u | ((cp >> 6) & 63)), (uint8_t)(0x80u | (cp & 63)), 0};
63 uint32_t key = 0;
64 memcpy(&key, bytes, sizeof(key));
65 return key;
66}
67
68bool ascii_glyph_palette_supported_impl(const char *palette) {
69 if (!palette || !*palette)
70 return false;
71 for (const uint8_t *p = (const uint8_t *)palette; *p;) {
72 size_t length;
73 if (glyph_palette_index(p, &length) < 0)
74 return false;
75 p += length;
76 }
77 return true;
78}
79
80typedef struct {
81 int16_t mask[16];
82 int16_t centered[16];
83 int16_t mask_row_sum[4];
85 int16_t fine_row_sum[8];
89
90// Cache only the sufficient statistics used by glyph scoring. The bounded,
91// frame-local table never retains source images or temporal history.
92#define GLYPH_MATCH_CACHE_SIZE 256
102
103static bool glyph_match_cached(const glyph_match_cache_t *match, uint32_t previous, const uint8_t patch[16], const int16_t chroma[2][16], int chroma_energy, const int16_t fine[64], bool colored) {
104 if (match->previous != previous || match->chroma_energy != chroma_energy || memcmp(match->patch, patch, sizeof(match->patch)))
105 return false;
106 if (chroma_energy && memcmp(match->chroma, chroma, sizeof(match->chroma)))
107 return false;
108 return !colored || memcmp(match->fine, fine, sizeof(match->fine)) == 0;
109}
110
111// Preserve hue while keeping visible ink against the dark canvas. Color is
112// weighted by glyph coverage, so a small feature is not colored by its corner.
113static uint32_t glyph_foreground(const glyph_candidate_t *glyph, const int16_t samples[3][16], const int sums[3], bool uniform_rows) {
114 unsigned channels[3], peak = 0;
115 int stride = uniform_rows ? 4 : 1, count = 16 / stride;
116 // With constant color, both coverage-weighted estimates equal that color.
117 // Upscaled source pixels commonly cover an entire terminal cell.
118 bool uniform = true;
119 for (int i = stride; uniform && i < 16; i += stride)
120 uniform = samples[0][i] == samples[0][0] && samples[1][i] == samples[1][0] && samples[2][i] == samples[2][0];
121 if (uniform) {
122 for (int c = 0; c < 3; ++c) {
123 channels[c] = (unsigned)samples[c][0];
124 if (channels[c] > peak)
125 peak = channels[c];
126 }
127 } else {
128 int order[16];
129 int luminance[16];
130 for (int i = 0; i < count; ++i) {
131 int index = i * stride;
132 luminance[index] = (77 * samples[0][index] + 150 * samples[1][index] + 29 * samples[2][index]) >> 8;
133 int j = i;
134 while (j > 0 && luminance[order[j - 1]] > luminance[index]) {
135 order[j] = order[j - 1];
136 --j;
137 }
138 order[j] = index;
139 }
140 int median = order[count / 2];
141 int weighted_luma = 0;
142 for (int i = 0; i < count; ++i)
143 weighted_luma += luminance[i * stride] * (uniform_rows ? glyph->mask_row_sum[i] : glyph->mask[i]);
144 if (glyph->sum) {
145 int covered = 0;
146 for (int i = 0; i < count; ++i) {
147 covered += uniform_rows ? glyph->mask_row_sum[order[i] / 4] : glyph->mask[order[i]];
148 if (covered * 2 >= glyph->sum) {
149 median = order[i];
150 break;
151 }
152 }
153 }
154 for (int c = 0; c < 3; ++c) {
155 int weighted = 0;
156 for (int i = 0; i < count; ++i)
157 weighted += samples[c][i * stride] * (uniform_rows ? glyph->mask_row_sum[i] : glyph->mask[i]);
158 unsigned average = glyph->sum ? (unsigned)((weighted + glyph->sum / 2) / glyph->sum) : (unsigned)((sums[c] + 8) / 16);
159 // Blend with a covered median pixel to reduce isolated outliers without
160 // creating colors by independently taking a median of each channel.
161 bool representative = !glyph->sum || luminance[median] * glyph->sum * 2 >= weighted_luma;
162 channels[c] = representative ? (average + (unsigned)samples[c][median] + 1) / 2 : average;
163 if (channels[c] > peak)
164 peak = channels[c];
165 }
166 }
167 if (peak) {
168 unsigned target = 128 + peak / 2;
169 for (int c = 0; c < 3; ++c)
170 channels[c] = (channels[c] * target + peak / 2) / peak;
171 }
172 return (channels[0] << 16) | (channels[1] << 8) | channels[2];
173}
174
175static int glyph_lift_luma(int luma) {
176 return luma + (luma * (255 - luma) + 256) / 512;
177}
178
179static uint32_t glyph_ordered_dither(uint32_t rgb, int x, int y, ascii_color_t mode) {
180 static const uint8_t bayer[4][4] = {{0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};
181 int amplitude = mode == ASCII_COLOR_16 ? 32 : 16;
182 int offset = ((int)bayer[y & 3][x & 3] * 2 - 15) * amplitude / 16;
183 uint32_t result = 0;
184 for (int shift = 0; shift <= 16; shift += 8) {
185 int channel = (int)((rgb >> shift) & 255);
186 if (channel > 0 && channel < 255) {
187 channel += offset;
188 if (channel < 0)
189 channel = 0;
190 if (channel > 255)
191 channel = 255;
192 }
193 result |= (uint32_t)channel << shift;
194 }
195 return result;
196}
197
198char *ascii_glyph_render(const image_t *image, ascii_color_t mode, const simd_cells_t *ops, const char *palette, bool background) {
199 if (!image || !image->pixels || !ops || image->w <= 0 || image->h <= 0 || image->w % 8 || image->h % 8 || mode < ASCII_COLOR_NONE || mode > ASCII_COLOR_TRUE) {
200 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid glyph matching input");
201 return NULL;
202 }
203 bool allowed[GLYPH_COUNT] = {false};
204 int candidates[GLYPH_COUNT];
205 // Restrict the atlas to unique palette entries before scoring any cells.
206 size_t candidate_count = 0;
207 int (*shape_correlation)(const int16_t[16], const int16_t[16]) = ops->glyph_shape_correlation ? ops->glyph_shape_correlation : glyph_shape_correlation_scalar;
208 if (palette) {
210 SET_ERRNO(ERROR_INVALID_PARAM, "Glyph palette contains an unsupported character");
211 return NULL;
212 }
213 for (const uint8_t *p = (const uint8_t *)palette; *p;) {
214 size_t length;
215 int index = glyph_palette_index(p, &length);
216 if (!allowed[index]) {
217 allowed[index] = true;
218 candidates[candidate_count++] = index;
219 }
220 p += length;
221 }
222 } else {
223 for (int i = 0; i < GLYPH_ASCII_COUNT; ++i) {
224 allowed[i] = true;
225 candidates[candidate_count++] = i;
226 }
227 }
228 // An explicitly selected palette may be syntactically valid but empty after
229 // runtime option changes. Do not enter the scoring loop with no candidates:
230 // the fallback below dereferences glyphs[best].
231 if (candidate_count == 0) {
232 SET_ERRNO(ERROR_INVALID_PARAM, "Glyph renderer has no candidate glyphs");
233 return NULL;
234 }
235 // Prepare coverage and its sufficient statistics once per frame.
237 // Precompute each mask's brightness and centered shape for correlation.
238 for (size_t c = 0; c < candidate_count; ++c) {
239 int g = candidates[c];
240 glyph_candidate_t *glyph = &glyphs[c];
241 glyph->key = glyph_key(g);
242 uint8_t block_mask[16];
243 const uint8_t *mask = g < GLYPH_ASCII_COUNT ? glyph_masks[g] : block_mask;
244 if (g >= GLYPH_ASCII_COUNT)
245 glyph_block_mask(g - GLYPH_ASCII_COUNT, block_mask);
246 glyph->fine_mean = 0;
247 for (int i = 0; i < 64; ++i) {
248 glyph->fine[i] = g < GLYPH_ASCII_COUNT ? glyph_masks_fine[g][i] : glyph_block_pixel(g - GLYPH_ASCII_COUNT, i % 8, i / 8);
249 glyph->fine_mean += glyph->fine[i];
250 }
251 glyph->fine_mean /= 64;
252 glyph->fine_energy = 0;
253 for (int y = 0; y < 8; ++y) {
254 glyph->fine_row_sum[y] = 0;
255 for (int x = 0; x < 8; ++x) {
256 int centered = (int)glyph->fine[y * 8 + x] - glyph->fine_mean;
257 glyph->fine_row_sum[y] += centered;
258 glyph->fine_energy += centered * centered;
259 }
260 }
261 glyph->sum = glyph->energy = 0;
262 for (int i = 0; i < 16; ++i) {
263 glyph->mask[i] = mask[i];
264 glyph->sum += mask[i];
265 }
266 for (int row = 0; row < 4; ++row) {
267 glyph->mask_row_sum[row] = 0;
268 for (int x = 0; x < 4; ++x)
269 glyph->mask_row_sum[row] += glyph->mask[row * 4 + x];
270 }
271 int mean = glyph->sum / 16;
272 glyph->tone = glyph->sum * 255 / (g < GLYPH_ASCII_COUNT ? GLYPH_MASK_MAX_SUM : 16 * 255);
273 for (int i = 0; i < 16; ++i) {
274 glyph->centered[i] = (int16_t)((int)mask[i] - mean);
275 glyph->energy += glyph->centered[i] * glyph->centered[i];
276 }
277 }
278 // Visit nearby tones first so the existing brightness lower bound can
279 // reject distant candidates sooner. Canonical indices still break ties.
280 size_t tone_order[GLYPH_COUNT];
281 for (size_t c = 0; c < candidate_count; ++c) {
282 size_t position = c;
283 while (position && glyphs[tone_order[position - 1]].tone > glyphs[c].tone) {
284 tone_order[position] = tone_order[position - 1];
285 --position;
286 }
287 tone_order[position] = c;
288 }
289 size_t tone_start[256];
290 size_t position = 0;
291 for (int tone = 0; tone < 256; ++tone) {
292 while (position < candidate_count && glyphs[tone_order[position]].tone < tone)
293 ++position;
294 tone_start[tone] = position;
295 }
297 cells.w /= 8;
298 cells.h /= 8;
299 ascii_frame_t frame;
300 if (ascii_frame_init(&frame, &cells, " .") != ASCIICHAT_OK)
301 return NULL;
302 frame.temporal_preselected = true;
303 // Cells often have the same fit at different RGB hues. Reuse only the fit,
304 // within this frame, and only for the same scoring inputs and prior glyph.
305 // Color and temporal history are still resolved independently for each cell.
307 uint8_t recent_way[GLYPH_MATCH_CACHE_SIZE / 2] = {0};
308 for (int y = 0; y < cells.h; ++y) {
309 for (int x = 0; x < cells.w; ++x) {
310 const rgb_pixel_t *pixels = image->pixels + (size_t)y * 8 * (size_t)image->w + (size_t)x * 8;
311 rgb_pixel_t row_colors[8];
312 bool uniform_rows = true;
313 for (int sy = 0; uniform_rows && sy < 8; ++sy) {
314 const rgb_pixel_t *row = pixels + (size_t)sy * image->w;
315 row_colors[sy] = row[0];
316 for (int sx = 1; uniform_rows && sx < 8; ++sx)
317 uniform_rows = memcmp(row, row + sx, sizeof(*row)) == 0;
318 }
319 int16_t samples[3][16] = {{0}};
320 int sums[3] = {0};
321 uint8_t patch[16];
322 int sample_mean = 0;
323 uint64_t patch_hash = UINT64_C(0xcbf29ce484222325);
324 for (int sy = 0; sy < 4; ++sy) {
325 const rgb_pixel_t *top = image->pixels + (size_t)(y * 8 + sy * 2) * (size_t)image->w + (size_t)(x * 8);
326 const rgb_pixel_t *bottom = top + image->w;
327 int red = 0, green = 0, blue = 0;
328 if (uniform_rows) {
329 red = (row_colors[sy * 2].r + row_colors[sy * 2 + 1].r) / 2;
330 green = (row_colors[sy * 2].g + row_colors[sy * 2 + 1].g) / 2;
331 blue = (row_colors[sy * 2].b + row_colors[sy * 2 + 1].b) / 2;
332 }
333 for (int sx = 0; sx < 4; ++sx) {
334 if (!uniform_rows) {
335 const rgb_pixel_t a = top[sx * 2], b = top[sx * 2 + 1];
336 const rgb_pixel_t c = bottom[sx * 2], d = bottom[sx * 2 + 1];
337 red = (a.r + b.r + c.r + d.r) / 4;
338 green = (a.g + b.g + c.g + d.g) / 4;
339 blue = (a.b + b.b + c.b + d.b) / 4;
340 }
341 int i = sy * 4 + sx;
342 patch[i] = (uint8_t)glyph_lift_luma((77 * red + 150 * green + 29 * blue) >> 8);
343 patch_hash = (patch_hash ^ patch[i]) * UINT64_C(0x100000001b3);
344 samples[0][i] = (int16_t)red;
345 samples[1][i] = (int16_t)green;
346 samples[2][i] = (int16_t)blue;
347 sample_mean += patch[i];
348 for (int channel = 0; channel < 3; ++channel)
349 sums[channel] += samples[channel][i];
350 }
351 }
352 // Compare local shape independently of the patch's average brightness.
353 sample_mean /= 16;
354 int16_t centered_samples[16];
355 int sample_energy = 0;
356 for (int i = 0; i < 16; ++i) {
357 int centered = (int)patch[i] - sample_mean;
358 centered_samples[i] = (int16_t)centered;
359 sample_energy += centered * centered;
360 }
361 // Compare chromatic structure as well as luminance: red and green can
362 // have the same brightness while forming a visible edge.
363 int16_t chroma[2][16];
364 int chroma_energy = 0;
365 for (int i = 0; i < 16; ++i) {
366 chroma[0][i] = (int16_t)((samples[0][i] - samples[1][i]) - (sums[0] - sums[1]) / 16);
367 chroma[1][i] = (int16_t)((samples[2][i] - samples[1][i]) - (sums[2] - sums[1]) / 16);
368 chroma_energy += chroma[0][i] * chroma[0][i] + chroma[1][i] * chroma[1][i];
369 }
370 size_t best = 0, previous_index = 0;
371 uint64_t best_error = UINT64_MAX;
372 uint64_t previous_error = UINT64_MAX;
373 ascii_temporal_cell_t *previous = frame.stabilizer ? &frame.stabilizer->cells[(size_t)y * frame.width + x] : NULL;
374 uint32_t previous_key = previous && previous->valid ? previous->glyph : 0;
375 int16_t fine_samples[64];
376 if (mode != ASCII_COLOR_NONE) {
377 for (int sy = 0; sy < 8; ++sy) {
378 const rgb_pixel_t *row = pixels + (size_t)sy * image->w;
379 int luma = uniform_rows ? glyph_lift_luma((77 * row_colors[sy].r + 150 * row_colors[sy].g + 29 * row_colors[sy].b) >> 8) : 0;
380 for (int sx = 0; sx < 8; ++sx) {
381 if (!uniform_rows) {
382 rgb_pixel_t p = row[sx];
383 luma = glyph_lift_luma((77 * p.r + 150 * p.g + 29 * p.b) >> 8);
384 }
385 fine_samples[sy * 8 + sx] = (int16_t)(luma - sample_mean);
386 }
387 }
388 }
389 // Residuals below eight contribute zero for every candidate. Otherwise
390 // compare the complete chroma vectors, including their integer centering.
391 int contributing_chroma = mode != ASCII_COLOR_NONE && chroma_energy >= 8 ? chroma_energy : 0;
392 patch_hash ^= previous_key ^ ((uint64_t)contributing_chroma << 32);
393 // Zero marks an empty entry; full comparisons still guard collisions.
394 uint64_t cache_hash = patch_hash ? patch_hash : 1;
395 size_t set = ((patch_hash ^ (patch_hash >> 32)) & (GLYPH_MATCH_CACHE_SIZE - 1)) / 2;
396 unsigned way = recent_way[set];
397 glyph_match_cache_t *match = &matches[set * 2 + way];
398 bool repeated = match->hash == cache_hash && glyph_match_cached(match, previous_key, patch, chroma, contributing_chroma, fine_samples, mode != ASCII_COLOR_NONE);
399 if (!repeated) {
400 way ^= 1;
401 match = &matches[set * 2 + way];
402 repeated = match->hash == cache_hash && glyph_match_cached(match, previous_key, patch, chroma, contributing_chroma, fine_samples, mode != ASCII_COLOR_NONE);
403 }
404 recent_way[set] = (uint8_t)way;
405 if (repeated) {
406 best = match->best;
407 previous_index = match->previous_index;
408 best_error = match->best_error;
409 previous_error = match->previous_error;
410 } else {
411 enum { GLYPH_SHORTLIST = 8 };
412 size_t shortlist[GLYPH_SHORTLIST];
413 uint64_t shortlist_error[GLYPH_SHORTLIST];
414 size_t shortlist_count = 0;
415 uint64_t prior_coarse_error = UINT64_MAX;
416 size_t lower = tone_start[sample_mean], upper = lower;
417 while (lower || upper < candidate_count) {
418 size_t c;
419 if (!lower || (upper < candidate_count && glyphs[tone_order[upper]].tone - sample_mean < sample_mean - glyphs[tone_order[lower - 1]].tone))
420 c = tone_order[upper++];
421 else
422 c = tone_order[--lower];
423 bool is_previous = previous && previous->valid && previous->glyph == glyphs[c].key;
424 int tone_delta = sample_mean - glyphs[c].tone;
425 int tone_error = 16 * tone_delta * tone_delta;
426 // Shape and color residuals cannot lower the brightness error.
427 if (!is_previous && shortlist_count == GLYPH_SHORTLIST && (uint64_t)tone_error > shortlist_error[shortlist_count - 1]) {
428 // A previous temporal choice must still receive its full score.
429 if (previous && previous->valid && prior_coarse_error == UINT64_MAX)
430 continue;
431 break;
432 }
433 int dot = sample_energy ? shape_correlation(centered_samples, glyphs[c].centered) : 0;
434 uint64_t error = (uint64_t)(tone_error + sample_energy + glyphs[c].energy - 2 * dot);
435 // Chroma residuals are nonnegative too. Avoid their correlations and
436 // division once the luminance fit alone cannot enter the shortlist.
437 if (!is_previous && shortlist_count == GLYPH_SHORTLIST && error > shortlist_error[shortlist_count - 1])
438 continue;
439 // A chroma residual below eight contributes zero after division.
440 if (mode != ASCII_COLOR_NONE && chroma_energy >= 8 && glyphs[c].energy) {
441 int64_t red_dot = shape_correlation(chroma[0], glyphs[c].centered);
442 int64_t blue_dot = shape_correlation(chroma[1], glyphs[c].centered);
443 int64_t explained = (red_dot * red_dot + blue_dot * blue_dot) / glyphs[c].energy;
444 int64_t residual = chroma_energy - explained;
445 if (residual > 0)
446 error += (uint64_t)residual / 8;
447 } else if (mode != ASCII_COLOR_NONE) {
448 error += (uint64_t)chroma_energy / 8;
449 }
450 if (is_previous) {
451 prior_coarse_error = error;
452 previous_index = c;
453 }
454 size_t position = 0;
455 while (position < shortlist_count && (shortlist_error[position] < error || (shortlist_error[position] == error && shortlist[position] < c)))
456 ++position;
457 if (position < GLYPH_SHORTLIST) {
458 size_t end = shortlist_count < GLYPH_SHORTLIST ? shortlist_count++ : GLYPH_SHORTLIST - 1;
459 for (size_t j = end; j > position; --j) {
460 shortlist[j] = shortlist[j - 1];
461 shortlist_error[j] = shortlist_error[j - 1];
462 }
463 shortlist[position] = c;
464 shortlist_error[position] = error;
465 }
466 }
467 // The second pass resolves near-ties with the original 8x8 samples.
468 // Keep monochrome's established glyph scoring and its reference behavior.
469 bool previous_scored = false;
470 for (size_t n = 0; n < shortlist_count + (prior_coarse_error != UINT64_MAX ? 1u : 0u); ++n) {
471 bool prior = n == shortlist_count;
472 size_t index = prior ? previous_index : shortlist[n];
473 if (prior && previous_scored)
474 continue;
475 uint64_t error = prior ? prior_coarse_error : shortlist_error[n];
476 bool is_previous = previous && previous->valid && previous->glyph == glyphs[index].key;
477 if (!is_previous && error >= best_error)
478 continue;
479 if (mode != ASCII_COLOR_NONE) {
480 // Both centered values are in [-255, 255], so the complete squared
481 // residual is at most 64 * 510 * 510 and fits in a signed int.
482 int fine_error = 0;
483 if (uniform_rows) {
484 // Each source value occurs eight times. Expand the squared
485 // residual using the mask's precomputed row sums and energy.
486 fine_error = glyphs[index].fine_energy;
487 for (int sy = 0; sy < 8; ++sy) {
488 int value = fine_samples[sy * 8];
489 fine_error += 8 * value * value - 2 * value * glyphs[index].fine_row_sum[sy];
490 }
491 } else {
492 for (int i = 0; i < 64; ++i) {
493 int delta = fine_samples[i] - ((int)glyphs[index].fine[i] - glyphs[index].fine_mean);
494 fine_error += delta * delta;
495 }
496 }
497 error += (uint64_t)fine_error / 16;
498 }
499 if (is_previous) {
500 previous_error = error;
501 previous_scored = true;
502 }
503 if (!prior && error < best_error) {
504 best_error = error;
505 best = index;
506 }
507 }
508 match->hash = cache_hash;
509 match->previous = previous_key;
510 match->chroma_energy = contributing_chroma;
511 match->best = best;
512 match->previous_index = previous_index;
513 match->best_error = best_error;
514 match->previous_error = previous_error;
515 memcpy(match->patch, patch, sizeof(patch));
516 if (contributing_chroma)
517 memcpy(match->chroma, chroma, sizeof(chroma));
518 if (mode != ASCII_COLOR_NONE)
519 memcpy(match->fine, fine_samples, sizeof(fine_samples));
520 }
521 uint32_t rgb = glyph_foreground(&glyphs[best], samples, sums, uniform_rows);
522 uint32_t bg_rgb = ((uint32_t)(sums[0] / 16) << 16) | ((uint32_t)(sums[1] / 16) << 8) | (uint32_t)(sums[2] / 16);
523 uint32_t selected = glyphs[best].key;
524 if (previous) {
525 uint32_t previous_color = rgb;
526 uint64_t margin = best_error / 8 + 128;
527 if (previous->glyph != selected && previous_error != UINT64_MAX && (previous_error <= best_error || previous_error - best_error <= margin))
528 previous_color = glyph_foreground(&glyphs[previous_index], samples, sums, uniform_rows);
529 selected = ascii_stabilizer_glyph(previous, patch, samples, mode != ASCII_COLOR_NONE, selected, best_error, previous_error, previous_color, frame.stabilizer->elapsed_ns, &rgb, &bg_rgb);
530 }
531 frame.glyph[x] = selected;
532 frame.packed[x] = rgb;
533 frame.index[x] = bg_rgb;
534 uint32_t color = background ? bg_rgb : rgb;
535 frame.luma[x] = (uint8_t)((77 * ((color >> 16) & 255) + 150 * ((color >> 8) & 255) + 29 * (color & 255)) >> 8);
536 }
537 // Anchor the ordered pattern to terminal cells so stationary video does
538 // not shimmer; truecolor and monochrome output remain unchanged.
539 if (mode == ASCII_COLOR_16 || mode == ASCII_COLOR_256) {
540 for (int x = 0; x < cells.w; ++x) {
541 frame.packed[x] = glyph_ordered_dither(frame.packed[x], x, y, mode);
542 if (background)
543 frame.index[x] = glyph_ordered_dither(frame.index[x], x, y, mode);
544 }
545 }
546 if (background && mode != ASCII_COLOR_NONE) {
547 if (mode == ASCII_COLOR_TRUE) {
548 memcpy(frame.bg, frame.index, frame.width * sizeof(uint32_t));
549 } else {
550 ops->quantize(frame.index, frame.bg, frame.width, mode == ASCII_COLOR_16 ? 16 : 256);
551 }
552 for (size_t x = 0; x < frame.width; ++x)
553 frame.fg[x] = ascii_background_contrast(mode, frame.bg[x], frame.luma[x]);
554 ascii_emit_prepared_row(&frame.output, mode, ops, frame.glyph, frame.fg, frame.bg, frame.width);
555 emit_row_end(&frame.output, true, y + 1 < cells.h);
556 ++frame.row;
557 } else {
558 if (mode == ASCII_COLOR_16 || mode == ASCII_COLOR_256)
559 ops->quantize(frame.packed, frame.index, frame.width, mode == ASCII_COLOR_16 ? 16 : 256);
560 ascii_frame_emit_row(&frame, mode, false, y + 1 < cells.h, ops);
561 }
562 }
563 return ascii_frame_finish(&frame);
564}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
int glyph_shape_correlation_scalar(const int16_t samples[16], const int16_t mask[16])
Definition cells.c:4
char cells[(512 *256 *2)]
Definition fft.c:22
#define GLYPH_MATCH_CACHE_SIZE
Definition glyph.c:92
char * ascii_glyph_render(const image_t *image, ascii_color_t mode, const simd_cells_t *ops, const char *palette, bool background)
Definition glyph.c:198
bool ascii_glyph_palette_supported_impl(const char *palette)
Definition glyph.c:68
#define GLYPH_MASK_MAX_SUM
unsigned int uint32_t
unsigned long long uint64_t
unsigned char uint8_t
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
⚙️ Common definitions, error codes, macros, and types shared throughout the application
SIMD-optimized ASCII conversion interface.
#define ascii_frame_init
#define GLYPH_COUNT
#define GLYPH_ASCII_COUNT
#define ascii_frame_emit_row
#define ascii_frame_finish
void emit_row_end(outbuf_t *out, bool colored, bool newline)
✅ Safe Integer Arithmetic and Overflow Detection
static bool size_t index
Definition queries.h:8
return true
Definition queries.h:13
uint32_t ascii_stabilizer_glyph(ascii_temporal_cell_t *cell, const uint8_t samples[16], const int16_t rgb_samples[3][16], bool colored, uint32_t candidate, uint64_t candidate_error, uint64_t previous_error, uint32_t previous_color, uint64_t elapsed_ns, uint32_t *color, uint32_t *background)
Definition stabilize.c:88
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with ascii frame, it keeps output, output_target, width, source_height here i...
ascii_temporal_cell_t * cells
Definition stabilize.h:25
uint64_t elapsed_ns
Definition stabilize.h:28
uint8_t fine[64]
Definition glyph.c:84
int16_t fine_row_sum[8]
Definition glyph.c:85
int16_t mask_row_sum[4]
Definition glyph.c:83
uint64_t hash
Definition glyph.c:94
int16_t fine[64]
Definition glyph.c:98
uint8_t patch[16]
Definition glyph.c:97
uint64_t best_error
Definition glyph.c:100
uint32_t previous
Definition glyph.c:95
size_t previous_index
Definition glyph.c:99
int16_t chroma[2][16]
Definition glyph.c:98
uint64_t previous_error
Definition glyph.c:100
SIMD-friendly storage for one RGB pixel. r, g, and b hold the color channels and padding keeps the la...
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
uint8_t b
Blue color component (0-255).
uint8_t g
Green color component (0-255).
uint8_t r
Red color component (0-255).
The useful part of simd cells is in luminance: together they describe what is pending,...
Definition cells.h:14
void(* quantize)(const uint32_t *rgb, uint32_t *out, size_t count, unsigned colors)
Definition cells.h:18
int(* glyph_shape_correlation)(const int16_t samples[16], const int16_t mask[16])
Definition cells.h:23
uint32_t ascii_background_contrast(ascii_color_t mode, uint32_t color, uint8_t luma)
void ascii_emit_prepared_row(outbuf_t *out, ascii_color_t mode, const simd_cells_t *ops, const uint32_t *glyph, const uint32_t *fg, const uint32_t *bg, size_t width)