ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
protocol_adapter.c
Go to the documentation of this file.
2
3/* Client mode adapter: worker startup, display/snapshot effects and
4 * crypto/control callbacks. Media parsing and participant state live in
5 * session/protocol. */
9
10#include "../main.h" // Global exit API
11#include "audio.h"
12#include "capture.h"
13#include "display.h"
14#include "keepalive.h"
15#include "main.h"
16#include "protocol_adapter.h"
17#include "server.h"
21
22#include <ascii-chat/buffer.h>
23#include <ascii-chat/common.h>
37#include <ascii-chat/util/fps.h>
40#include <options/options.h>
41#include <options/rcu.h> // For RCU-based options access
42
43#include "crypto.h"
44
46#include <libplatform/atomic.h>
47#include <stdio.h>
48#include <string.h>
49#include <unistd.h>
50
51#ifdef _WIN32
52#include <libplatform/windows_compat.h>
53#endif
54
55#include <errno.h>
56
57static void handle_ascii_frame_packet(client_connection_t *connection,
58 const ascii_frame_packet_t *frame_header,
59 const char *frame_data) {
60 bool snapshot_should_exit = false;
61 ascii_frame_packet_t header = *frame_header;
62 if (should_exit())
63 return;
64
65 // FPS tracking for received ASCII frames using reusable tracker utility
66
67 // Initialize FPS tracker on first frame
68 if (!connection->frame_fps_tracker_initialized) {
69 int fps = GET_OPTION(fps);
70 int expected_fps = fps > 0 ? ((fps > 144) ? 144 : fps) : DEFAULT_MAX_FPS;
71 fps_init(&connection->frame_fps_tracker, expected_fps, "ASCII_RX");
72 connection->frame_fps_tracker_initialized = true;
73 }
74
75 // Track this frame and detect lag
76 fps_frame_ns(&connection->frame_fps_tracker, time_get_ns(), "ASCII frame");
77
78 // Track frame dimension changes
79
80 if (header.width > 0 && header.height > 0) {
81 if (header.width != connection->frame_last_width ||
82 header.height != connection->frame_last_height) {
83 connection->frame_last_width = header.width;
84 connection->frame_last_height = header.height;
85 }
86 }
87
88 // Handle snapshot mode timing
89 if (GET_OPTION(snapshot_mode)) {
90
91 connection->frame_snapshot_frame_count++;
92 log_debug("Snapshot frame %d received",
93 connection->frame_snapshot_frame_count);
94
95 if (!connection->frame_first_frame_recorded) {
96 connection->frame_first_frame_time_ns = time_get_ns();
99 connection
100 ->frame_first_frame_time_ns); // Also store globally for access
101 // from data_reception_thread
102 log_info("[SNAPSHOT_INIT] SET g_snapshot_first_frame_time_ns=%llu "
103 "first_frame_time_ns=%llu",
104 (unsigned long long)atomic_load_u64(
105 &connection->snapshot_first_frame_time_ns),
106 (unsigned long long)connection->frame_first_frame_time_ns);
107 connection->frame_first_frame_recorded = true;
108
109 if (GET_OPTION(snapshot_delay) == 0) {
110 log_debug("Snapshot captured immediately (delay=0)!");
111 snapshot_should_exit = true;
112 } else {
113 log_debug("Snapshot mode: first frame received, waiting %.2f seconds "
114 "for webcam warmup...",
115 GET_OPTION(snapshot_delay));
116 }
117 } else {
118 uint64_t current_time_ns = time_get_ns();
119 double elapsed = time_ns_to_s(time_elapsed_ns(
120 connection->frame_first_frame_time_ns, current_time_ns));
121 double snapshot_delay = GET_OPTION(snapshot_delay);
122
123 // Log every 0.5 seconds to debug timing
124
125 if (current_time_ns - connection->frame_last_debug_log_ns >
126 500 * 1000 * 1000) { // 500ms
127 log_debug("SNAPSHOT_DELAY_CHECK: elapsed=%.3f target=%.3f "
128 "first_frame_ns=%llu current_ns=%llu",
129 elapsed, snapshot_delay,
130 (unsigned long long)connection->frame_first_frame_time_ns,
131 (unsigned long long)current_time_ns);
132 connection->frame_last_debug_log_ns = current_time_ns;
133 }
134
135 if (elapsed >= snapshot_delay) {
136 char duration_str[TIME_DURATION_BUFFER_SIZE];
137 time_pretty((uint64_t)(elapsed * 1e9), -1, duration_str,
138 sizeof(duration_str));
139 log_info("Snapshot captured after %s (target=%.3f)", duration_str,
140 snapshot_delay);
141 snapshot_should_exit = true;
142 }
143 }
144 }
145
146 // Check if we need to clear console before rendering this frame
147 // IMPORTANT: We track if this is the first frame to ensure proper
148 // initialization
149
150 if (!connection->frame_first_frame_rendered) {
151 // Always clear display and disable logging before rendering the first frame
152 // This ensures clean ASCII display regardless of packet arrival order
153 log_debug("First frame - clearing display and disabling terminal logging");
156 connection->frame_first_frame_rendered = true;
157 connection->protocol.server_state_initialized = true; // Mark as initialized
158 connection->protocol.layout_changed =
159 false; // Clear any pending clear request
160 log_debug("CLIENT_DISPLAY: Display cleared, ready for ASCII frames");
161 } else if (connection->protocol.layout_changed) {
162 // Subsequent clear request from server (e.g., after client list changes)
163 log_debug("CLIENT_DISPLAY: Clearing display for layout change");
166 connection->protocol.layout_changed = false;
167 }
168
169 // Safety check before rendering
170 if (!frame_data || header.original_size == 0) {
171 log_error("Invalid frame data for rendering: frame_data=%p, size=%u",
172 frame_data, header.original_size);
173 return;
174 }
175
176 // The server paces frames using our negotiated desired_fps. Present received
177 // frames without a second arrival-time limiter: network jitter can deliver a
178 // correctly paced frame just before its nominal interval. The UI controller
179 // coalesces pending frames if the terminal cannot keep up.
180
181 // Frame counting now handled in session_display_write_ascii() which is called
182 // by both client and host/discovery modes for consistent metrics
183
184 // Render ASCII art frame (display_render_frame will apply effects like
185 // --matrix)
187 "CALLING_DISPLAY_RENDER: frame_data=%p len=%zu, calling "
188 "display_render_frame()",
189 frame_data, strlen(frame_data));
190 display_render_frame(connection, frame_data);
192 "DISPLAY_RENDER_RETURNED: frame was rendered");
193
194 // The frame must be presented before snapshot shutdown is requested. The
195 // reception thread is also responsible for rendering the packet, so exiting
196 // above would discard the very frame that satisfied the snapshot condition.
197 if (snapshot_should_exit)
198 signal_exit();
199}
200
201static bool handle_error_message_packet(client_connection_t *connection,
202 const void *data, size_t len) {
203 asciichat_error_t remote_error = ASCIICHAT_OK;
204 char message[MAX_ERROR_MESSAGE_LENGTH + 1] = {0};
205
207 data, len, &remote_error, message, sizeof(message), NULL);
208 if (parse_result != ASCIICHAT_OK) {
209 log_error("Failed to parse error packet from server: %s",
210 asciichat_error_format(NULL, parse_result));
211 return false;
212 }
213
214 remote_error = network_error_public_code(remote_error);
215 log_error("Server reported %s", asciichat_error_format(NULL, remote_error));
217 SET_ERRNO(remote_error, "Server notification: %s",
218 asciichat_error_string(remote_error));
219 if (network_error_action(remote_error) == NETWORK_ERROR_CONTINUE) {
220 log_warn("Server audio unavailable; continuing video");
222 return true;
223 }
224 server_connection_set_remote_error(connection, remote_error);
225 if (network_error_action(remote_error) == NETWORK_ERROR_STOP) {
226 errno_request_exit(remote_error);
227 signal_exit();
228 }
229 log_warn("Server rejected this connection; closing it");
231 server_connection_shutdown(connection);
232 server_connection_lost(connection);
233 return true;
234}
235
236static void handle_remote_log_packet(const void *data, size_t len) {
237 log_level_t remote_level = LOG_INFO;
239 uint16_t flags = 0;
240 char message[MAX_REMOTE_LOG_MESSAGE_LENGTH + 1] = {0};
241
242 asciichat_error_t parse_result =
243 packet_parse_remote_log(data, len, &remote_level, &direction, &flags,
244 message, sizeof(message), NULL);
245 if (parse_result != ASCIICHAT_OK) {
246 log_error("Failed to parse remote log packet from server: %s",
247 asciichat_error_format(NULL, parse_result));
248 return;
249 }
250
251 if (direction != REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT) {
252 log_error("Remote log packet direction mismatch (direction=%u)", direction);
253 return;
254 }
255
256 bool truncated = (flags & REMOTE_LOG_FLAG_TRUNCATED) != 0;
257
258 if (truncated) {
259 log_msg(remote_level, __FILE__, __LINE__, __func__,
260 "[REMOTE SERVER] %s [message truncated]", message);
261 } else {
262 log_msg(remote_level, __FILE__, __LINE__, __func__, "[REMOTE SERVER] %s",
263 message);
264 }
265}
266
268client_present_frame(const ascii_frame_packet_t *header, const char *text,
269 void *context) {
270 handle_ascii_frame_packet(context, header, text);
271 return ASCIICHAT_OK;
272}
273
274static asciichat_error_t client_play_samples(const float *samples, size_t count,
275 void *context) {
276 if (GET_OPTION(audio_enabled))
277 audio_process_received_samples(context, samples, (int)count);
278 return ASCIICHAT_OK;
279}
280
281static asciichat_error_t client_decode_opus(const void *data, size_t length,
282 float *samples, size_t capacity,
283 size_t *decoded, void *context) {
284 *decoded = 0;
285 if (!GET_OPTION(audio_enabled))
286 return ASCIICHAT_OK;
287 int count = audio_decode_opus(context, data, length, samples, (int)capacity);
288 // The audio pipeline provides packet-loss concealment for corrupt frames.
289 if (count <= 0)
290 count = audio_decode_opus(context, NULL, 0, samples, (int)capacity);
291 if (count <= 0)
292 return SET_ERRNO(ERROR_AUDIO, "Failed to decode participant Opus audio");
293 *decoded = (size_t)count;
294 return ASCIICHAT_OK;
295}
296
297static void client_track_audio(size_t length, void *context) {
298 (void)context;
299 if (GET_OPTION(audio_enabled) && GET_OPTION(audio_analysis_enabled))
301}
302
303/* ============================================================================
304 * ACIP Callback Forward Declarations and Structure
305 * ============================================================================
306 */
307
308// Forward declarations for ACIP callbacks (implemented after this section)
309static void acip_on_error(const error_packet_t *header, const char *message,
310 void *ctx);
311static void acip_on_remote_log(const remote_log_packet_t *header,
312 const char *message, void *ctx);
313static void acip_on_ping(void *ctx);
314static void acip_on_pong(void *ctx);
315static void acip_on_clear_console(void *ctx);
316static void acip_on_webrtc_sdp(const acip_webrtc_sdp_t *sdp, size_t total_len,
317 void *ctx);
318static void acip_on_webrtc_ice(const acip_webrtc_ice_t *ice, size_t total_len,
319 void *ctx);
320static void acip_on_session_joined(const acip_session_joined_t *joined,
321 void *ctx);
322
323static const acip_client_callbacks_t g_acip_client_callbacks = {
324 .on_error = acip_on_error,
325 .on_remote_log = acip_on_remote_log,
326 .on_ping = acip_on_ping,
327 .on_pong = acip_on_pong,
328 .on_clear_console = acip_on_clear_console,
329
330 .on_webrtc_sdp = acip_on_webrtc_sdp,
331 .on_webrtc_ice = acip_on_webrtc_ice,
332 .on_session_joined = acip_on_session_joined,
333 .app_ctx = NULL};
334
335/* ============================================================================
336 * Data Reception Thread
337 * ============================================================================
338 */
339
340static asciichat_error_t client_connection_packet(network_connection_t *network,
341 packet_type_t type,
342 const void *payload,
343 size_t length, void *arg) {
344 (void)network;
345 client_connection_t *connection = arg;
346 asciichat_error_t result =
347 session_protocol_dispatch(&connection->protocol, type, payload, length);
348 // A recorded rejection already closed the transport. Stop this receive loop
349 // with its public reason instead of reading again and notifying a second EOF.
350 return result != ASCIICHAT_OK
351 ? result
353}
354static void *data_reception_thread_func(void *arg) {
355 client_connection_t *connection = arg;
356 network_connection_callbacks_t callbacks = {.packet =
357 client_connection_packet};
358 asciichat_error_t result =
359 network_connection_run(connection->network, &callbacks, connection);
360 uint64_t first_frame =
362 if (GET_OPTION(snapshot_mode) && first_frame &&
363 time_ns_to_s(time_elapsed_ns(first_frame, time_get_ns())) >=
364 GET_OPTION(snapshot_delay)) {
365 signal_exit();
366 } else if (!should_exit()) {
367 if (result == ERROR_CRYPTO) {
368 NOTICE(DANGER, "ENCRYPTION POLICY VIOLATION",
369 "Server violated the encryption policy; closing connection.");
371 signal_exit();
372 }
373 server_connection_lost(connection);
374 }
375 atomic_store_bool(&connection->data_thread_exited, true);
376 return NULL;
377}
378
379/* ============================================================================
380 * Public Interface Functions
381 * ============================================================================
382 */
383
384// Before the receive worker starts, an admission rejection can race
385// STREAM_START. Preserve the peer's public error instead of reporting only the
386// failed write.
388client_startup_peer_error(client_connection_t *connection,
389 asciichat_error_t send_error) {
390 acip_transport_t *transport = server_connection_get_transport(connection);
391 if (!transport ||
392 (send_error != ERROR_NETWORK && send_error != ERROR_NETWORK_CONNECT))
393 return send_error;
394 uint64_t previous_timeout = transport->receive_timeout_ns;
395 uint64_t deadline = time_get_ns() + 500 * NS_PER_MS_INT;
396 asciichat_error_t result = send_error;
397 while (time_get_ns() < deadline && !should_exit()) {
398 transport->receive_timeout_ns = 100 * NS_PER_MS_INT;
399 packet_type_t type = 0;
400 void *payload = NULL, *allocation = NULL;
401 size_t length = 0;
402 bool notifications = errno_notifications_suppress(true);
404 packet_envelope_t envelope = {0};
405 asciichat_error_t received =
406 acip_client_receive_packet(transport, &envelope);
407 type = envelope.type;
408 payload = envelope.data;
409 length = envelope.len;
410 allocation = envelope.allocated_buffer;
412 errno_notifications_suppress(notifications);
413 if (received == ASCIICHAT_OK && type == PACKET_TYPE_ERROR_MESSAGE)
414 result = network_error_decode(type, payload, length);
415 buffer_release(allocation);
416 if (result != send_error ||
417 (received != ASCIICHAT_OK && received != ERROR_NETWORK_TIMEOUT &&
418 received != ERROR_NETWORK_INCOMPLETE))
419 break;
420 }
421 transport->receive_timeout_ns = previous_timeout;
422 return result;
423}
424
426 log_warn("[FRAME_RECV_INIT] ๐ŸŸข PROTOCOL_START: Starting client protocol "
427 "initialization");
428
429 // The server can send Opus audio as soon as streaming starts. Initialize the
430 // decoder before either transport's receive worker can dispatch those
431 // packets.
432 asciichat_error_t audio_result = audio_connection_init(connection);
433 if (audio_result != ASCIICHAT_OK)
434 return audio_result;
435 if (client_connection_checkpoint("audio-pipeline") != ASCIICHAT_OK)
436 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
437
438 acip_client_callbacks_t control = g_acip_client_callbacks;
439 control.app_ctx = connection;
441 &connection->protocol, server_connection_get_transport(connection),
442 (session_protocol_media_t){.terminal_output = true,
443 .on_frame = client_present_frame,
444 .on_samples = client_play_samples,
445 .decode_opus = client_decode_opus,
446 .on_audio_packet = client_track_audio,
447 .context = connection,
448 .frame_workspace =
449 &connection->decoded_ascii_workspace},
450 control);
451
452 // Reset display state for new connection
454
455 // Start receiving before the capability/settings exchange. The server may
456 // reply to the initial settings packet immediately, and that reply must not
457 // wait for the worker that dispatches it.
458 atomic_store_bool(&connection->data_thread_exited, false);
460 data_reception_thread_func, connection, 1,
461 "data_reception") != ASCIICHAT_OK) {
462 log_error("[FRAME_RECV_INIT] Failed to start data reception thread");
463 LOG_ERRNO_IF_SET("Data reception thread creation failed");
464 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
465 }
466
468 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
469
470 // Send CLIENT_CAPABILITIES packet (after crypto is ready for both TCP and WS)
471 // Server expects this as the first packet after crypto handshake
472 log_debug("[FRAME_RECV_INIT] Sending CLIENT_CAPABILITIES (terminal size)");
474 connection, (int)terminal_get_effective_width(GET_OPTION(width), 80),
476 if (cap_result != ASCIICHAT_OK) {
477 log_error("[FRAME_RECV_INIT] Failed to send terminal size capabilities");
478 return client_startup_peer_error(connection, cap_result);
479 }
480
481 // Capabilities establish the viewer geometry, but renderer preferences are
482 // carried by SETTINGS_SYNC. Send them before STREAM_START so the server
483 // cannot render the first frames from its zero-initialized (luminance)
484 // fallback while the asynchronous settings update is still in flight.
485 options_snapshot_t initial_settings;
486 if (options_read_snapshot(&initial_settings) != ASCIICHAT_OK)
487 return client_startup_peer_error(connection, ERROR_CONFIG);
488 asciichat_error_t settings_result =
490 &initial_settings.values, 1, UINT32_MAX);
491 if (settings_result != ASCIICHAT_OK) {
492 log_error("[FRAME_RECV_INIT] Failed to send initial rendering settings");
493 return client_startup_peer_error(connection, settings_result);
494 }
495
496 // Send STREAM_START packet with combined stream types
497 uint32_t stream_types = STREAM_TYPE_VIDEO; // Always have video
498 if (GET_OPTION(audio_enabled)) {
499 stream_types |= STREAM_TYPE_AUDIO; // Add audio if enabled
500 }
501 log_debug("[FRAME_RECV_INIT] Sending STREAM_START: types=0x%x (video%s)",
502 stream_types, (stream_types & STREAM_TYPE_AUDIO) ? "+audio" : "");
503 asciichat_error_t stream_result =
504 threaded_send_stream_start_packet(connection, stream_types);
505 if (stream_result != ASCIICHAT_OK) {
506 log_error("[FRAME_RECV_INIT] Failed to send stream start");
507 return client_startup_peer_error(connection, stream_result);
508 }
509
510 // Start webcam capture thread
511 log_debug("Starting webcam capture thread...");
512 if (capture_start_thread(connection) != 0) {
513 log_error("Failed to start webcam capture thread");
514 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
515 }
516 log_debug("Webcam capture thread started successfully");
518 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
519
520 // Start local media audio only after the connection succeeds. Starting the
521 // worker during client initialization would consume file audio while dialing.
522 audio_context_t *audio_context = connection->audio_context;
523 if (audio_context && audio_context->initialized) {
525 audio_context);
526 audio_context->capture_media_source =
528 if (audio_start_duplex(audio_context) != ASCIICHAT_OK) {
529 log_error("Failed to start full-duplex audio");
530 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
531 }
532 }
533
534 if (client_connection_checkpoint("audio-duplex") != ASCIICHAT_OK)
535 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
536
537 // Initialize audio sender thread BEFORE starting audio capture
538 // This ensures sender is ready when capture thread starts queueing packets
539 // Must happen after connection succeeds to prevent deadlock if connection
540 // fails
541 if (audio_sender_init(connection) != ASCIICHAT_OK)
542 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
543
544 // Start audio capture thread if audio is enabled
545 log_debug("Starting audio capture thread...");
546 if (audio_start_thread(connection) != 0) {
547 log_error("Failed to start audio capture thread");
548 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
549 }
550 log_debug("Audio capture thread started successfully (or skipped if audio "
551 "disabled)");
552
553 if (client_connection_checkpoint("audio-capture") != ASCIICHAT_OK)
554 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
555
556 // Start keepalive/ping thread to prevent server timeout
557 log_debug("Starting keepalive/ping thread...");
558 if (keepalive_start_thread(connection) != 0) {
559 log_error("Failed to start keepalive/ping thread");
560 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
561 }
562 log_debug("Keepalive/ping thread started successfully");
563
564 if (client_connection_checkpoint("keepalive") != ASCIICHAT_OK)
565 return SET_ERRNO(ERROR_THREAD, "Could not start client protocol workers");
566 return ASCIICHAT_OK;
567}
568
573
574/* ============================================================================
575 * ACIP Callback Implementations
576 * ============================================================================
577 */
578
579static void acip_on_error(const error_packet_t *header, const char *message,
580 void *ctx) {
581 client_connection_t *connection = ctx;
582 (void)ctx;
583
584 // Reconstruct packet for existing handler
585 size_t msg_len = message ? strlen(message) : 0;
586 size_t total_len = sizeof(*header) + msg_len;
587
588 uint8_t *packet = SAFE_MALLOC(total_len, uint8_t *);
589 if (!packet) {
590 log_error("Failed to allocate buffer for error packet callback");
591 return;
592 }
593
594 memcpy(packet, header, sizeof(*header));
595 if (msg_len > 0) {
596 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary packet data
597 memcpy(packet + sizeof(*header), message, msg_len);
598 }
599
600 handle_error_message_packet(connection, packet, total_len);
601 SAFE_FREE(packet);
602}
603
604static void acip_on_ping(void *ctx) {
605 client_connection_t *connection = ctx;
606 (void)ctx;
607
608 // Respond with PONG
609 if (threaded_send_pong_packet(connection) != ASCIICHAT_OK) {
610 log_error("Failed to send PONG response");
611 }
612}
613
614static void acip_on_remote_log(const remote_log_packet_t *header,
615 const char *message, void *ctx) {
616 (void)ctx;
617
618 // Reconstruct packet for existing handler
619 size_t msg_len = strlen(message);
620 size_t total_len = sizeof(*header) + msg_len;
621
622 uint8_t *packet = SAFE_MALLOC(total_len, uint8_t *);
623 if (!packet) {
624 log_error("Failed to allocate buffer for remote log callback");
625 return;
626 }
627
628 memcpy(packet, header, sizeof(*header));
629 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary packet data,
630 // not string
631 memcpy(packet + sizeof(*header), message, msg_len);
632
633 handle_remote_log_packet(packet, total_len);
634 SAFE_FREE(packet);
635}
636
637static void acip_on_pong(void *ctx) {
638 (void)ctx;
640}
641
642static void acip_on_clear_console(void *ctx) {
643 (void)ctx;
644
645 // Server requested console clear
647 log_debug("Console cleared by server");
648}
649
650static void acip_on_webrtc_sdp(const acip_webrtc_sdp_t *sdp, size_t total_len,
651 void *ctx) {
652 (void)ctx;
653 (void)total_len; // Peer manager reads variable data via pointer arithmetic
654
655 // Check if WebRTC is initialized
656 if (!g_peer_manager) {
657 log_warn("Received WebRTC SDP but peer manager not initialized - ignoring");
658 return;
659 }
660
661 // Log SDP type for debugging
662 const char *sdp_type_str = (sdp->sdp_type == 0) ? "offer" : "answer";
663 log_debug("Received WebRTC SDP %s from participant (session_id=%.8s...)",
664 sdp_type_str, (const char *)sdp->session_id);
665
666 // Handle SDP through peer manager (extracts variable data internally)
667 asciichat_error_t result =
669
670 if (result != ASCIICHAT_OK) {
671 log_error("Failed to handle WebRTC SDP: %s",
672 asciichat_error_format(NULL, result));
673 }
674}
675
676static void acip_on_webrtc_ice(const acip_webrtc_ice_t *ice, size_t total_len,
677 void *ctx) {
678 (void)ctx;
679 (void)total_len; // Peer manager reads variable data via pointer arithmetic
680
681 // Check if WebRTC is initialized
682 if (!g_peer_manager) {
683 log_warn("Received WebRTC ICE but peer manager not initialized - ignoring");
684 return;
685 }
686
687 log_debug(
688 "Received WebRTC ICE candidate from participant (session_id=%.8s...)",
689 (const char *)ice->session_id);
690
691 // Handle ICE through peer manager (extracts variable data internally)
692 asciichat_error_t result =
694
695 if (result != ASCIICHAT_OK) {
696 log_error("Failed to handle WebRTC ICE: %s",
697 asciichat_error_format(NULL, result));
698 }
699}
700
701static void acip_on_session_joined(const acip_session_joined_t *joined,
702 void *ctx) {
703 (void)ctx;
704
705 if (!joined) {
706 log_error("SESSION_JOINED callback received NULL response");
707 return;
708 }
709
710 // Check if join was successful
711 if (!joined->success) {
712 log_error("ACDS session join failed: error %d: %s", joined->error_code,
713 joined->error_message);
714 // Connection will timeout waiting for SDP/WebRTC completion and fallback to
715 // next stage
716 return;
717 }
718
719 // Join succeeded - we have session context now
720 log_debug("ACDS session join succeeded (participant_id=%.8s..., "
721 "session_type=%s, server=%s:%u)",
722 (const char *)joined->participant_id,
723 joined->session_type == 1 ? "WebRTC" : "DirectTCP",
724 joined->server_address, joined->server_port);
725
726 // Check if this is a WebRTC session
727 if (joined->session_type == SESSION_TYPE_WEBRTC) {
728 log_debug("WebRTC session joined; discovery mode owns peer-manager "
729 "initialization");
730 } else {
731 // Direct TCP - connection is already established or will be established
732 log_debug("Direct TCP session - using existing connection");
733 }
734}
ascii-chat Discovery Service (ACDS) Protocol Message Formats
void audio_analysis_track_received_packet(size_t size)
Track received packet.
Definition analysis.c:499
Audio Analysis and Debugging Interface.
void errno_request_exit(asciichat_error_t code)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_scope_begin(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_HANDLED
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
#define buffer_release(data)
Definition buffer.h:108
Common buffer size definitions.
int capture_start_thread(client_connection_t *connection)
Start capture thread.
ascii-chat Client Media Capture Management Interface
struct webrtc_peer_manager * g_peer_manager
Client connection session state for session_client_like integration.
ascii-chat Client Mode Entry Point Header
void session_capture_set_audio_context(session_capture_ctx_t *ctx, void *audio_ctx)
Set the audio context for playback control.
asciichat_error_t session_protocol_dispatch(session_protocol_t *protocol, packet_type_t type, const void *payload, size_t length)
void session_protocol_init(session_protocol_t *protocol, acip_transport_t *transport, session_protocol_media_t media, acip_client_callbacks_t control)
Named object registry for debugging โ€” log identifiable resource names.
๐Ÿ”„ Network byte order conversion helpers
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
โฑ๏ธ FPS tracking utility for monitoring frame throughput across all threads
asciichat_error_t audio_start_duplex(audio_context_t *ctx)
Start full-duplex audio (simultaneous capture and playback).
void display_reset_for_new_connection(client_connection_t *connection)
Reset display state for new connection.
void display_full_reset()
Perform full display reset.
void display_render_frame(client_connection_t *connection, const char *frame_data)
Render ASCII frame to display.
unsigned short uint16_t
unsigned int uint32_t
#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
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
@ ERROR_NETWORK_CONNECT
Definition error_codes.h:79
@ ERROR_NETWORK_INCOMPLETE
Definition error_codes.h:97
@ ERROR_NETWORK
Definition error_codes.h:77
@ ERROR_AUDIO
Definition error_codes.h:66
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:80
@ ERROR_THREAD
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second).
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
void log_msg(log_level_t level, const char *file, int line, const char *func, const char *fmt,...)
Log a message at a specific level.
Definition log/log.c:1313
enum remote_log_direction remote_log_direction_t
Remote log packet direction enumeration.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
log_level_t
Logging levels enumeration.
Definition log/types.h:33
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
Definition log/log.c:818
@ REMOTE_LOG_DIRECTION_SERVER_TO_CLIENT
Definition network/log.h:22
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:21
acip_session_joined_t
Definition acds.h:479
acip_webrtc_ice_t
Definition acds.h:655
acip_webrtc_sdp_t
Definition acds.h:609
@ SESSION_TYPE_WEBRTC
WebRTC P2P mesh with STUN/TURN relay.
Definition acds.h:151
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
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
#define US_PER_SEC_INT
Definition time.h:177
#define STREAM_TYPE_VIDEO
Video stream.
Definition packet.h:1016
#define STREAM_TYPE_AUDIO
Audio stream.
Definition packet.h:1017
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define MAX_REMOTE_LOG_MESSAGE_LENGTH
Maximum remote log message length (512 bytes).
Definition packet.h:163
#define REMOTE_LOG_FLAG_TRUNCATED
Remote log packet flag definitions.
Definition packet.h:787
#define MAX_ERROR_MESSAGE_LENGTH
Maximum error message length (512 bytes).
Definition packet.h:153
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
#define GET_OPTION(field)
Definition options.h:1339
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
void * session_capture_get_media_source(session_capture_ctx_t *ctx)
Get the underlying media source from capture context.
asciichat_error_t webrtc_peer_manager_handle_ice(webrtc_peer_manager_t *manager, const acip_webrtc_ice_t *ice)
Handle incoming ICE candidate from ACDS.
asciichat_error_t webrtc_peer_manager_handle_sdp(webrtc_peer_manager_t *manager, const acip_webrtc_sdp_t *sdp)
Handle incoming SDP message from ACDS.
ACIP protocol packet handlers (transport-agnostic).
๐Ÿ”Š Audio Capture and Playback Interface for ascii-chat
โš™๏ธ Common definitions, error codes, macros, and types shared throughout the application
Client-side handshake functions.
ACIP client-side protocol API.
Transport abstraction layer for ACIP protocol.
struct network_connection network_connection_t
Network error handling utilities.
int keepalive_start_thread(client_connection_t *connection)
Start keepalive/ping thread.
Definition keepalive.c:219
ascii-chat Client Connection Keepalive Management Interface
asciichat_error_t acip_client_receive_packet(acip_transport_t *transport, packet_envelope_t *out)
asciichat_error_t acip_settings_send(acip_transport_t *transport, const options_t *values, uint32_t request, uint32_t expected_revision)
asciichat_error_t network_connection_run(network_connection_t *c, const network_connection_callbacks_t *callbacks, void *context)
asciichat_error_t network_error_public_code(asciichat_error_t code)
asciichat_error_t network_error_decode(packet_type_t type, const void *payload, size_t size)
network_error_action_t network_error_action(asciichat_error_t code)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define LOG_INFO
Definition log/types.h:44
void signal_exit(void)
Definition main.c:262
bool should_exit(void)
Definition main.c:260
Global application exit and signal handling API.
#define NOTICE(severity, title,...)
Definition notice.h:86
โš™๏ธ Unified options parsing system for ascii-chat with builder pattern and lock-free access
asciichat_error_t packet_parse_remote_log(const void *data, size_t len, log_level_t *out_level, remote_log_direction_t *out_direction, uint16_t *out_flags, char *message_buffer, size_t message_buffer_size, size_t *out_message_length)
Parse a remote log packet payload into components.
Definition packet.c:885
asciichat_error_t packet_parse_error_message(const void *data, size_t len, asciichat_error_t *out_error_code, char *message_buffer, size_t message_buffer_size, size_t *out_message_length)
Parse an error packet payload into components.
Definition packet.c:793
asciichat_error_t client_protocol_start(client_connection_t *connection)
bool client_protocol_connection_lost(client_connection_t *connection)
asciichat_error_t options_read_snapshot(options_snapshot_t *snapshot)
Definition rcu.c:934
ACIP shared/bidirectional packet sending functions.
asciichat_error_t audio_connection_init(client_connection_t *connection)
int audio_decode_opus(client_connection_t *connection, const uint8_t *opus_data, size_t opus_len, float *output, int max_samples)
Decode Opus packet using the audio pipeline.
int audio_start_thread(client_connection_t *connection)
Start audio capture thread.
void audio_process_received_samples(client_connection_t *connection, const float *samples, int num_samples)
Process received audio samples from server.
asciichat_error_t audio_sender_init(client_connection_t *connection)
Initialize async audio sender queue and thread.
ascii-chat Client Audio Processing Management Interface
asciichat_error_t client_connection_checkpoint(const char *stage)
struct client_connection client_connection_t
ascii-chat Client Display Management Interface
void server_connection_shutdown(client_connection_t *connection)
Interrupt connection I/O from normal thread context.
asciichat_error_t threaded_send_terminal_size_with_auto_detect(client_connection_t *connection, unsigned short width, unsigned short height)
Thread-safe terminal size packet transmission with auto-detection.
asciichat_error_t threaded_send_stream_start_packet(client_connection_t *connection, uint32_t stream_type)
Thread-safe stream start packet transmission.
void server_connection_set_remote_error(client_connection_t *connection, asciichat_error_t code)
Atomic flag indicating if connection is currently active.
void server_connection_lost(client_connection_t *connection)
Signal that connection has been lost.
asciichat_error_t threaded_send_pong_packet(client_connection_t *connection)
Thread-safe pong packet transmission.
asciichat_error_t server_connection_get_remote_error(client_connection_t *connection)
bool server_connection_is_lost(client_connection_t *connection)
Check if connection loss has been detected.
void server_connection_pong_received(client_connection_t *connection)
Signal that connection has been lost.
acip_transport_t * server_connection_get_transport(client_connection_t *connection)
Get ACIP transport instance.
ascii-chat Client Server Connection Management Interface
unsigned short int terminal_get_effective_height(int height_option, unsigned short fallback_height)
unsigned short int terminal_get_effective_width(int width_option, unsigned short fallback_width)
๐Ÿ”ค String Manipulation and Shell Escaping Utilities
Client-side packet handler callbacks.
Definition handlers.h:55
void * app_ctx
Application context (passed to all callbacks).
Definition handlers.h:117
uint64_t receive_timeout_ns
Optional TCP receive timeout override; zero uses the normal polling timeout.
The wire metadata for one rendered ASCII frame. width and height describe the terminal grid,...
Definition packet.h:920
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
When code needs to work with audio device info, it keeps index, max_input_channels,...
bool initialized
True if context has been initialized.
network_connection_t * network
thread_pool_t * client_worker_pool
atomic_t snapshot_first_frame_time_ns
session_protocol_t protocol
session_capture_ctx_t * capture_context
buffer_workspace_t decoded_ascii_workspace
audio_context_t * audio_context
Error packet structure carrying error code and textual description.
Definition packet.h:778
Callbacks and operations used by network connection callbacks. Packet payloads are borrowed until ret...
Packet envelope containing received packet data.
Definition packet.h:1208
Remote log packet structure carrying log level and message text.
Definition packet.h:792
asciichat_error_t thread_pool_spawn(thread_pool_t *pool, void *(*thread_func)(void *), void *thread_arg, int stop_id, const char *thread_name)
Spawn a worker thread in the pool.
๐Ÿงต Generic thread pool abstraction for managing worker threads
โฑ๏ธ High-precision timing utilities using sokol_time.h and uthash
๐Ÿ“Š String Formatting Utilities
Common validation macros to reduce duplication in protocol handlers.