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/render.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define SERVER_RENDER_THREAD_DISPLAY_NAME_BUFFER_SIZE 64
4#define SERVER_RENDER_THREAD_NAME_BUFFER_SIZE 64
5
7#include <ascii-chat/otel.h>
9/* Per-client video conversion and audio mixing. Render workers submit media
10 * to the shared ACIP scheduler and are joined before connection destruction. */
11
12#include <errno.h>
13#include <math.h>
14#include <stdio.h>
15#include <string.h>
16#include <time.h>
17
18#include "client.h"
19#include "connections.h"
20#include "main.h"
21#include "protocol.h"
22#include "render.h"
23#include "stream.h"
28#include <ascii-chat/common.h>
33#include <ascii-chat/util/fps.h>
35#include <libplatform/compiler.h>
36#include <libplatform/system.h>
37#include <libplatform/terminal.h>
38#include <options/options.h>
39#include <options/rcu.h> // For RCU-based options access
40
41/* ============================================================================
42 * Cross-Platform Utility Functions
43 * ============================================================================
44 */
45
95
96// Removed interruptible_usleep - using regular platform_sleep_us instead
97// Sleep interruption isn't needed for small delays and isn't truly possible
98// anyway
99
100/* ============================================================================
101 * Per-Client Video Rendering Implementation
102 * ============================================================================
103 */
104
204
206 acip_frame_workspace_t event_workspace = {0};
207 client_info_t *client = (client_info_t *)arg;
208 if (!client) {
209 log_error("NULL client pointer in video render thread");
210 return NULL;
211 }
212
213 // Take snapshot of client ID and socket at start to avoid race conditions
214 char thread_client_id[MAX_CLIENT_ID_LEN];
215 SAFE_STRNCPY(thread_client_id, client->client_id,
216 sizeof(thread_client_id) - 1);
217 bool is_webrtc =
218 acip_transport_get_type(client->transport) == ACIP_TRANSPORT_WEBRTC;
219 (void)is_webrtc; // May be unused in release builds
220
221 log_debug("Video render thread: client_id=%s, webrtc=%d", thread_client_id,
222 is_webrtc);
223
224 log_debug("[VIDEO_RENDER_THREAD_START] ★★★ LOCK STATE at thread entry for "
225 "client %s",
226 thread_client_id);
227 // debug_sync_print_state(); // Disabled: causes AddressSanitizer
228 // stack-use-after-return crash
229
230 // Wait for client to send terminal capabilities before rendering
231 // Without capabilities, convert_composite_to_ascii() will fail
232 int timeout_ms = 5000;
233 int waited_ms = 0;
234 while (!client->has_terminal_caps && !atomic_load_bool(&g_should_exit) &&
235 !atomic_load_bool(&client->shutting_down)) {
236 if (waited_ms == 0) {
237 log_debug("Waiting for terminal capabilities from client %s...",
238 thread_client_id);
239 }
240 APP_CALLBACK_VOID(platform_pump_events);
241 platform_sleep_ms(10);
242 waited_ms += 10;
243 if (waited_ms >= timeout_ms) {
244 log_debug("Still waiting for terminal capabilities from client %s",
245 thread_client_id);
246 waited_ms = 0;
247 }
248 }
249 if (client->has_terminal_caps) {
250 log_debug("Received terminal capabilities for client %s after %dms",
251 thread_client_id, waited_ms);
252 }
253
254 // Get client's desired FPS from capabilities or use default
255 int client_fps = VIDEO_RENDER_FPS; // Default to 60 FPS
256 // Use snapshot pattern to avoid mutex in render thread
257 bool has_caps = client->has_terminal_caps;
258 int desired_fps = has_caps ? client->terminal_caps.desired_fps : 0;
259 if (has_caps && desired_fps > 0) {
260 client_fps = desired_fps;
261 log_debug("Client %s requested FPS: %d (has_caps=%d, desired_fps=%d)",
262 thread_client_id, client_fps, has_caps, desired_fps);
263 } else {
264 log_debug("Client %s using default FPS: %d (has_caps=%d, desired_fps=%d)",
265 thread_client_id, client_fps, has_caps, desired_fps);
266 }
267
268 int base_frame_interval_ms = 1000 / client_fps;
269 log_debug("Client %s render interval: %dms (%d FPS)", thread_client_id,
270 base_frame_interval_ms, client_fps);
271
272 // FPS tracking for video render thread
273 fps_t video_fps_tracker = {0};
274 fps_init(&video_fps_tracker, client_fps, "SERVER VIDEO");
275
276 uint64_t frame_interval_ns = NS_PER_SEC_INT / (uint64_t)client_fps;
277 uint64_t next_frame_ns = time_get_ns() + frame_interval_ns;
278 bool last_has_sources = false;
279 uint32_t frame_gen_count = 0;
280 uint64_t frame_gen_start_time = 0;
281 uint64_t render_rate_window_start_ns = time_get_ns();
282 uint64_t rendered_frames_in_window = 0;
283 uint64_t missed_deadlines_in_window = 0;
284
285 log_debug("Video render loop STARTING for client %s", thread_client_id);
286
287 bool should_continue = true;
288 while (should_continue && !atomic_load_bool(&g_should_exit) &&
289 !atomic_load_bool(&client->shutting_down)) {
290 ASCII_OTEL_SCOPE(SERVER_VIDEO);
292 "Video render loop iteration for client %s",
293 thread_client_id);
294
295 // Check for immediate shutdown
297 log_debug("Video render thread stopping for client %s (g_should_exit)",
298 thread_client_id);
299 break;
300 }
301
302 bool video_running = atomic_load_bool(&client->video_render_thread_running);
303 bool active = atomic_load_bool(&client->active);
304 bool shutting_down = atomic_load_bool(&client->shutting_down);
305
306 should_continue = video_running && active && !shutting_down;
307
308 if (!should_continue) {
309 log_debug("Video render thread stopping for client %s "
310 "(should_continue=false: video_running=%d, active=%d, "
311 "shutting_down=%d)",
312 thread_client_id, video_running, active, shutting_down);
313 break;
314 }
315
316 // SETTINGS_SYNC can change the viewer's requested render rate while this
317 // thread is alive. Read the published capabilities under the same mutex
318 // used by publish_render_settings(), then restart the cadence from now so
319 // a rate change cannot produce a burst of catch-up frames.
320 int requested_fps = 0;
321 mutex_lock(&client->client_state_mutex);
322 requested_fps = client->terminal_caps.desired_fps;
323 mutex_unlock(&client->client_state_mutex);
324 if (requested_fps > 0 && requested_fps != client_fps) {
325 client_fps = requested_fps;
326 frame_interval_ns = NS_PER_SEC_INT / (uint64_t)client_fps;
327 next_frame_ns = time_get_ns() + frame_interval_ns;
328 fps_init(&video_fps_tracker, client_fps, "SERVER VIDEO");
329 log_debug("Client %s updated render interval: %llums (%d FPS)",
330 thread_client_id,
331 (unsigned long long)(frame_interval_ns / NS_PER_MS_INT),
332 client_fps);
333 }
334
335 // Processing consumes part of the frame interval. Sleep only until the
336 // scheduled deadline, and skip missed deadlines without a catch-up burst.
337 uint64_t iter_start_ns = time_get_ns();
338 if (iter_start_ns < next_frame_ns) {
339 platform_sleep_ns(next_frame_ns - iter_start_ns);
340 }
341 uint64_t after_sleep_ns = time_get_ns();
342 uint64_t elapsed_intervals =
343 after_sleep_ns >= next_frame_ns
344 ? (after_sleep_ns - next_frame_ns) / frame_interval_ns + 1
345 : 1;
346 if (elapsed_intervals > 1) {
347 missed_deadlines_in_window += elapsed_intervals - 1;
348 }
349 next_frame_ns += elapsed_intervals * frame_interval_ns;
350
351 // Capture timestamp for FPS tracking and frame timestamps
352 uint64_t current_time_ns = time_get_ns();
353
354 // Check thread state again before acquiring locks (client might have been
355 // destroyed during sleep).
356 should_continue = atomic_load_bool(&client->video_render_thread_running) &&
357 atomic_load_bool(&client->active) &&
359 if (!should_continue) {
360 break;
361 }
362
363 // Optimization: No mutex needed - all fields are atomic or stable.
364 // client_id: stable string pointer
365 // width/height: stable uint16_t values (set once, never modified)
366 // active: atomic_t - use atomic_load for thread safety
367 const char *client_id_snapshot = client->client_id; // Stable read
368 unsigned short width_snapshot = client->width; // Stable uint16_t
369 unsigned short height_snapshot = client->height; // Stable uint16_t
370 bool active_snapshot = atomic_load_bool(&client->active); // Atomic read
371
372 // Check if client is still active after getting snapshot
373 if (!active_snapshot) {
374 break;
375 }
376
377 // Phase 2 IMPLEMENTED: Generate frame specifically for THIS client using
378 // snapshot data
379 size_t frame_size = 0;
380
381 // Check if any clients are sending video
382 bool has_video_sources = any_clients_sending_video();
383
384 // DIAGNOSTIC: Track when video sources become available
385 if (has_video_sources != last_has_sources) {
386 log_debug("Client %s video sources: %s", thread_client_id,
387 has_video_sources ? "AVAILABLE" : "UNAVAILABLE");
388 last_has_sources = has_video_sources;
389 }
390
392 "Video render iteration for client %s: "
393 "has_video_sources=%d, width=%u, height=%u",
394 thread_client_id, has_video_sources, width_snapshot,
395 height_snapshot);
396
397 // Use default dimensions if client dimensions not received
398 if (width_snapshot == 0 || height_snapshot == 0) {
400 "Using default dimensions for client %s (client reported: "
401 "width=%u, height=%u)",
402 thread_client_id, width_snapshot, height_snapshot);
403 // Use 80x25 as standard terminal size fallback for snapshot/test clients
404 width_snapshot = 80;
405 height_snapshot = 25;
406 }
407
408 // Generate frames for all clients with valid dimensions, regardless of
409 // whether other clients are sending video. This ensures WebSocket snapshot
410 // clients (receive-only mode) receive frames even when no other clients are
411 // sending video.
412 int sources_count = 0; // Track number of video sources in this frame
413
414 // DIAGNOSTIC: Track every frame generation attempt
415 frame_gen_count++;
416 if (frame_gen_count == 1) {
417 frame_gen_start_time = current_time_ns;
418 }
419
420 // Log every 120 attempts (should be ~2 seconds at 60 Hz)
421 if (frame_gen_count % 120 == 0) {
422 uint64_t elapsed_ns = current_time_ns - frame_gen_start_time;
423 double gen_fps = (120.0 / (elapsed_ns / (double)NS_PER_SEC_INT));
424 log_dev("render loop: client=%s fps=%.1f", thread_client_id, gen_fps);
425 }
426
428 "About to call create_mixed_ascii_frame_for_client for "
429 "client %s with dims %ux%u",
430 thread_client_id, width_snapshot, height_snapshot);
431
432 // debug_sync_print_state() is too expensive to call every frame (kills FPS)
433
434 uint64_t frame_create_start_ns = time_get_ns();
435 acip_render_settings_t frame_rendering = {0};
436 char *ascii_frame = create_mixed_ascii_frame_for_client(
437 client_id_snapshot, width_snapshot, height_snapshot, false, &frame_size,
438 NULL, &sources_count, &frame_rendering);
439 uint64_t frame_create_end_ns = time_get_ns();
440 if (sources_count > 0) {
442 frame_create_end_ns - frame_create_start_ns);
446 1);
447 }
448
449 if (frame_gen_count % 120 == 0) {
450 char sleep_str[TIME_DURATION_BUFFER_SIZE],
451 create_str[TIME_DURATION_BUFFER_SIZE];
452 time_pretty((uint64_t)(after_sleep_ns - iter_start_ns), -1, sleep_str,
453 sizeof(sleep_str));
454 time_pretty((uint64_t)(frame_create_end_ns - frame_create_start_ns), -1,
455 create_str, sizeof(create_str));
456 log_dev("render timing: adaptive_sleep=%s frame_create=%s", sleep_str,
457 create_str);
458 }
459
460 // Always send frames at configured FPS, even if no external video sources
461 // yet This ensures single-client mode (like testing) still gets continuous
462 // frames The frame data (animated background or test pattern) is still
463 // valid content
464
465 if (ascii_frame && frame_size > 0) {
466 server_send_video(client, &event_workspace, ascii_frame, frame_size,
467 frame_rendering.width, frame_rendering.height,
468 sources_count, &frame_rendering);
469 fps_frame_ns(&video_fps_tracker, current_time_ns, "frame rendered");
470 rendered_frames_in_window++;
471 uint64_t render_rate_now_ns = time_get_ns();
472 uint64_t render_rate_elapsed_ns =
473 render_rate_now_ns - render_rate_window_start_ns;
474 if (render_rate_elapsed_ns >= NS_PER_SEC_INT) {
475 double render_fps = (double)rendered_frames_in_window * NS_PER_SEC_INT /
476 (double)render_rate_elapsed_ns;
477 if (render_fps < (double)client_fps * 0.9 ||
478 missed_deadlines_in_window > 0) {
479 log_warn("Server video render lagging client=%s fps=%.1f target=%d "
480 "missed_deadlines=%llu",
481 thread_client_id, render_fps, client_fps,
482 (unsigned long long)missed_deadlines_in_window);
483 } else {
484 log_debug("Server video render client=%s fps=%.1f target=%d "
485 "missed_deadlines=0",
486 thread_client_id, render_fps, client_fps);
487 }
488 render_rate_window_start_ns = render_rate_now_ns;
489 rendered_frames_in_window = 0;
490 missed_deadlines_in_window = 0;
491 }
492 SAFE_FREE(ascii_frame);
493 }
494
495 uint64_t iter_end_ns = time_get_ns();
496 if (frame_gen_count % 120 == 0) {
497 char total_str[TIME_DURATION_BUFFER_SIZE];
498 time_pretty((uint64_t)(iter_end_ns - iter_start_ns), -1, total_str,
499 sizeof(total_str));
500 log_warn_every(US_PER_SEC_INT, " TIMING: TOTAL_ITERATION=%s", total_str);
501 }
502 STOP_TIMER_AND_LOG(dev, 0, "render_iteration",
503 "render_iteration completed (total)");
504 }
505
506#ifdef DEBUG_THREADS
507 log_debug("Video render thread stopped for client %s", thread_client_id);
508#endif
509 acip_frame_workspace_destroy(&event_workspace);
510
511 // Clean up thread-local error context before exit
512
513 return NULL;
514}
515
516/* ============================================================================
517 * Per-Client Audio Rendering Implementation
518 * ============================================================================
519 */
520
626
628 client_info_t *client = (client_info_t *)arg;
629
630 if (!client) {
631 log_error("Invalid client info in audio render thread");
632 return NULL;
633 }
634
635 // Take snapshot of client ID and display name at start to avoid race
636 // conditions
637 char thread_client_id[MAX_CLIENT_ID_LEN];
638 SAFE_STRNCPY(thread_client_id, client->client_id,
639 sizeof(thread_client_id) - 1);
640 char thread_display_name[SERVER_RENDER_THREAD_DISPLAY_NAME_BUFFER_SIZE];
641 bool is_webrtc =
642 acip_transport_get_type(client->transport) == ACIP_TRANSPORT_WEBRTC;
643 (void)is_webrtc; // May be unused in release builds
644
645 // LOCK OPTIMIZATION: Only need client_state_mutex, not global rwlock
646 // We already have a stable client pointer
647 mutex_lock(&client->client_state_mutex);
648 SAFE_STRNCPY(thread_display_name, client->display_name,
649 sizeof(thread_display_name));
650 mutex_unlock(&client->client_state_mutex);
651
652#ifdef DEBUG_THREADS
653 log_debug("Audio render thread started for client %s (%s), webrtc=%d",
654 thread_client_id, thread_display_name, is_webrtc);
655#endif
656
657 // Mix buffer: up to OPUS_FRAME_SAMPLES samples for adaptive reading
658 // Normal: 480 samples = 10ms @ 48kHz
659 // Catchup: OPUS_FRAME_SAMPLES samples = 20ms when buffers are filling up
660 float mix_buffer[OPUS_FRAME_SAMPLES * AUDIO_CHANNELS];
661
662 // Opus frame accumulation buffer (OPUS_FRAME_SAMPLES samples = 20ms @ 48kHz)
663 // Opus requires minimum 480 samples, OPUS_FRAME_SAMPLES is optimal for 20ms
664 // frames
665 float opus_frame_buffer[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)];
666 int opus_frame_accumulated = 0;
667
668 // Create an Opus encoder for the interleaved stereo stream.
671 if (!opus_encoder) {
672 log_error(
673 "Failed to create Opus encoder for audio render thread (client %s)",
674 thread_client_id);
675 return NULL;
676 }
677
678 // FPS tracking for audio render thread
679 fps_t audio_fps_tracker = {0};
680 fps_init(&audio_fps_tracker, AUDIO_PACKET_FPS, "SERVER AUDIO");
681
682 // Per-thread counters (NOT static - each thread instance gets its own)
683 int server_audio_frame_count = 0;
684
685 bool should_continue = true;
686 uint64_t audio_deadline = time_get_ns();
687 while (should_continue && !atomic_load_bool(&g_should_exit) &&
688 !atomic_load_bool(&client->shutting_down)) {
689 ASCII_OTEL_SCOPE(SERVER_AUDIO);
690 log_debug_every(LOG_RATE_SLOW, "Audio render loop iteration for client %s",
691 thread_client_id);
692
693 // Check for immediate shutdown
695 log_debug("Audio render thread stopping for client %s (g_should_exit)",
696 thread_client_id);
697 break;
698 }
699
700 // Check thread state before acquiring any locks to prevent
701 // use-after-destroy. If we acquire locks after client is being destroyed,
702 // we'll crash with SIGSEGV
703 should_continue =
704 (((int)atomic_load_bool(&client->audio_render_thread_running) != 0) &&
705 ((int)atomic_load_bool(&client->active) != 0) &&
707
708 if (!should_continue) {
709 log_debug(
710 "Audio render thread stopping for client %s (should_continue=false)",
711 thread_client_id);
712 break;
713 }
714
715 if (!g_audio_mixer) {
717 "Audio render waiting for mixer (client %s)",
718 thread_client_id);
719 // Check shutdown flag while waiting
721 break;
722 platform_sleep_ns(10 * NS_PER_MS_INT);
723 continue;
724 }
725
726 // There is no mixed audio to send when this is the only registered
727 // source. Avoid entering the mixer just to discover that exclusion; this
728 // is the common single-client server case.
730 audio_deadline += 20 * NS_PER_MS_INT;
731 uint64_t idle_now = time_get_ns();
732 if (audio_deadline > idle_now)
733 platform_sleep_ns(audio_deadline - idle_now);
734 else
735 audio_deadline = idle_now;
736 continue;
737 }
738
739 const char *client_id_snapshot = client->client_id;
740 if (!atomic_load_bool(&client->active))
741 break;
742
743 // Create mix excluding THIS client's audio using snapshot data
744
745 // Mix one complete Opus frame per iteration. This keeps the source lock at
746 // the packet cadence instead of reacquiring it twice for every 20 ms of
747 // audio, while preserving the exact frame boundary required by the codec.
748 int samples_to_read = OPUS_FRAME_SAMPLES * AUDIO_CHANNELS;
749
750 int samples_mixed = 0;
751 uint32_t client_id_hash = fnv1a_hash_string(client_id_snapshot);
752 uint64_t stats_mix_start = time_get_ns();
753 samples_mixed = mixer_process_excluding_source(
754 g_audio_mixer, mix_buffer, samples_to_read, client_id_hash);
756 time_get_ns() - stats_mix_start);
757
759 "Audio render for client %s: samples_mixed=%d",
760 client_id_snapshot, samples_mixed);
761
762 // Accumulate all samples (including 0 or partial) until we have a full Opus
763 // frame This maintains continuous stream without silence padding
764
765 int space_available =
766 (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS) - opus_frame_accumulated;
767 int samples_to_copy =
768 (samples_mixed <= space_available) ? samples_mixed : space_available;
769
770 // Only copy if we have samples, otherwise just wait for next frame
771 if (samples_to_copy > 0) {
773 opus_frame_buffer + opus_frame_accumulated,
774 ((OPUS_FRAME_SAMPLES * AUDIO_CHANNELS) - opus_frame_accumulated) *
775 sizeof(float),
776 mix_buffer, samples_to_copy * sizeof(float));
777 opus_frame_accumulated += samples_to_copy;
778 }
779
780 // Only encode and send when we have accumulated a full Opus frame
781 if (opus_frame_accumulated >= (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)) {
782 // Encode accumulated Opus frame (OPUS_FRAME_SAMPLES samples = 20ms @
783 // 48kHz)
784 uint8_t
785 opus_buffer[AUDIO_OPUS_SERVER_PACKET_CAPACITY]; // Max Opus frame size
786
787 int opus_size = (int)opus_codec_encode(
788 opus_encoder, opus_frame_buffer, OPUS_FRAME_SAMPLES * AUDIO_CHANNELS,
789 opus_buffer, sizeof(opus_buffer));
790
791 // DEBUG: Log mix buffer and encoding results to see audio levels being
792 // sent
793 {
794 float peak = 0.0f, rms = 0.0f;
795 for (int i = 0; i < (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS); i++) {
796 float abs_val = fabsf(opus_frame_buffer[i]);
797 if (abs_val > peak)
798 peak = abs_val;
799 rms += opus_frame_buffer[i] * opus_frame_buffer[i];
800 }
801 rms = sqrtf(rms / (OPUS_FRAME_SAMPLES * AUDIO_CHANNELS));
802 // NOTE: server_audio_frame_count is now per-thread (not static), so
803 // each client thread has its own counter
804 server_audio_frame_count++;
805 if (server_audio_frame_count <= 5 ||
806 server_audio_frame_count % 20 == 0) {
807 // Log first 4 samples to verify they look like valid audio (not
808 // NaN/Inf/garbage)
810 "Server audio frame #%d for client %s: "
811 "samples_mixed=%d, Peak=%.6f, RMS=%.6f, opus_size=%d, "
812 "first4=[%.4f,%.4f,%.4f,%.4f]",
813 server_audio_frame_count, client_id_snapshot,
814 samples_mixed, peak, rms, opus_size,
815 opus_frame_buffer[0], opus_frame_buffer[1],
816 opus_frame_buffer[2], opus_frame_buffer[3]);
817 }
818 }
819
820 // Always reset accumulation buffer after attempting to encode - we've
821 // consumed these samples If we don't reset, new audio samples would be
822 // dropped while stale data sits in the buffer
823 opus_frame_accumulated = 0;
824
825 if (opus_size <= 0) {
828 "Failed to encode audio to Opus for client %s: opus_size=%d",
829 client_id_snapshot, opus_size);
830 } else {
831 // Wrap Opus data in proper batch packet format for client parsing:
832 // Header: sample_rate (4B) + frame_duration (4B) + frame_count (4B)
833 // Frame sizes: frame_count * 2B (one uint16 per frame with Opus data
834 // size) Opus data: raw encoded audio
835
836 // Fixed values for Opus encoding (standard 48kHz, OPUS_FRAME_SAMPLES
837 // samples per frame = 20ms)
838 const uint32_t sample_rate = AUDIO_SAMPLE_RATE;
839 const uint32_t frame_duration =
840 CLIENT_AUDIO_PIPELINE_FRAME_MS; // milliseconds (OPUS_FRAME_SAMPLES
841 // samples / 48kHz = 20ms)
842 const uint32_t frame_count = 1; // one Opus frame per packet
843 const uint16_t frame_size = (uint16_t)opus_size;
844
845 // Calculate total packet size: 16-byte header + frame_sizes + opus data
846 const size_t header_size = 16; // 4 uint32s (sample_rate,
847 // frame_duration, frame_count, reserved)
848 const size_t frame_sizes_size = (size_t)frame_count * sizeof(uint16_t);
849 const size_t total_packet_size =
850 header_size + frame_sizes_size + (size_t)opus_size;
851
852 // Allocate buffer for the complete packet
853 uint8_t *packet_buffer = SAFE_MALLOC(total_packet_size, uint8_t *);
854 if (!packet_buffer) {
855 log_error("Failed to allocate Opus batch packet buffer for client %s "
856 "(size=%zu)",
857 client_id_snapshot, total_packet_size);
858 } else {
859 // Build header in network byte order
860 uint8_t *ptr = packet_buffer;
861
862 // Write sample_rate (4 bytes, network byte order)
863 uint32_t sr_net = htonl(sample_rate);
864 memcpy(ptr, &sr_net, 4);
865 ptr += 4;
866
867 // Write frame_duration (4 bytes, network byte order)
868 uint32_t fd_net = htonl(frame_duration);
869 memcpy(ptr, &fd_net, 4);
870 ptr += 4;
871
872 // Write frame_count (4 bytes, network byte order)
873 uint32_t fc_net = htonl(frame_count);
874 memcpy(ptr, &fc_net, 4);
875 ptr += 4;
876
877 // Write reserved field (4 bytes, all zeros)
878 uint32_t reserved = 0;
879 memcpy(ptr, &reserved, 4);
880 ptr += 4;
881
882 // Write frame sizes (2 bytes per frame, network byte order)
883 for (uint32_t i = 0; i < frame_count; i++) {
884 uint16_t fs_net = htons(frame_size);
885 memcpy(ptr, &fs_net, 2);
886 ptr += 2;
887 }
888
889 // Copy Opus data
890 memcpy(ptr, opus_buffer, (size_t)opus_size);
891
892 // Queue the properly formatted packet
893 asciichat_error_t result =
894 server_send_audio(client, packet_buffer, total_packet_size);
895
896 if (result != ASCIICHAT_OK) {
898 "Failed to queue Opus audio for client %s",
899 client_id_snapshot);
900 } else {
901 // FPS tracking - audio packet successfully queued (handles lag
902 // detection and periodic reporting)
903 fps_frame_ns(&audio_fps_tracker, time_get_ns(),
904 "audio packet queued");
905 }
906
907 // Free the allocated packet buffer after queuing
908 // (packet_queue_push_copy copies data)
909 SAFE_FREE(packet_buffer);
910 }
911 }
912 // NOTE: opus_frame_accumulated is already reset at line 928 after encode
913 // attempt
914 }
915
916 // Audio mixing rate limiting using adaptive sleep system.
917 // One complete Opus frame is mixed per 20 ms iteration.
918 // Use queue_depth=0 and target_depth=0 for constant-rate audio processing
919 audio_deadline += 20 * NS_PER_MS_INT;
920 uint64_t now = time_get_ns();
921 if (audio_deadline > now)
922 platform_sleep_ns(audio_deadline - now);
923 else if (now - audio_deadline > 100 * NS_PER_MS_INT)
924 audio_deadline = now;
925 }
926
927#ifdef DEBUG_THREADS
928 log_debug("Audio render thread stopped for client %s", thread_client_id);
929#endif
930
931 // Clean up Opus encoder
932 if (opus_encoder) {
933 opus_codec_destroy(opus_encoder);
934 }
935
936 // Clean up thread-local error context before exit
937
938 return NULL;
939}
940
941/* ============================================================================
942 * Thread Lifecycle Management Functions
943 * ============================================================================
944 */
945
1016
1018 client_info_t *client) {
1019 log_debug("client_id=%s", client ? client->client_id : "NULL");
1020
1021 if (!server_ctx || !client) {
1022 log_error("Cannot create render threads: NULL %s",
1023 !server_ctx ? "server_ctx" : "client");
1024 return -1;
1025 }
1026
1027#ifdef DEBUG_THREADS
1028 log_debug("Creating render threads for client %s", client->client_id);
1029#endif
1030
1031 // NOTE: Mutexes are already initialized in add_client() before any threads
1032 // start This prevents race conditions where receive thread tries to use
1033 // uninitialized mutexes
1034
1035 // Initialize render thread control flags
1036 // IMPORTANT: Set to true BEFORE creating thread to avoid race condition
1037 // where thread starts and immediately exits because flag is false
1040
1041 // Create video rendering thread (stop_id=2, stop after receive thread)
1042 char thread_name[SERVER_RENDER_THREAD_NAME_BUFFER_SIZE];
1043 safe_snprintf(thread_name, sizeof(thread_name), "video_render_%s",
1044 client->client_id);
1045 asciichat_error_t video_result;
1046
1047 video_result =
1048 platform_thread_create(&client->video_render_thread, thread_name,
1050
1051 if (video_result != ASCIICHAT_OK) {
1052 // Reset flag since thread creation failed
1055 // Mutexes will be destroyed by remove_client() which called us
1056 return -1;
1057 }
1058
1059 // Create audio rendering thread (stop_id=2, same priority as video)
1060 safe_snprintf(thread_name, sizeof(thread_name), "audio_render_%s",
1061 client->client_id);
1062 asciichat_error_t audio_result;
1063
1064 audio_result =
1065 platform_thread_create(&client->audio_render_thread, thread_name,
1067 if (audio_result != ASCIICHAT_OK) {
1068 // Clean up video thread (atomic operation, no mutex needed)
1070 // Reset audio flag since thread creation failed
1072 // stop_client_render_threads() will be called by remove_client()
1073 // to clean up the video thread we just created
1074 // Mutexes will be destroyed by remove_client() which called us
1075 return -1;
1076 }
1077
1078#ifdef DEBUG_THREADS
1079 log_debug("Created render threads for client %s", client->client_id);
1080#endif
1081
1082 return 0;
1083}
1084
1167 if (!client)
1168 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing render client");
1171 if (thread_is_initialized(&client->video_render_thread)) {
1172 asciichat_error_t result = thread_join(&client->video_render_thread, NULL);
1173 if (result != ASCIICHAT_OK)
1174 return result;
1175 thread_init(&client->video_render_thread);
1176 }
1177 if (thread_is_initialized(&client->audio_render_thread)) {
1178 asciichat_error_t result = thread_join(&client->audio_render_thread, NULL);
1179 if (result != ASCIICHAT_OK)
1180 return result;
1181 thread_init(&client->audio_render_thread);
1182 }
1183 return ASCIICHAT_OK;
1184}
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
#define SET_ERRNO(code,...)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
#define OPUS_FRAME_SAMPLES
#define CLIENT_AUDIO_PIPELINE_FRAME_MS
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:9
#define AUDIO_CHANNELS
#define AUDIO_OPUS_SERVER_PACKET_CAPACITY
Platform initialization and static synchronization helpers.
void server_send_video(client_info_t *client, acip_frame_workspace_t *workspace, const char *data, size_t length, uint32_t width, uint32_t height, int sources, const acip_render_settings_t *rendering)
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
⏱️ FPS tracking utility for monitoring frame throughput across all threads
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:32
int mixer_process_excluding_source(mixer_t *mixer, float *output, int num_samples, uint32_t exclude_client_id)
Process audio from all sources except one (for per-client output).
Definition mixer.c:759
void opus_codec_destroy(opus_codec_t *codec)
Destroy an Opus codec instance.
Definition opus.c:315
size_t opus_codec_encode(opus_codec_t *codec, const float *samples, int num_samples, uint8_t *out_data, size_t out_size)
Encode audio frame with Opus.
Definition opus.c:151
int mixer_source_count(const mixer_t *mixer)
Definition mixer.c:556
opus_codec_t * opus_codec_create_encoder_channels(opus_application_t application, int sample_rate, int bitrate, int channels)
Definition opus.c:46
@ OPUS_APPLICATION_AUDIO
General audio (optimized for music).
Definition opus.h:93
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
void fps_frame_ns(fps_t *tracker, uint64_t current_time_ns, const char *context)
Track a frame and detect lag conditions (nanosecond version - PRIMARY).
Definition fps.c:58
unsigned long long uint64_t
unsigned char uint8_t
#define SAFE_MEMCPY(dest, dest_size, src, count)
void fps_init(fps_t *tracker, int expected_fps, const char *name)
Initialize FPS tracker.
Definition fps.c:37
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#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_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define STOP_TIMER_AND_LOG(log_level, threshold_ns, timer_name, msg_fmt,...)
Stop a timer and log the result with a custom message.
Definition time.h:618
#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 US_PER_MS_INT
Definition time.h:176
#define US_PER_SEC_INT
Definition time.h:177
struct client_info client_info_t
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
ACIP server-side protocol API.
@ ACIP_TRANSPORT_WEBRTC
WebRTC DataChannel (P2P).
void acip_frame_workspace_destroy(acip_frame_workspace_t *workspace)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
#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
Multi-Source Audio Mixing and Processing System.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
Opus audio codec wrapper for real-time encoding/decoding.
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
mixer_t *volatile g_audio_mixer
Global audio mixer instance for multi-client audio processing.
int server_send_audio(const float *samples, int num_samples)
Send audio data to server.
Per-client state management and lifecycle orchestration.
Server packet processing and protocol implementation.
#define SERVER_RENDER_THREAD_DISPLAY_NAME_BUFFER_SIZE
#define SERVER_RENDER_THREAD_NAME_BUFFER_SIZE
void * client_video_render_thread(void *arg)
Interruptible sleep function with platform-specific optimizations.
void * client_audio_render_thread(void *arg)
Main audio rendering thread function for individual clients.
int create_client_render_threads(server_context_t *server_ctx, client_info_t *client)
Create and initialize per-client rendering threads.
asciichat_error_t stop_client_render_threads(client_info_t *client)
Stop and cleanup per-client rendering threads.
Per-client rendering threads with rate limiting.
#define VIDEO_RENDER_FPS
#define AUDIO_PACKET_FPS
bool any_clients_sending_video(void)
Queue ASCII frame for delivery to specific client.
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
Send ASCII frame to client (server → client).
acip render settings keeps the values that move through the subsystem: caps, width,...
terminal_capabilities_t terminal_caps
char display_name[MAX_DISPLAY_NAME_LEN]
platform_thread_t audio_render_thread
platform_thread_t video_render_thread
char client_id[MAX_CLIENT_ID_LEN]
Counters and timestamps used to calculate and report frame rate.
Definition fps.h:59
State for one Opus encoding or decoding direction.
Definition opus.h:113
Server context - encapsulates all server state.
⏱️ High-precision timing utilities using sokol_time.h and uthash
📊 String Formatting Utilities