ascii-chat 0.8.38
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
sse2.c
Go to the documentation of this file.
1
7#if SIMD_SUPPORT_SSE2
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <stdint.h>
12
13#include <emmintrin.h>
14
15#include <ascii-chat/video/simd/sse2.h>
16#include <ascii-chat/video/simd/ascii_simd.h>
17#include <ascii-chat/common.h>
18#include <ascii-chat/output_buffer.h>
19#include <ascii-chat/util/overflow.h>
20
21//=============================================================================
22// Image-based API (matches NEON architecture)
23//=============================================================================
24
25// Simple monochrome ASCII function (matches scalar image_print performance)
26char *render_ascii_image_monochrome_sse2(const image_t *image, const char *ascii_chars) {
27 if (!image || !image->pixels || !ascii_chars) {
28 return NULL;
29 }
30
31 const int h = image->h;
32 const int w = image->w;
33
34 if (h <= 0 || w <= 0) {
35 return NULL;
36 }
37
38 // Get cached UTF-8 character mappings
39 utf8_palette_cache_t *utf8_cache = get_utf8_palette_cache(ascii_chars);
40 if (!utf8_cache) {
41 log_error("Failed to get UTF-8 palette cache");
42 return NULL;
43 }
44
45 // Buffer size for UTF-8 characters
46 const size_t max_char_bytes = 4;
47 const size_t len = (size_t)h * ((size_t)w * max_char_bytes + 1);
48
49 char *output;
50 output = SAFE_MALLOC(len, char *);
51
52 char *pos = output;
53 const rgb_pixel_t *pixels = (const rgb_pixel_t *)image->pixels;
54
55 // Pure SSE2 processing - matches NEON approach
56 for (int y = 0; y < h; y++) {
57 const rgb_pixel_t *row = &pixels[y * w];
58 int x = 0;
59
60 // Process 16 pixels at a time with SSE2 (full 128-bit register capacity)
61 for (; x + 15 < w; x += 16) {
62 // Manual deinterleave RGB components (SSE2 limitation vs NEON's vld3q_u8)
63 uint8_t r_array[16], g_array[16], b_array[16];
64 for (int j = 0; j < 16; j++) {
65 r_array[j] = row[x + j].r;
66 g_array[j] = row[x + j].g;
67 b_array[j] = row[x + j].b;
68 }
69
70 // Load full 16 bytes into SSE2 registers (process in two 8-pixel batches)
71 __m128i r_vec_lo = _mm_loadl_epi64((__m128i *)(r_array + 0)); // First 8 pixels
72 __m128i r_vec_hi = _mm_loadl_epi64((__m128i *)(r_array + 8)); // Second 8 pixels
73 __m128i g_vec_lo = _mm_loadl_epi64((__m128i *)(g_array + 0));
74 __m128i g_vec_hi = _mm_loadl_epi64((__m128i *)(g_array + 8));
75 __m128i b_vec_lo = _mm_loadl_epi64((__m128i *)(b_array + 0));
76 __m128i b_vec_hi = _mm_loadl_epi64((__m128i *)(b_array + 8));
77
78 // Process first 8 pixels
79 __m128i r_16_lo = _mm_unpacklo_epi8(r_vec_lo, _mm_setzero_si128());
80 __m128i g_16_lo = _mm_unpacklo_epi8(g_vec_lo, _mm_setzero_si128());
81 __m128i b_16_lo = _mm_unpacklo_epi8(b_vec_lo, _mm_setzero_si128());
82
83 __m128i luma_r_lo = _mm_mullo_epi16(r_16_lo, _mm_set1_epi16(77));
84 __m128i luma_g_lo = _mm_mullo_epi16(g_16_lo, _mm_set1_epi16(150));
85 __m128i luma_b_lo = _mm_mullo_epi16(b_16_lo, _mm_set1_epi16(29));
86
87 __m128i luma_sum_lo = _mm_add_epi16(luma_r_lo, luma_g_lo);
88 luma_sum_lo = _mm_add_epi16(luma_sum_lo, luma_b_lo);
89 luma_sum_lo = _mm_add_epi16(luma_sum_lo, _mm_set1_epi16(128));
90 luma_sum_lo = _mm_srli_epi16(luma_sum_lo, 8);
91
92 // Process second 8 pixels
93 __m128i r_16_hi = _mm_unpacklo_epi8(r_vec_hi, _mm_setzero_si128());
94 __m128i g_16_hi = _mm_unpacklo_epi8(g_vec_hi, _mm_setzero_si128());
95 __m128i b_16_hi = _mm_unpacklo_epi8(b_vec_hi, _mm_setzero_si128());
96
97 __m128i luma_r_hi = _mm_mullo_epi16(r_16_hi, _mm_set1_epi16(77));
98 __m128i luma_g_hi = _mm_mullo_epi16(g_16_hi, _mm_set1_epi16(150));
99 __m128i luma_b_hi = _mm_mullo_epi16(b_16_hi, _mm_set1_epi16(29));
100
101 __m128i luma_sum_hi = _mm_add_epi16(luma_r_hi, luma_g_hi);
102 luma_sum_hi = _mm_add_epi16(luma_sum_hi, luma_b_hi);
103 luma_sum_hi = _mm_add_epi16(luma_sum_hi, _mm_set1_epi16(128));
104 luma_sum_hi = _mm_srli_epi16(luma_sum_hi, 8);
105
106 // Pack both halves to 8-bit
107 __m128i luminance_lo = _mm_packus_epi16(luma_sum_lo, _mm_setzero_si128());
108 __m128i luminance_hi = _mm_packus_epi16(luma_sum_hi, _mm_setzero_si128());
109
110 // Store and convert to ASCII characters
111 uint8_t luma_array[16];
112 _mm_storel_epi64((__m128i *)(luma_array + 0), luminance_lo);
113 _mm_storel_epi64((__m128i *)(luma_array + 8), luminance_hi);
114
115 // Convert luminance to UTF-8 characters using optimized mappings
116 for (int j = 0; j < 16; j++) {
117 const utf8_char_t *char_info = &utf8_cache->cache[luma_array[j]];
118 // Optimized: Use direct assignment for single-byte ASCII characters
119 if (char_info->byte_len == 1) {
120 *pos++ = char_info->utf8_bytes[0];
121 } else {
122 // Fallback to full memcpy for multi-byte UTF-8
123 memcpy(pos, char_info->utf8_bytes, char_info->byte_len);
124 pos += char_info->byte_len;
125 }
126 }
127 }
128
129 // Handle remaining pixels with optimized scalar code
130 for (; x < w; x++) {
131 const rgb_pixel_t pixel = row[x];
132 const int luminance = (LUMA_RED * pixel.r + LUMA_GREEN * pixel.g + LUMA_BLUE * pixel.b + LUMA_THRESHOLD) >> 8;
133 const utf8_char_t *char_info = &utf8_cache->cache[luminance];
134 // Optimized: Use direct assignment for single-byte ASCII characters
135 if (char_info->byte_len == 1) {
136 *pos++ = char_info->utf8_bytes[0];
137 } else {
138 // Fallback to full memcpy for multi-byte UTF-8
139 memcpy(pos, char_info->utf8_bytes, char_info->byte_len);
140 pos += char_info->byte_len;
141 }
142 }
143
144 // Add clear-to-end-of-line and newline (except last row)
145 *pos++ = '\033';
146 *pos++ = '[';
147 *pos++ = 'K';
148 if (y < h - 1) {
149 *pos++ = '\n';
150 }
151 }
152
153 // Null terminate
154 *pos = '\0';
155
156 return output;
157}
158
159// 256-color palette mapping (RGB to ANSI 256 color index) - copied from NEON
160static inline uint8_t rgb_to_256color_sse2(uint8_t r, uint8_t g, uint8_t b) {
161 return (uint8_t)(16 + 36 * (r / 51) + 6 * (g / 51) + (b / 51));
162}
163
164// Unified SSE2 function for all color modes (full implementation like NEON)
165char *render_ascii_sse2_unified_optimized(const image_t *image, bool use_background, bool use_256color,
166 const char *ascii_chars) {
167 if (!image || !image->pixels) {
168 return NULL;
169 }
170
171 const int width = image->w;
172 const int height = image->h;
173
174 if (width <= 0 || height <= 0) {
175 char *empty;
176 empty = SAFE_MALLOC(1, char *);
177 empty[0] = '\0';
178 return empty;
179 }
180
181 outbuf_t ob = {0};
182 // Estimate buffer size based on mode (copied from NEON)
183 size_t bytes_per_pixel = use_256color ? 6u : 8u; // 256-color shorter than truecolor
184
185 // Calculate buffer size with overflow checking
186 size_t height_times_width;
187 if (checked_size_mul((size_t)height, (size_t)width, &height_times_width) != ASCIICHAT_OK) {
188 log_error("Buffer size overflow: height * width overflow");
189 return NULL;
190 }
191
192 size_t pixel_data_size;
193 if (checked_size_mul(height_times_width, bytes_per_pixel, &pixel_data_size) != ASCIICHAT_OK) {
194 log_error("Buffer size overflow: (height * width) * bytes_per_pixel overflow");
195 return NULL;
196 }
197
198 size_t height_times_16;
199 if (checked_size_mul((size_t)height, 16u, &height_times_16) != ASCIICHAT_OK) {
200 log_error("Buffer size overflow: height * 16 overflow");
201 return NULL;
202 }
203
204 size_t temp;
205 if (checked_size_add(pixel_data_size, height_times_16, &temp) != ASCIICHAT_OK) {
206 log_error("Buffer size overflow: pixel_data + height*16 overflow");
207 return NULL;
208 }
209
210 if (checked_size_add(temp, 64u, &ob.cap) != ASCIICHAT_OK) {
211 log_error("Buffer size overflow: total capacity overflow");
212 return NULL;
213 }
214
215 ob.buf = SAFE_MALLOC(ob.cap ? ob.cap : 1, char *);
216 if (!ob.buf)
217 return NULL;
218
219 // Get cached UTF-8 character mappings for color rendering
220 utf8_palette_cache_t *utf8_cache = get_utf8_palette_cache(ascii_chars);
221 if (!utf8_cache) {
222 log_error("Failed to get UTF-8 palette cache for SSE2 color");
223 SAFE_FREE(ob.buf);
224 return NULL;
225 }
226
227 // SSE2 doesn't have _mm_shuffle_epi8 (introduced in SSSE3), so use scalar UTF-8 cache lookup
228 // This is still much faster than the old approach since UTF-8 parsing is cached
229
230 // Track current color state (copied from NEON)
231 int curR = -1, curG = -1, curB = -1;
232 int cur_color_idx = -1;
233
234 for (int y = 0; y < height; y++) {
235 const rgb_pixel_t *row = &((const rgb_pixel_t *)image->pixels)[y * width];
236 int x = 0;
237
238 // Process 16-pixel chunks with SSE2 (full 128-bit register capacity)
239 while (x + 16 <= width) {
240 // Manual deinterleave RGB components (SSE2 limitation vs NEON's vld3q_u8)
241 uint8_t r_array[16], g_array[16], b_array[16];
242 for (int j = 0; j < 16; j++) {
243 r_array[j] = row[x + j].r;
244 g_array[j] = row[x + j].g;
245 b_array[j] = row[x + j].b;
246 }
247
248 // Load into SSE2 registers
249 __m128i r_vec = _mm_loadl_epi64((__m128i *)r_array);
250 __m128i g_vec = _mm_loadl_epi64((__m128i *)g_array);
251 __m128i b_vec = _mm_loadl_epi64((__m128i *)b_array);
252
253 // Convert to 16-bit for arithmetic
254 __m128i r_16 = _mm_unpacklo_epi8(r_vec, _mm_setzero_si128());
255 __m128i g_16 = _mm_unpacklo_epi8(g_vec, _mm_setzero_si128());
256 __m128i b_16 = _mm_unpacklo_epi8(b_vec, _mm_setzero_si128());
257
258 // Calculate luminance: (77*R + 150*G + 29*B + 128) >> 8
259 __m128i luma_r = _mm_mullo_epi16(r_16, _mm_set1_epi16(LUMA_RED));
260 __m128i luma_g = _mm_mullo_epi16(g_16, _mm_set1_epi16(LUMA_GREEN));
261 __m128i luma_b = _mm_mullo_epi16(b_16, _mm_set1_epi16(LUMA_BLUE));
262
263 __m128i luma_sum = _mm_add_epi16(luma_r, luma_g);
264 luma_sum = _mm_add_epi16(luma_sum, luma_b);
265 luma_sum = _mm_add_epi16(luma_sum, _mm_set1_epi16(LUMA_THRESHOLD));
266 luma_sum = _mm_srli_epi16(luma_sum, 8);
267
268 // Pack back to 8-bit and store
269 __m128i luminance = _mm_packus_epi16(luma_sum, _mm_setzero_si128());
270 uint8_t luma_array[8];
271 _mm_storel_epi64((__m128i *)luma_array, luminance);
272
273 // Convert to UTF-8 character indices using cached mappings
274 uint8_t char_indices[8];
275 for (int i = 0; i < 8; i++) {
276 const uint8_t luma_idx = luma_array[i] >> 2; // 0-63 index
277 char_indices[i] = luma_idx; // Direct index into cache64
278 }
279
280 if (use_256color) {
281 // 256-color mode processing (copied from NEON logic)
282 uint8_t color_indices[8];
283 for (int i = 0; i < 8; i++) {
284 color_indices[i] = rgb_to_256color_sse2(r_array[i], g_array[i], b_array[i]);
285 }
286
287 // Emit with RLE on (UTF-8 character, color) runs
288 for (int i = 0; i < 8;) { // SSE2 processes 8 pixels, not 16
289 const uint8_t char_idx = char_indices[i];
290 const utf8_char_t *char_info = &utf8_cache->cache64[char_idx];
291 const uint8_t color_idx = color_indices[i];
292
293 int j = i + 1;
294 while (j < 8 && char_indices[j] == char_idx && color_indices[j] == color_idx) {
295 j++;
296 }
297 const uint32_t run = (uint32_t)(j - i);
298
299 if (color_idx != cur_color_idx) {
300 if (use_background) {
301 emit_set_256_color_bg(&ob, color_idx);
302 } else {
303 emit_set_256_color_fg(&ob, color_idx);
304 }
305 cur_color_idx = color_idx;
306 }
307
308 // Emit UTF-8 character from cache
309 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
310 if (rep_is_profitable(run)) {
311 emit_rep(&ob, run - 1);
312 } else {
313 for (uint32_t k = 1; k < run; k++) {
314 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
315 }
316 }
317 i = j;
318 }
319 } else {
320 // Truecolor mode processing with UTF-8 characters
321 for (int i = 0; i < 8;) { // SSE2 processes 8 pixels
322 const uint8_t char_idx = char_indices[i];
323 const utf8_char_t *char_info = &utf8_cache->cache64[char_idx];
324 const uint8_t r = r_array[i];
325 const uint8_t g = g_array[i];
326 const uint8_t b = b_array[i];
327
328 int j = i + 1;
329 while (j < 8 && char_indices[j] == char_idx && r_array[j] == r && g_array[j] == g && b_array[j] == b) {
330 j++;
331 }
332 const uint32_t run = (uint32_t)(j - i);
333
334 if (r != curR || g != curG || b != curB) {
335 if (use_background) {
336 emit_set_truecolor_bg(&ob, r, g, b);
337 } else {
338 emit_set_truecolor_fg(&ob, r, g, b);
339 }
340 curR = r;
341 curG = g;
342 curB = b;
343 }
344
345 // Emit UTF-8 character from cache
346 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
347 if (rep_is_profitable(run)) {
348 emit_rep(&ob, run - 1);
349 } else {
350 for (uint32_t k = 1; k < run; k++) {
351 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
352 }
353 }
354 i = j;
355 }
356 }
357 x += 16;
358 }
359
360 // Scalar tail for remaining pixels (copied from NEON logic)
361 for (; x < width;) {
362 const rgb_pixel_t *p = &row[x];
363 uint32_t R = p->r, G = p->g, B = p->b;
364 uint8_t Y = (uint8_t)((LUMA_RED * R + LUMA_GREEN * G + LUMA_BLUE * B + LUMA_THRESHOLD) >> 8);
365 uint8_t luma_idx = Y >> 2;
366 const utf8_char_t *char_info = &utf8_cache->cache64[luma_idx];
367
368 if (use_256color) {
369 // 256-color scalar tail with UTF-8
370 uint8_t color_idx = rgb_to_256color_sse2((uint8_t)R, (uint8_t)G, (uint8_t)B);
371
372 int j = x + 1;
373 while (j < width) {
374 const rgb_pixel_t *q = &row[j];
375 uint32_t R2 = q->r, G2 = q->g, B2 = q->b;
376 uint8_t Y2 = (uint8_t)((LUMA_RED * R2 + LUMA_GREEN * G2 + LUMA_BLUE * B2 + LUMA_THRESHOLD) >> 8);
377 uint8_t luma_idx2 = Y2 >> 2;
378 uint8_t color_idx2 = rgb_to_256color_sse2((uint8_t)R2, (uint8_t)G2, (uint8_t)B2);
379 if (luma_idx2 != luma_idx || color_idx2 != color_idx)
380 break;
381 j++;
382 }
383 uint32_t run = (uint32_t)(j - x);
384
385 if (color_idx != cur_color_idx) {
386 if (use_background) {
387 emit_set_256_color_bg(&ob, color_idx);
388 } else {
389 emit_set_256_color_fg(&ob, color_idx);
390 }
391 cur_color_idx = color_idx;
392 }
393
394 // Emit UTF-8 character from cache
395 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
396 if (rep_is_profitable(run)) {
397 emit_rep(&ob, run - 1);
398 } else {
399 for (uint32_t k = 1; k < run; k++) {
400 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
401 }
402 }
403 x = j;
404 } else {
405 // Truecolor scalar tail with UTF-8
406 int j = x + 1;
407 while (j < width) {
408 const rgb_pixel_t *q = &row[j];
409 uint32_t R2 = q->r, G2 = q->g, B2 = q->b;
410 uint8_t Y2 = (uint8_t)((LUMA_RED * R2 + LUMA_GREEN * G2 + LUMA_BLUE * B2 + LUMA_THRESHOLD) >> 8);
411 uint8_t luma_idx2 = Y2 >> 2;
412 if (luma_idx2 != luma_idx || R2 != R || G2 != G || B2 != B)
413 break;
414 j++;
415 }
416 uint32_t run = (uint32_t)(j - x);
417
418 if ((int)R != curR || (int)G != curG || (int)B != curB) {
419 if (use_background) {
420 emit_set_truecolor_bg(&ob, (uint8_t)R, (uint8_t)G, (uint8_t)B);
421 } else {
422 emit_set_truecolor_fg(&ob, (uint8_t)R, (uint8_t)G, (uint8_t)B);
423 }
424 curR = (int)R;
425 curG = (int)G;
426 curB = (int)B;
427 }
428
429 // Emit UTF-8 character from cache
430 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
431 if (rep_is_profitable(run)) {
432 emit_rep(&ob, run - 1);
433 } else {
434 for (uint32_t k = 1; k < run; k++) {
435 ob_write(&ob, char_info->utf8_bytes, char_info->byte_len);
436 }
437 }
438 x = j;
439 }
440 }
441
442 // End row: clear to EOL, reset SGR, add newline (except for last row) (copied from NEON)
443 ob_putc(&ob, '\033');
444 ob_putc(&ob, '[');
445 ob_putc(&ob, 'K');
446 emit_reset(&ob);
447 if (y < height - 1) {
448 ob_putc(&ob, '\n');
449 }
450 curR = curG = curB = -1;
451 cur_color_idx = -1;
452 }
453
454 ob_term(&ob);
455 return ob.buf;
456}
457
458// Destroy SSE2 cache resources (called at program shutdown)
459void sse2_caches_destroy(void) {
460 // SSE2 currently uses shared caches from common.c, so no specific cleanup needed
461 log_debug("SSE2_CACHE: SSE2 caches cleaned up");
462}
463
464#endif /* SIMD_SUPPORT_SSE2 */
void emit_set_256_color_bg(outbuf_t *ob, uint8_t color_idx)
void emit_set_256_color_fg(outbuf_t *ob, uint8_t color_idx)
void ob_term(outbuf_t *ob)
void ob_putc(outbuf_t *ob, char c)
bool rep_is_profitable(uint32_t runlen)
void emit_set_truecolor_fg(outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
void emit_rep(outbuf_t *ob, uint32_t extra)
void ob_write(outbuf_t *ob, const char *s, size_t n)
void emit_reset(outbuf_t *ob)
void emit_set_truecolor_bg(outbuf_t *ob, uint8_t r, uint8_t g, uint8_t b)
#define R2(v, w, x, y, z, i)
Definition sha1.c:58
utf8_palette_cache_t * get_utf8_palette_cache(const char *ascii_chars)