ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
src/server/stream.c
Go to the documentation of this file.
1
132
133/* Storage capacities in elements; text buffers include the terminating NUL. */
134#define SERVER_STREAM_HEX_BUFFER_SIZE 300
135#define SERVER_STREAM_ASCII_BUFFER_SIZE 100
136
138#include <float.h>
139#include <libplatform/atomic.h>
140#include <math.h>
141#include <stdio.h>
142#include <string.h>
143#include <time.h>
144
145#include "client.h"
146#include "main.h"
147#include "stream.h"
148#include <ascii-chat/buffer.h>
149#include <ascii-chat/common.h>
155#include <ascii-chat/util/time.h>
156#include <ascii-chat/util/utf8.h>
162
172static atomic_t g_previous_active_video_count = {0};
173
225
233static int collect_video_sources(image_source_t *sources, int max_sources) {
234 int source_count = 0;
235
236 // Check for shutdown before acquiring locks to prevent lock corruption
238 return 0;
239 }
240
241 // Keep client slots and their incoming frame buffers alive until every
242 // active source has been copied out of its double buffer. remove_client()
243 // frees those buffers under the manager write lock after stopping only that
244 // client's own workers; the other clients' render workers also read them.
245 bool manager_lock_held = g_client_manager_rwlock_initialized;
246 if (manager_lock_held) {
247 rwlock_rdlock(&g_client_manager_rwlock);
248 }
249
250 // Snapshot fields while holding the manager read lock so removal cannot
251 // invalidate a frame-buffer pointer between this scan and its copy.
255 typedef struct {
256 char client_id[MAX_CLIENT_ID_LEN];
257 bool is_active;
258 bool is_sending_video;
259 video_frame_buffer_t *video_buffer;
260 } client_snapshot_t;
261
262 client_snapshot_t client_snapshots[MAX_CLIENTS];
263 int snapshot_count = 0;
264
265 // The manager read lock protects slot identity and buffer lifetime; stream
266 // flags are atomic because receive callbacks update them independently.
267 for (int i = 0; i < MAX_CLIENTS; i++) {
268 client_info_t *client = &g_client_manager.clients[i];
269
270 if (client->client_id[0] == '\0') {
271 continue; // Skip uninitialized clients
272 }
273
274 // Snapshot all needed client state (all atomic reads or stable pointers)
275 SAFE_STRNCPY(client_snapshots[snapshot_count].client_id, client->client_id,
276 sizeof(client_snapshots[snapshot_count].client_id) - 1);
277 client_snapshots[snapshot_count].is_active =
278 atomic_load_bool(&client->active);
279 client_snapshots[snapshot_count].is_sending_video =
281 client_snapshots[snapshot_count].video_buffer =
282 client->incoming_video_buffer; // Stable pointer
283 snapshot_count++;
284 }
285
286 // Process frames (expensive operations)
287 log_dev_every(5 * NS_PER_MS_INT, "Processing %d snapshots", snapshot_count);
288 for (int i = 0; i < snapshot_count && source_count < max_sources; i++) {
289 client_snapshot_t *snap = &client_snapshots[i];
290
291 if (!snap->is_active) {
292 log_dev_every(5 * NS_PER_MS_INT, "Skipping inactive client %s",
293 snap->client_id);
294 continue;
295 }
296
297 log_dev_every(5 * NS_PER_MS_INT, "Client %s: is_sending_video=%d",
298 snap->client_id, snap->is_sending_video);
299
300 SAFE_STRNCPY(sources[source_count].client_id, snap->client_id,
301 sizeof(sources[source_count].client_id) - 1);
302 sources[source_count].image = NULL; // Will be set if video is available
303 sources[source_count].has_video = false;
304
305 // Declare these outside the if block so they're accessible later
306 multi_source_frame_t current_frame = {0};
307 bool got_new_frame = false;
308
309 // Always try to get the last available video frame for consistent ASCII
310 // generation. Keep the swap mutex held until the front-buffer bytes have
311 // been copied: after the next commit, this frame becomes the writer's back
312 // buffer and can be overwritten while the compositor is still reading it.
313 if (snap->is_sending_video && snap->video_buffer) {
314 video_frame_buffer_t *video_buffer = snap->video_buffer;
315 mutex_lock(&video_buffer->swap_mutex);
316 const video_frame_t *frame = video_buffer->front_buffer;
317 if (!frame || !frame->data || frame->size < sizeof(uint32_t) * 2 ||
318 frame->size > video_buffer->allocated_buffer_size) {
319 mutex_unlock(&video_buffer->swap_mutex);
320 continue;
321 }
322
323 size_t frame_size_val = frame->size;
324
325 if (frame_size_val >= (sizeof(uint32_t) * 2 + 3)) {
326 // PARSE AND VALIDATE DIMENSIONS BEFORE COPYING
327 // Don't trust frame->size - calculate correct size from dimensions
328 uint32_t peek_width = NET_TO_HOST_U32(read_u32_unaligned(frame->data));
330 (const uint8_t *)frame->data + sizeof(uint32_t)));
331
332 // Reject obviously corrupted dimensions
333 if (peek_width == 0 || peek_height == 0 || peek_width > 4096 ||
334 peek_height > 2160) {
335 log_debug("Per-client %s: rejected dimensions %ux%u as corrupted",
336 snap->client_id, peek_width, peek_height);
337 mutex_unlock(&video_buffer->swap_mutex);
338 continue;
339 }
340
341 // Validate dimensions
342 if (image_validate_dimensions((size_t)peek_width,
343 (size_t)peek_height) != ASCIICHAT_OK) {
344 mutex_unlock(&video_buffer->swap_mutex);
345 continue;
346 }
347
348 // Calculate CORRECT frame size based on dimensions (don't trust
349 // frame->size)
350 size_t correct_frame_size = sizeof(uint32_t) * 2;
351 {
352 size_t rgb_size = 0;
353 if (image_calc_rgb_size((size_t)peek_width, (size_t)peek_height,
354 &rgb_size) != ASCIICHAT_OK) {
355 log_debug("Per-client: rgb_size calc failed for %ux%u", peek_width,
356 peek_height);
357 mutex_unlock(&video_buffer->swap_mutex);
358 continue;
359 }
360 correct_frame_size += rgb_size;
361 }
362
364 "Per-client: frame dimensions=%ux%u, frame_size=%zu, "
365 "correct_size=%zu",
366 peek_width, peek_height, frame_size_val,
367 correct_frame_size);
368
369 // Verify frame is at least large enough for the correct size
370 if (frame_size_val < correct_frame_size) {
371 log_debug("Per-client: frame too small: got %zu, need %zu",
372 frame_size_val, correct_frame_size);
373 mutex_unlock(&video_buffer->swap_mutex);
374 continue;
375 }
376
377 // We have frame data - copy ONLY the correct amount based on dimensions
378 current_frame.data = buffer_alloc(NULL, correct_frame_size);
379
380 if (current_frame.data) {
381 memcpy(current_frame.data, frame->data, correct_frame_size);
382 current_frame.size = correct_frame_size;
383 SAFE_STRNCPY(current_frame.source_client_id, snap->client_id,
384 sizeof(current_frame.source_client_id) - 1);
385 current_frame.timestamp =
387 got_new_frame = true;
388 // Keep the frame for reuse, but mark it consumed before the next
389 // swap.
390 atomic_store_bool(&video_buffer->new_frame_available, false);
391 }
392 mutex_unlock(&video_buffer->swap_mutex);
393 } else {
394 mutex_unlock(&video_buffer->swap_mutex);
395 }
396 }
397
398 multi_source_frame_t *frame_to_use = got_new_frame ? &current_frame : NULL;
399
400 if (frame_to_use && frame_to_use->data &&
401 frame_to_use->size > sizeof(uint32_t) * 2) {
402 // Parse the image data
403 // Format: [width:4][height:4][rgb_data:w*h*3]
404 // Use unaligned read helpers - frame data may not be aligned
405 uint32_t img_width =
407 uint32_t img_height = NET_TO_HOST_U32(
408 read_u32_unaligned(frame_to_use->data + sizeof(uint32_t)));
409
410 // Debug logging to understand the data
411 if (img_width == 0xBEBEBEBE || img_height == 0xBEBEBEBE) {
412 SET_ERRNO(
414 "Uninitialized frame dimensions from client %s: 0x%08x x 0x%08x",
415 snap->client_id, img_width, img_height);
416 }
417
418 // Validate dimensions using image utility function
419 if (image_validate_dimensions((size_t)img_width, (size_t)img_height) !=
420 ASCIICHAT_OK) {
422 "Per-client: Invalid image dimensions from client %s: %ux%u "
423 "(data may be corrupted)",
424 snap->client_id, img_width, img_height);
425 if (got_new_frame) {
426 buffer_release(current_frame.data);
427 }
428 source_count++;
429 continue;
430 }
431
432 // Calculate expected frame size with overflow checking
433 size_t expected_size = sizeof(uint32_t) * 2;
434 {
435 size_t rgb_size = 0;
436 if (image_calc_rgb_size((size_t)img_width, (size_t)img_height,
437 &rgb_size) != ASCIICHAT_OK) {
438 SET_ERRNO(
440 "Per-client: RGB size calculation failed for client %s: %ux%u",
441 snap->client_id, img_width, img_height);
442 if (got_new_frame) {
443 buffer_release(current_frame.data);
444 }
445 source_count++;
446 continue;
447 }
448 expected_size += rgb_size;
449 }
450 if (frame_to_use->size != expected_size) {
452 "Per-client: Frame size mismatch from client %s: got %zu, "
453 "expected %zu for %ux%u image",
454 snap->client_id, frame_to_use->size, expected_size, img_width,
455 img_height);
456 if (got_new_frame) {
457 buffer_release(current_frame.data);
458 }
459 source_count++;
460 continue;
461 }
462
463 // Extract pixel data pointer
464 rgb_pixel_t *pixels =
465 (rgb_pixel_t *)(frame_to_use->data + (sizeof(uint32_t) * 2));
466
467 // Create image from buffer domain for consistent video pipeline
468 // management
469 image_t *img = image_new(img_width, img_height);
470 if (!img) {
471 log_error("Per-client: image_new failed for %ux%u", img_width,
472 img_height);
473 if (got_new_frame) {
474 buffer_release(current_frame.data);
475 }
476 continue;
477 }
478 memcpy(img->pixels, pixels,
479 (size_t)img_width * (size_t)img_height * sizeof(rgb_pixel_t));
480 sources[source_count].image = img;
481 sources[source_count].has_video = true;
482
483 // Free temporary frame buffer - image has its own pixel data now
484 if (got_new_frame) {
485 buffer_release(current_frame.data);
486 }
487 } else {
488 // frame_to_use check failed - clean up allocated frame data
489 if (got_new_frame && current_frame.data) {
490 buffer_release(current_frame.data);
491 }
492 }
493
494 // Increment source count for this active client (with or without video)
495 source_count++;
496 }
497
498 if (manager_lock_held) {
499 rwlock_rdunlock(&g_client_manager_rwlock);
500 }
501 return source_count;
502}
503
514static image_t *
515create_single_source_composite(image_source_t *sources, int source_count,
516 const char *target_client_id
517 __attribute__((unused)),
518 unsigned short width __attribute__((unused)),
519 unsigned short height __attribute__((unused))) {
520 (void)target_client_id;
521 (void)width;
522 (void)height;
523 // Find the single source with video
524 image_t *single_source = NULL;
525 for (int i = 0; i < source_count; i++) {
526 if (sources[i].has_video && sources[i].image) {
527 single_source = sources[i].image;
528 break;
529 }
530 }
531
532 if (!single_source) {
534 "Logic error: sources_with_video=1 but no source found");
535 return NULL;
536 }
537
538 // For single source, don't pre-fit the image. Let
539 // ascii_convert_with_capabilities handle all aspect ratio fitting with proper
540 // CHAR_ASPECT correction. This avoids double-correction that was happening
541 // when the image was pre-fitted in pixel space and then aspect_ratio() was
542 // called again with CHAR_ASPECT=2.0. Just return the source image as-is;
543 // ascii_convert_with_capabilities will fit it properly.
544 return single_source;
545}
546
570static void calculate_optimal_grid_layout(
571 image_source_t *sources, int source_count, int sources_with_video,
572 int terminal_width, int terminal_height, int *out_cols, int *out_rows) {
573 // Special cases
574 if (sources_with_video == 0) {
575 *out_cols = 0;
576 *out_rows = 0;
577 return;
578 }
579
580 if (sources_with_video == 1) {
581 *out_cols = 1;
582 *out_rows = 1;
583 return;
584 }
585
586 // ASCII character aspect ratio: characters are ~2x taller than wide
587 // So we need to adjust terminal dimensions to visual space
588 const float CHAR_ASPECT = 2.0f; // Character height / width ratio
589
590 // Calculate average aspect ratio of all video sources
591 float avg_aspect = 0.0f;
592 int aspect_count = 0;
593 for (int i = 0; i < source_count; i++) {
594 if (sources[i].has_video && sources[i].image) {
595 float aspect = (float)sources[i].image->w / (float)sources[i].image->h;
596 avg_aspect += aspect;
597 aspect_count++;
598 }
599 }
600 if (aspect_count > 0) {
601 avg_aspect /= aspect_count;
602 } else {
603 avg_aspect = 1.6f; // Default aspect ratio
604 }
605
606 // Try all reasonable grid configurations
607 int best_cols = 1;
608 int best_rows = sources_with_video;
609 float best_utilization = 0.0f;
610
611 // Try grid configurations from 1x1 up to reasonable limits
612 for (int cols = 1; cols <= sources_with_video; cols++) {
613 int rows = (sources_with_video + cols - 1) / cols; // Ceiling division
614
615 // Skip configurations with too many empty cells (more than one row worth)
616 int total_cells = cols * rows;
617 int empty_cells = total_cells - sources_with_video;
618 if (empty_cells > cols) {
619 continue;
620 }
621
622 // Calculate cell dimensions for this configuration
623 int cell_width = terminal_width / cols;
624 int cell_height = terminal_height / rows;
625
626 // Skip if cells would be too small
627 if (cell_width < 20 || cell_height < 10) {
628 continue;
629 }
630
631 // Calculate total area utilized by all videos in this configuration
632 // For each video, calculate how much space it would use in a cell
633 // IMPORTANT: Account for character aspect ratio (chars are 2x taller than
634 // wide)
635 float total_area_used = 0.0f;
636 int cell_area = cell_width * cell_height;
637
638 for (int i = 0; i < sources_with_video; i++) {
639 // Use average aspect ratio for calculation
640 float video_aspect = avg_aspect;
641
642 // Calculate VISUAL cell aspect ratio (accounting for character shape)
643 // A cell that is cell_width chars wide and cell_height chars tall
644 // has visual aspect = cell_width / (cell_height * CHAR_ASPECT)
645 float cell_visual_aspect =
646 (float)cell_width / ((float)cell_height * CHAR_ASPECT);
647
648 // Calculate fitted dimensions while preserving aspect ratio
649 int fitted_width, fitted_height;
650
651 if (video_aspect > cell_visual_aspect) {
652 // Video is wider than cell - fit to width
653 fitted_width = cell_width;
654 // Visual height needed: cell_width / video_aspect
655 // Character height: visual_height / CHAR_ASPECT
656 fitted_height = (int)((cell_width / video_aspect) / CHAR_ASPECT);
657 } else {
658 // Video is taller than cell - fit to height
659 fitted_height = cell_height;
660 // Visual width needed: cell_height * CHAR_ASPECT * video_aspect
661 fitted_width = (int)(cell_height * CHAR_ASPECT * video_aspect);
662 }
663
664 // Clamp to cell bounds
665 if (fitted_width > cell_width) {
666 fitted_width = cell_width;
667 }
668 if (fitted_height > cell_height) {
669 fitted_height = cell_height;
670 }
671
672 // Add area used by this video
673 total_area_used += fitted_width * fitted_height;
674 }
675
676 // Calculate utilization percentage
677 float total_available_area = (float)(cell_area * sources_with_video);
678 float utilization = total_area_used / total_available_area;
679
680 float test_cell_visual_aspect =
681 (float)cell_width / ((float)cell_height * CHAR_ASPECT);
684 " Testing %dx%d: cell=%dx%d (visual aspect %.2f), utilization=%.1f%%",
685 cols, rows, cell_width, cell_height, test_cell_visual_aspect,
686 utilization * 100.0f);
687
688 // Prefer configurations with better utilization
689 if (utilization > best_utilization) {
690 best_utilization = utilization;
691 best_cols = cols;
692 best_rows = rows;
693 }
694 }
695
696 *out_cols = best_cols;
697 *out_rows = best_rows;
698
699 float terminal_visual_aspect =
700 (float)terminal_width / ((float)terminal_height * CHAR_ASPECT);
702 "Grid layout: %d clients -> %dx%d grid (%.1f%% utilization) | "
703 "terminal=%dx%d (char aspect %.2f, VISUAL "
704 "aspect %.2f), video aspect: %.2f",
705 sources_with_video, best_cols, best_rows,
706 best_utilization * 100.0f, terminal_width, terminal_height,
707 (float)terminal_width / (float)terminal_height,
708 terminal_visual_aspect, avg_aspect);
709}
710
722static image_t *create_multi_source_composite(
723 image_source_t *sources, int source_count, int sources_with_video,
724 const char *target_client_id, unsigned short width, unsigned short height) {
725 (void)target_client_id; // Unused - composite is same for all clients now
726
727 // Calculate optimal grid layout using space-maximizing algorithm
728 int grid_cols, grid_rows;
729 calculate_optimal_grid_layout(sources, source_count, sources_with_video,
730 width, height, &grid_cols, &grid_rows);
731
732 // Calculate composite dimensions in PIXELS for half-block mode
733 // Terminal dimensions are in CHARACTERS, need to convert to pixels:
734 // - Width: 1 char = 1 horizontal pixel
735 // - Height: 1 char = 2 vertical pixels (half-block = 2 pixels per char)
736 const int PIXELS_PER_CHAR_HEIGHT = 2;
737 int composite_width_px = width; // chars = pixels horizontally
738 int composite_height_px =
739 height * PIXELS_PER_CHAR_HEIGHT; // chars * 2 = pixels vertically
740
741 // Create composite with final dimensions - no recreation needed
742 image_t *composite = image_new(composite_width_px, composite_height_px);
743 image_clear(composite);
744
745 // Place each source in the grid
746 int video_source_index = 0; // Track only sources with video
747 for (int i = 0; i < source_count && video_source_index < 9;
748 i++) { // Max 9 sources in 3x3 grid
749 if (!sources[i].image)
750 continue;
751
752 int row = video_source_index / grid_cols;
753 int col = video_source_index % grid_cols;
754 video_source_index++;
755
756 // Use actual composite dimensions for cell calculations
757 // Composite is now in PIXELS (already converted from terminal characters)
758 int cell_width_px = composite->w / grid_cols;
759 int cell_height_px = composite->h / grid_rows;
760
761 // Calculate aspect ratios
762 float src_aspect = (float)sources[i].image->w / (float)sources[i].image->h;
763 float cell_visual_aspect = (float)cell_width_px / (float)cell_height_px;
764
765 int target_width_px, target_height_px;
766
767 // CONTAIN strategy: Fill one dimension completely, let other scale down
768 // (never overflow) Compare aspects to decide which dimension to fill
769 if (src_aspect > cell_visual_aspect) {
770 // Video is WIDER than cell → fill WIDTH (height will be smaller)
771 target_width_px = cell_width_px;
772 target_height_px = (int)((cell_width_px / src_aspect) + 0.5f);
773 } else {
774 // Video is TALLER than cell → fill HEIGHT (width will be smaller)
775 target_height_px = cell_height_px;
776 target_width_px = (int)((cell_height_px * src_aspect) + 0.5f);
777 }
778
781 "Cell %d: %dx%d px, video %.1f, cell %.2f → target %dx%d px (fill %s)",
782 video_source_index - 1, cell_width_px, cell_height_px, src_aspect,
783 cell_visual_aspect, target_width_px, target_height_px,
784 (src_aspect > cell_visual_aspect) ? "WIDTH" : "HEIGHT");
785
786 // Create resized image with standard allocation
787 image_t *resized = image_new(target_width_px, target_height_px);
788 image_resize(sources[i].image, resized);
789
790 // Calculate cell position in pixels (after any composite recreation)
791 int cell_x_offset_px = col * cell_width_px;
792 int cell_y_offset_px = row * cell_height_px;
793
794 // Grid centering strategy:
795 // - Multi-client: Apply padding ONLY to edge cells to center the grid as a
796 // whole
797 // (left column gets left padding, right column gets right padding)
798 // (top row gets top padding, bottom row gets bottom padding)
799 // This keeps cells edge-to-edge while centering the entire grid
800 // - Single client: Center the image within the cell
801 int x_padding_px, y_padding_px;
802
803 // Center images within their cells for all layouts
804 // This prevents gaps/stripes between clients
805 x_padding_px = (cell_width_px - target_width_px) / 2;
806 y_padding_px = (cell_height_px - target_height_px) / 2;
807
808 // Define cell boundaries for clipping (prevents bleeding into adjacent
809 // cells)
810 int cell_x_min = cell_x_offset_px;
811 int cell_x_max = cell_x_offset_px + cell_width_px - 1;
812 int cell_y_min = cell_y_offset_px;
813 int cell_y_max = cell_y_offset_px + cell_height_px - 1;
814
815 // Copy resized image to composite with cell boundary clipping
816 // This allows images to fill cells completely while preventing overlap
817
818 for (int y = 0; y < resized->h; y++) {
819 for (int x = 0; x < resized->w; x++) {
820 // Calculate destination position
821 int dst_x = cell_x_offset_px + x_padding_px + x;
822 int dst_y = cell_y_offset_px + y_padding_px + y;
823
824 // Clip to cell boundaries (prevents bleeding into adjacent cells)
825 if (dst_x < cell_x_min || dst_x > cell_x_max || dst_y < cell_y_min ||
826 dst_y > cell_y_max) {
827 continue; // Skip pixels outside cell boundaries
828 }
829
830 // Additional composite boundary check
831 if (dst_x < 0 || dst_x >= composite->w || dst_y < 0 ||
832 dst_y >= composite->h) {
833 continue; // Skip pixels outside composite
834 }
835
836 // Copy pixel
837 int src_idx = (y * resized->w) + x;
838 int dst_idx = (dst_y * composite->w) + dst_x;
839 composite->pixels[dst_idx] = resized->pixels[src_idx];
840 }
841 }
842
843 image_destroy(resized);
844 }
845
846 return composite;
847}
848
849/* FNV-1a intentionally wraps at 64 bits; keep that defined hash operation
850 * out of integer-overflow sanitizer diagnostics. */
851#if defined(__clang__)
852__attribute__((no_sanitize("unsigned-integer-overflow")))
853#endif
854static uint64_t hash_client_id(const char *client_id) {
855 uint64_t hash = 1469598103934665603ULL;
856 for (const unsigned char *p = (const unsigned char *)client_id; *p; ++p) {
857 hash ^= *p;
858 hash *= 1099511628211ULL;
859 }
860 return hash ? hash : 1;
861}
862
863static void invalidate_changed_composite_owners(ascii_stabilizer_t *history,
864 image_source_t *sources,
865 int source_count,
866 int sources_with_video,
867 int width, int height) {
868 if (!history->cells || history->width != (size_t)width ||
869 sources_with_video <= 0 ||
870 (history->height != (size_t)height &&
871 history->height != (size_t)height * 2))
872 return;
873 size_t history_scale = history->height / (size_t)height;
874 int cols = 1, rows = 1;
875 if (sources_with_video > 1)
876 calculate_optimal_grid_layout(sources, source_count, sources_with_video,
877 width, height, &cols, &rows);
878 uint64_t owners[9] = {0};
879 int count = 0;
880 for (int i = 0; i < source_count && count < 9; ++i) {
881 if (!sources[i].has_video || !sources[i].image)
882 continue;
883 owners[count++] = hash_client_id(sources[i].client_id);
884 }
885 int cell_width = width / cols, cell_height = (height * 2) / rows;
886 if (!cell_width || !cell_height)
887 return;
888 for (size_t y = 0; y < history->height; ++y) {
889 for (int x = 0; x < width; ++x) {
890 int col = x / cell_width,
891 row = (int)((y * 2 / history_scale) / (size_t)cell_height);
892 int index = row * cols + col;
893 uint64_t owner =
894 col < cols && row < rows && index < count ? owners[index] : 0;
896 &history->cells[y * (size_t)width + (size_t)x];
897 if (cell->source_owner != owner)
898 cell->valid = false;
899 cell->source_owner = owner;
900 }
901 }
902}
903
913static char *convert_composite_to_ascii(
914 image_t *composite, const char *target_client_id, unsigned short width,
915 unsigned short height, acip_render_settings_t *out_rendering,
916 image_source_t *sources, int source_count, int sources_with_video) {
917 // LOCK OPTIMIZATION: Don't call find_client_by_id() - it would acquire rwlock
918 // unnecessarily Instead, the render thread already has snapshot of client
919 // state, so we just need palette data which is stable after initialization
920
921 // We need to find the client to access palette data, but we can do this
922 // without locking since palette is initialized once and never changes
923 client_info_t *render_client = NULL;
924
925 // Find client without locking - client_id is stable once set
926 for (int i = 0; i < MAX_CLIENTS; i++) {
927 client_info_t *client = &g_client_manager.clients[i];
928 if (strcmp(client->client_id, target_client_id) == 0) {
929 render_client = client;
930 break;
931 }
932 }
933
934 if (!render_client) {
935 SET_ERRNO(ERROR_INVALID_STATE, "Per-client %s: Target client not found",
936 target_client_id);
937 return NULL;
938 }
939
940 mutex_lock(&render_client->client_state_mutex);
941 bool ready = render_client->has_terminal_caps &&
942 render_client->client_palette_initialized;
943 acip_render_settings_t rendering = render_client->render_settings;
944 mutex_unlock(&render_client->client_state_mutex);
945 if (!ready) {
946 SET_ERRNO(ERROR_TERMINAL, "Client rendering is not configured");
947 return NULL;
948 }
949 if (out_rendering)
950 *out_rendering = rendering;
951 terminal_capabilities_t caps_snapshot = rendering.caps;
952 width = rendering.width;
953 height = rendering.height;
954 if (caps_snapshot.stabilize)
955 invalidate_changed_composite_owners(&render_client->render_stabilizer,
956 sources, source_count,
957 sources_with_video, width, height);
958 uint64_t convert_start_ns = time_get_ns();
959 char *ascii_frame = ascii_convert_with_buffers_stabilized(
960 composite, width, height, &caps_snapshot, true, false, rendering.palette,
961 false, NULL, NULL,
962 caps_snapshot.stabilize ? &render_client->render_stabilizer : NULL);
963 if (!caps_snapshot.stabilize)
965 uint64_t convert_end_ns = time_get_ns();
966 uint64_t convert_duration_ns = convert_end_ns - convert_start_ns;
967
968 if (convert_duration_ns > 5 * NS_PER_MS_INT) { // Log if > 5ms
969 char duration_str[TIME_DURATION_BUFFER_SIZE];
970 time_pretty((uint64_t)((double)convert_duration_ns), -1, duration_str,
971 sizeof(duration_str));
974 "SLOW_ASCII_CONVERT: Client %s took %s to convert %dx%d image to ASCII",
975 target_client_id, duration_str, composite->w, composite->h);
976 }
977
978 const bool matrix_rain =
979 (caps_snapshot.capabilities & TERM_CAP_MATRIX_RAIN) != 0;
980 if (matrix_rain && ascii_frame) {
981 if (!render_client->digital_rain ||
982 render_client->digital_rain->num_columns != width ||
983 render_client->digital_rain->num_rows != height) {
984 if (render_client->digital_rain) {
985 digital_rain_destroy(render_client->digital_rain);
986 }
987 render_client->digital_rain = digital_rain_init(width, height);
988 render_client->digital_rain_last_update_time =
989 (double)time_get_ns() / (double)NS_PER_SEC_INT;
990 }
991
992 if (render_client->digital_rain) {
993 const double now = (double)time_get_ns() / (double)NS_PER_SEC_INT;
994 const float elapsed =
995 (float)(now - render_client->digital_rain_last_update_time);
996 render_client->digital_rain_last_update_time = now;
998 caps_snapshot.color_filter);
999 char *rain_frame =
1000 digital_rain_apply(render_client->digital_rain, ascii_frame, elapsed);
1001 if (rain_frame) {
1002 SAFE_FREE(ascii_frame);
1003 ascii_frame = rain_frame;
1004 }
1005 }
1006 } else if (render_client->digital_rain) {
1007 digital_rain_destroy(render_client->digital_rain);
1008 render_client->digital_rain = NULL;
1009 }
1010
1011 if (ascii_frame && (size_t)utf8_display_width(rendering.palette) !=
1012 utf8_char_count(rendering.palette)) {
1013 // Normalize display-cell geometry (wide palettes and REP included) with the
1014 // same row composer as discovery/browser hosts.
1015 ascii_frame_source_t source = {.frame_data = ascii_frame,
1016 .frame_size = strlen(ascii_frame)};
1017 size_t size;
1018 char *rectangular = ascii_create_grid(&source, 1, width, height, &size);
1019 SAFE_FREE(ascii_frame);
1020 ascii_frame = rectangular;
1021 }
1022 return ascii_frame;
1023}
1024
1025/* ============================================================================
1026 * Per-Client Video Mixing and Frame Generation
1027 * ============================================================================
1028 */
1029
1125// Compute hash of all active video sources for cache invalidation
1126// Uses hardware-accelerated CRC32 for ultra-fast hashing
1128 const char *target_client_id, unsigned short width, unsigned short height,
1129 bool wants_stretch, size_t *out_size, bool *out_grid_changed,
1130 int *out_sources_count, acip_render_settings_t *out_rendering) {
1131 (void)wants_stretch; // Unused - we always handle aspect ratio ourselves
1132
1133 // Register the stream counter once even when per-client render workers enter
1134 // this function concurrently.
1135 static _Atomic bool stream_atomics_registered = false;
1136 if (!atomic_exchange_explicit(&stream_atomics_registered, true,
1137 memory_order_acq_rel)) {
1138 NAMED_REGISTER_ATOMIC(&g_previous_active_video_count,
1139 "server_video_source_count_for_layout_detection",
1140 NULL);
1141 }
1142
1143 uint64_t frame_gen_start_ns = time_get_ns();
1144
1145 // Initialize output parameters
1146 if (out_grid_changed) {
1147 *out_grid_changed = false;
1148 }
1149 if (out_sources_count) {
1150 *out_sources_count = 0;
1151 }
1152
1153 if (!out_size || width == 0 || height == 0) {
1155 "Invalid parameters: width=%u, height=%u, out_size=%p", width,
1156 height, out_size);
1157 return NULL;
1158 }
1159
1160 // Collect all active clients and their image sources
1161 image_source_t sources[MAX_CLIENTS];
1162 uint64_t collect_start_ns = time_get_ns();
1163 int source_count = collect_video_sources(sources, MAX_CLIENTS);
1164 uint64_t collect_end_ns = time_get_ns();
1165
1166 // Count sources that actually have video data
1167 int sources_with_video = 0;
1168 for (int i = 0; i < source_count; i++) {
1169 if (sources[i].has_video && sources[i].image) {
1170 sources_with_video++;
1171 }
1172 }
1173
1175 "FRAME_GEN_START: target_client=%s sources=%d collect=%.1fms",
1176 target_client_id, sources_with_video,
1177 (collect_end_ns - collect_start_ns) / NS_PER_MS);
1178
1179 // Return the source count for debugging/tracking
1180 if (out_sources_count) {
1181 *out_sources_count = sources_with_video;
1182 }
1183
1184 // GRID LAYOUT CHANGE DETECTION:
1185 // Check if the number of active video sources has changed
1186 // NOTE: We only UPDATE the count and SIGNAL the change via out parameter
1187 // Broadcasting CLEAR_CONSOLE must happen AFTER the new frames are written to
1188 // buffers to prevent race condition where CLEAR arrives before new frame is
1189 // ready
1190 uint64_t previous_count = atomic_load_u64(&g_previous_active_video_count);
1191 if (sources_with_video != (int)previous_count) {
1192 // Use compare-and-swap to ensure only ONE thread detects the change
1193 if (atomic_cas_u64(&g_previous_active_video_count, &previous_count,
1194 (uint64_t)sources_with_video)) {
1196 "Grid layout changing: %d -> %d active video sources - "
1197 "caller will broadcast clear AFTER buffering frame",
1198 previous_count, sources_with_video);
1199 if (out_grid_changed) {
1200 *out_grid_changed = true; // Signal to caller
1201 }
1202 }
1203 }
1204
1205 // No active video sources - don't generate placeholder frames
1206 image_t *composite = NULL;
1207
1208 if (sources_with_video == 0) {
1209 *out_size = 0;
1210 // No active video sources for client - this isn't an error.
1211 // Return NULL to indicate no frame should be sent
1212 return NULL;
1213 }
1214
1215 if (sources_with_video == 1) {
1216 // Single source handling - create composite and convert to ASCII
1217 // Note: create_single_source_composite returns a reference to
1218 // sources[i].image which could be modified by other threads. Make a copy to
1219 // prevent concurrent modification during ascii_convert_with_capabilities.
1220 image_t *single_source = create_single_source_composite(
1221 sources, source_count, target_client_id, width, height);
1222 if (single_source) {
1223 composite = image_new_copy(single_source);
1224 if (!composite) {
1225 SET_ERRNO(ERROR_MEMORY, "Failed to copy single source composite");
1226 *out_size = 0;
1227 return NULL;
1228 }
1229 }
1230 } else {
1231 // Multiple sources - create grid layout
1232 composite =
1233 create_multi_source_composite(sources, source_count, sources_with_video,
1234 target_client_id, width, height);
1235 }
1236
1237 char *out = NULL;
1238
1239 if (!composite) {
1241 "Per-client %s: Failed to create composite image",
1242 target_client_id);
1243 *out_size = 0;
1244 return NULL;
1245 }
1246
1247 // Convert composite to ASCII using client capabilities
1248 // Pass terminal dimensions so the frame can be padded to full width
1249 char *ascii_frame = convert_composite_to_ascii(
1250 composite, target_client_id, width, height, out_rendering, sources,
1251 source_count, sources_with_video);
1252
1253 if (ascii_frame) {
1254 // The frame should have been null-terminated by the padding functions.
1255 // Use strlen() which is optimized and reliable
1256 size_t ascii_len = strlen(ascii_frame);
1257
1258 // Safety check: don't accept unreasonably large frames (10MB limit)
1259 if (ascii_len > 10 * 1024 * 1024) {
1260 log_error(
1261 "Frame size exceeds 10MB safety limit (possible buffer overflow)");
1262 SET_ERRNO(ERROR_INVALID_PARAM, "Frame size exceeds 10MB");
1263 SAFE_FREE(ascii_frame);
1264 image_destroy(composite);
1265 *out_size = 0;
1266 return NULL;
1267 }
1268
1269 *out_size = ascii_len; // Renderer owns complete rows; never truncate to a
1270 // color reset.
1271
1272 log_dev_every(LOG_RATE_SLOW, "Final frame size=%zu bytes for client %s",
1273 *out_size, target_client_id);
1274
1275 // Debug: Log the last 50 bytes of the frame to see what's really there
1276 if (*out_size >= 50) {
1277 char hex_buf[SERVER_STREAM_HEX_BUFFER_SIZE] = {0};
1278 size_t hex_len = 0;
1279 const uint8_t *last_bytes =
1280 (const uint8_t *)ascii_frame + (*out_size - 50);
1281 for (int i = 0; i < 50 && hex_len < sizeof(hex_buf) - 5; i++) {
1282 hex_len += snprintf(hex_buf + hex_len, sizeof(hex_buf) - hex_len,
1283 "%02X ", last_bytes[i]);
1284 }
1285 log_dev_every(4500 * US_PER_MS_INT, "FRAME_LAST_50_BYTES (hex): %s",
1286 hex_buf);
1287
1288 // Also log as ASCII for readability
1289 char ascii_buf[SERVER_STREAM_ASCII_BUFFER_SIZE] = {0};
1290 for (int i = 0; i < 50 && i < (int)sizeof(ascii_buf) - 1; i++) {
1291 if (last_bytes[i] >= 32 && last_bytes[i] < 127) {
1292 ascii_buf[i] = (char)last_bytes[i];
1293 } else if (last_bytes[i] == '\n') {
1294 ascii_buf[i] = 'N';
1295 } else if (last_bytes[i] == '\0') {
1296 ascii_buf[i] = '0';
1297 } else {
1298 ascii_buf[i] = '.';
1299 }
1300 }
1301 log_dev_every(4500 * US_PER_MS_INT, "FRAME_LAST_50_ASCII: %s", ascii_buf);
1302 }
1303
1304 out = ascii_frame;
1305 } else {
1306 SET_ERRNO(ERROR_TERMINAL, "Per-client %s: Failed to convert image to ASCII",
1307 target_client_id);
1308 *out_size = 0;
1309 }
1310
1311 if (composite) {
1312 image_destroy(composite);
1313 }
1314 for (int i = 0; i < source_count; i++) {
1315 if (sources[i].image) {
1316 image_destroy(sources[i].image);
1317 }
1318 }
1319
1320 uint64_t frame_gen_end_ns = time_get_ns();
1321 uint64_t frame_gen_duration_ns = frame_gen_end_ns - frame_gen_start_ns;
1322 if (frame_gen_duration_ns > 10 * NS_PER_MS_INT) { // Log if > 10ms
1323 char duration_str[TIME_DURATION_BUFFER_SIZE];
1324 time_pretty((uint64_t)((double)frame_gen_duration_ns), -1, duration_str,
1325 sizeof(duration_str));
1327 "SLOW_FRAME_GENERATION: Client %s full frame gen took %s",
1328 target_client_id, duration_str);
1329 }
1330
1331 return out;
1332}
1333
1334/* ============================================================================
1335 * Frame Queuing and Delivery Functions
1336 * ============================================================================
1337 */
1338
1397
1412 // LOCK OPTIMIZATION: Don't acquire rwlock - all fields we access are atomic
1413 // client_id, active, is_sending_video are all atomic variables
1414
1415 // Iterate through all client slots
1416 for (int i = 0; i < MAX_CLIENTS; i++) {
1417 client_info_t *client = &g_client_manager.clients[i];
1418
1419 // Skip uninitialized clients (atomic read)
1420 if (client->client_id[0] == '\0') {
1421 continue;
1422 }
1423
1424 // Check if client is active and sending video (both atomic reads)
1425 bool is_active = atomic_load_bool(&client->active);
1426 bool is_sending = atomic_load_bool(&client->is_sending_video);
1427
1428 if (is_active && is_sending) {
1429 return true;
1430 }
1431 }
1432
1433 return false;
1434}
char * ascii_convert_with_buffers_stabilized(const image_t *original, const ssize_t width, const ssize_t height, const terminal_capabilities_t *caps, const bool use_aspect_ratio, const bool stretch, const char *palette_chars, const bool contain, image_t **workspace, outbuf_t *output, ascii_stabilizer_t *stabilizer)
Definition ascii.c:282
#define SET_ERRNO(code,...)
#define CHAR_ASPECT
📐 Aspect Ratio Calculation Functions
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
#define buffer_release(data)
Definition buffer.h:108
Named object registry for debugging — log identifiable resource names.
Matrix-style digital rain effect for ASCII frames.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U32(val)
Definition endian.h:85
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:32
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define read_u32_unaligned
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_TERMINAL
Definition error_codes.h:68
#define MAX_CLIENTS
Maximum possible clients (static array size) - actual runtime limit set by –max-clients (1-128).
#define MAX_CLIENT_ID_LEN
Maximum client ID length - format: "noun.N (transport:port)" e.g., "mountain.0 (tcp:48036)".
#define LOG_RATE_SLOW
Log rate limit: 10 seconds (10,000,000 microseconds).
Definition log_rates.h:41
#define LOG_RATE_DEFAULT
Log rate limit: 5 seconds (5,000,000 microseconds) - default for audio/video packets.
Definition log_rates.h:38
#define LOG_RATE_NORMAL
Log rate limit: 3 seconds (3,000,000 microseconds).
Definition log_rates.h:34
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
#define NS_PER_SEC_INT
Definition time.h:173
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define NS_PER_MS_INT
Definition time.h:172
#define NS_PER_MS
Definition time.h:163
#define US_PER_MS_INT
Definition time.h:176
#define US_PER_SEC_INT
Definition time.h:177
int utf8_display_width(const char *str)
Calculate terminal display width of a UTF-8 string.
Definition utf8.c:102
size_t utf8_char_count(const char *str)
Count UTF-8 characters (not bytes).
Definition utf8.c:112
struct client_info client_info_t
image_t * image_new_copy(const image_t *source)
Create a copy of an existing image.
void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter)
Set digital rain color from color filter.
void image_clear(image_t *p)
Clear image (set all pixels to black).
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 image_resize(const image_t *s, image_t *d)
Resize image using nearest-neighbor interpolation.
digital_rain_t * digital_rain_init(int num_columns, int num_rows)
Initialize digital rain effect context.
char * ascii_create_grid(ascii_frame_source_t *sources, int source_count, int width, int height, size_t *out_size)
Create a grid layout from multiple ASCII frames.
Definition ascii.c:708
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define ascii_stabilizer_reset
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:716
🔢 Mathematical Utility Functions
static bool size_t index
Definition queries.h:10
static bool size_t gotel_query_t * out
Definition queries.h:10
Lock-Free Ring Buffer and Frame Buffer Management.
rwlock_t g_client_manager_rwlock
Reader-writer lock protecting the global client manager.
bool g_client_manager_rwlock_initialized
client_manager_t g_client_manager
Hash table entry for client packet dispatch.
Per-client state management and lifecycle orchestration.
bool any_clients_sending_video(void)
Queue ASCII frame for delivery to specific client.
#define SERVER_STREAM_HEX_BUFFER_SIZE
#define SERVER_STREAM_ASCII_BUFFER_SIZE
char * create_mixed_ascii_frame_for_client(const char *target_client_id, unsigned short width, unsigned short height, bool wants_stretch, size_t *out_size, bool *out_grid_changed, int *out_sources_count, acip_render_settings_t *out_rendering)
Generate personalized ASCII frame for a specific client.
Multi-client video mixing and ASCII frame generation.
🔤 String Manipulation and Shell Escaping Utilities
acip render settings keeps the values that move through the subsystem: caps, width,...
Frame source structure for grid layout.
Definition ascii.h:350
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
acip_render_settings_t render_settings
video_frame_buffer_t * incoming_video_buffer
ascii_stabilizer_t render_stabilizer
char client_id[MAX_CLIENT_ID_LEN]
int num_rows
Number of rows in grid.
int num_columns
Number of columns in grid.
One client's video input as seen by the compositor.
bool has_video
Whether this client has active video stream.
image_t * image
Pointer to client's current video frame (owned by buffer system).
char client_id[MAX_CLIENT_ID_LEN]
Unique client identifier for this source.
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).
One variable-length payload in the video ring buffer.
Definition ringbuffer.h:419
char * data
Owning frame payload; release with buffer_release() after reading.
Definition ringbuffer.h:431
uint32_t timestamp
Timestamp when frame was captured.
Definition ringbuffer.h:427
size_t size
Actual size of frame data in bytes.
Definition ringbuffer.h:429
char source_client_id[MAX_CLIENT_ID_LEN]
Client ID that sent this frame.
Definition ringbuffer.h:423
One captured, decoded, or rendered video frame and its timing metadata.
mutex_t swap_mutex
Brief mutex for pointer swap only.
atomic_t new_frame_available
Atomic flag: true when new frame available.
size_t allocated_buffer_size
Size of allocated data buffers (for cleanup).
video_frame_t * front_buffer
Currently displayed frame (reader owns).
When code needs to work with simple frame swap, it keeps current_frame, frame_a, frame_b,...
size_t size
Size of frame data in bytes.
uint64_t capture_timestamp_ns
Timestamp when frame was captured (nanoseconds).
void * data
Frame data pointer (points to pre-allocated buffer).
⏱️ High-precision timing utilities using sokol_time.h and uthash
🔤 UTF-8 Encoding and Decoding Utilities
asciichat_error_t image_validate_dimensions(size_t width, size_t height)
Validate image dimensions (non-zero, within limits).
Definition util/image.c:116
asciichat_error_t image_calc_rgb_size(size_t width, size_t height, size_t *out_size)
Calculate total RGB buffer size from dimensions.
Definition util/image.c:64
🖼️ Safe overflow-checked buffer size calculations for images and video frames