ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
server.h File Reference

ascii-chat Client Server Connection Management Interface More...

Go to the source code of this file.

Enumerations

enum  connection_error_t {
  CONNECTION_SUCCESS = 0 , CONNECTION_WARNING_NO_CLIENT_AUTH = 1 , CONNECTION_ERROR_GENERIC = -1 , CONNECTION_ERROR_AUTH_FAILED = -2 ,
  CONNECTION_ERROR_HOST_KEY_FAILED = -3
}
 Connection establishment error codes. More...

Functions

int server_connection_init (client_connection_t *connection)
 Initialize server connection management subsystem.
bool server_connection_is_active (client_connection_t *connection)
 Establish connection to ascii-chat server.
struct acip_transport * server_connection_get_transport (client_connection_t *connection)
 Get ACIP transport instance.
void server_connection_set_transport (client_connection_t *connection, struct acip_transport *transport)
 Set ACIP transport instance from connection fallback.
uint32_t server_connection_get_client_id (client_connection_t *connection)
 Get client ID assigned by server.
const char * server_connection_get_ip (client_connection_t *connection)
 Get resolved server IP address.
void server_connection_set_ip (client_connection_t *connection, const char *ip)
 Set the server IP address.
void server_connection_set_port (client_connection_t *connection, int port)
 Set the server port.
int server_connection_get_port (client_connection_t *connection)
 Get the server port.
void server_connection_shutdown (client_connection_t *connection)
 Interrupt connection I/O from normal thread context.
void server_connection_lost (client_connection_t *connection)
 Signal that connection has been lost.
void server_connection_pong_received (client_connection_t *connection)
 Signal that connection has been lost.
void server_connection_set_remote_error (client_connection_t *connection, asciichat_error_t code)
 Atomic flag indicating if connection is currently active.
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 was detected.
asciichat_error_t threaded_send_packet (client_connection_t *connection, packet_type_t type, const void *data, size_t len)
 Thread-safe packet transmission.
asciichat_error_t threaded_send_audio_batch_packet (client_connection_t *connection, const float *samples, int num_samples, int batch_count)
 Thread-safe batched audio packet transmission.
asciichat_error_t threaded_send_audio_opus (client_connection_t *connection, const uint8_t *opus_data, size_t opus_size, int sample_rate, int frame_duration)
 Thread-safe Opus audio frame transmission.
asciichat_error_t threaded_send_audio_opus_batch (client_connection_t *connection, const uint8_t *opus_data, size_t opus_size, const uint16_t *frame_sizes, int frame_count)
 Thread-safe Opus audio batch packet transmission.
asciichat_error_t threaded_send_image_frame (client_connection_t *connection, const void *pixel_data, uint32_t width, uint32_t height, uint32_t pixel_format)
 Thread-safe image frame transmission.
asciichat_error_t threaded_send_image_frame_encoded (client_connection_t *connection, const void *pixel_data, uint32_t width, uint32_t height, video_codec_t codec, bool *encoding_failed)
 Send HEVC/H.264-encoded video frame to server (thread-safe).
asciichat_error_t threaded_send_ping_packet (client_connection_t *connection)
 Thread-safe ping packet transmission.
asciichat_error_t threaded_send_pong_packet (client_connection_t *connection)
 Thread-safe pong packet transmission.
asciichat_error_t threaded_send_stream_start_packet (client_connection_t *connection, uint32_t stream_type)
 Thread-safe stream start packet transmission.
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_client_join_packet (client_connection_t *connection, const char *display_name, uint32_t capabilities)
 Thread-safe client join packet transmission.
int server_send_packet (packet_type_t type, const void *data, size_t len)
 Send general packet to server.
int server_send_audio (const float *samples, int num_samples)
 Send audio data to server.
int server_send_audio_batch (const float *samples, int num_samples, int batch_count)
 Send batched audio data to server.
int server_send_terminal_capabilities (unsigned short width, unsigned short height)
 Send terminal capabilities to server.
int server_send_ping ()
 Send ping keepalive packet.
int server_send_pong ()
 Send pong response packet.
int server_send_stream_start (uint32_t stream_type)
 Send stream start notification.
int server_send_stream_stop (uint32_t stream_type)
 Send stream stop notification.

Detailed Description

ascii-chat Client Server Connection Management Interface

Provides connection establishment, management, and thread-safe packet transmission functions for communicating with ascii-chat servers.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
2025

Definition in file src/client/server.h.

Enumeration Type Documentation

◆ connection_error_t

Connection establishment error codes.

These codes are returned by server_connection_establish() to indicate different failure modes. Zero indicates success.

Enumerator
CONNECTION_SUCCESS 

Connection established successfully.

CONNECTION_WARNING_NO_CLIENT_AUTH 

Server not using client verification (warning).

CONNECTION_ERROR_GENERIC 

Generic error (retry allowed).

CONNECTION_ERROR_AUTH_FAILED 

Authentication failure (no retry).

CONNECTION_ERROR_HOST_KEY_FAILED 

Host key verification failed (no retry).

Definition at line 34 of file src/client/server.h.

34 {
connection_error_t
Connection establishment error codes.
@ CONNECTION_ERROR_GENERIC
Generic error (retry allowed).
@ CONNECTION_ERROR_HOST_KEY_FAILED
Host key verification failed (no retry).
@ CONNECTION_SUCCESS
Connection established successfully.
@ CONNECTION_ERROR_AUTH_FAILED
Authentication failure (no retry).
@ CONNECTION_WARNING_NO_CLIENT_AUTH
Server not using client verification (warning).

Function Documentation

◆ server_connection_get_client_id()

uint32_t server_connection_get_client_id ( client_connection_t * connection)

Get client ID assigned by server.

Returns
Client ID or 0 if not connected
Client ID (based on local port) or 0 if not connected

Definition at line 226 of file src/client/server.c.

226 {
227 return connection->my_client_id;
228}

References client_connection::my_client_id.

◆ server_connection_get_ip()

const char * server_connection_get_ip ( client_connection_t * connection)

Get resolved server IP address.

Returns
Server IP address string (IPv4 or IPv6)

Returns the server's IP address that was resolved during connection establishment. Used for known_hosts verification and logging.

Returns
Server IP address string (IPv4 or IPv6), or empty string if not connected

Definition at line 240 of file src/client/server.c.

240 {
241 return connection->server_ip;
242}
char server_ip[HOSTNAME_BUFFER_SIZE]

References client_connection::server_ip.

◆ server_connection_get_port()

int server_connection_get_port ( client_connection_t * connection)

Get the server port.

Returns
Server port number

Returns the currently configured server port.

Returns
Server port number (0 if not set)

Definition at line 286 of file src/client/server.c.

286 {
287 return connection->server_port;
288}

References client_connection::server_port.

◆ server_connection_get_remote_error()

asciichat_error_t server_connection_get_remote_error ( client_connection_t * connection)

Definition at line 130 of file src/client/server.c.

130 {
131 return (asciichat_error_t)atomic_load_int(&connection->remote_error);
132}
int atomic_load_int(atomic_t *a)
Atomically load an int value.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48

References atomic_load_int(), and client_connection::remote_error.

◆ server_connection_get_transport()

struct acip_transport * server_connection_get_transport ( client_connection_t * connection)

Get ACIP transport instance.

Returns
Transport instance or NULL if not connected

Definition at line 208 of file src/client/server.c.

208 {
209 return atomic_ptr_load(&connection->transport);
210}
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.

References atomic_ptr_load(), and client_connection::transport.

Referenced by client_protocol_start(), threaded_send_audio_batch_packet(), threaded_send_audio_opus(), threaded_send_audio_opus_batch(), threaded_send_client_join_packet(), threaded_send_image_frame(), threaded_send_image_frame_encoded(), and threaded_send_packet().

◆ server_connection_init()

int server_connection_init ( client_connection_t * connection)

Initialize server connection management subsystem.

Returns
0 on success, negative on error

Initialize server connection management subsystem.

Sets up the send mutex and initializes connection state variables. Must be called once during client startup before any connection attempts.

Returns
0 on success, non-zero on failure

Definition at line 159 of file src/client/server.c.

159 {
160 ASCII_OTEL_SCOPE(SERVER_CONNECTION_INIT);
161 // Initialize mutex for thread-safe packet sending
162 if (mutex_init(&connection->send_mutex, "send") != 0) {
163 log_error("Failed to initialize send mutex");
164 return -1;
165 }
166
167 connection->send_mutex_initialized = true;
168
169 // Initialize connection state
170 atomic_ptr_store(&connection->transport, NULL);
171 atomic_store_bool(&connection->connection_active, false);
172 atomic_store_bool(&connection->connection_lost, false);
173 connection->my_client_id = 0;
174
175 return 0;
176}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77

References ASCII_OTEL_SCOPE, atomic_ptr_store(), atomic_store_bool(), client_connection::connection_active, client_connection::connection_lost, log_error, client_connection::my_client_id, client_connection::send_mutex, client_connection::send_mutex_initialized, and client_connection::transport.

Referenced by client_connection_create().

◆ server_connection_is_active()

bool server_connection_is_active ( client_connection_t * connection)

Establish connection to ascii-chat server.

Attempts to connect to the specified server with full capability negotiation. Implements reconnection logic with exponential backoff for failed attempts. On successful connection, performs initial handshake including terminal capabilities and client join protocol.

Parameters
addressServer IP address or hostname
portServer port number
reconnect_attemptCurrent reconnection attempt number (0 for first)
first_connectionTrue if this is the initial connection attempt
has_ever_connectedTrue if a connection was ever successfully established
Returns
0 on success, negative on error

Definition at line 195 of file src/client/server.c.

195 {
196 if (!connection)
197 return false;
198 return atomic_load_bool(&connection->connection_active) && atomic_ptr_load(&connection->transport) != NULL;
199}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.

References atomic_load_bool(), atomic_ptr_load(), client_connection::connection_active, and client_connection::transport.

Referenced by threaded_send_image_frame(), and threaded_send_image_frame_encoded().

◆ server_connection_is_lost()

bool server_connection_is_lost ( client_connection_t * connection)

Check if connection loss was detected.

Returns
true if connection lost, false otherwise

Check if connection loss was detected.

Returns
true if connection loss was flagged, false otherwise

Definition at line 334 of file src/client/server.c.

334 {
335 if (!connection)
336 return true;
337 return atomic_load_bool(&connection->connection_lost);
338}

References atomic_load_bool(), and client_connection::connection_lost.

Referenced by client_protocol_connection_lost().

◆ server_connection_lost()

void server_connection_lost ( client_connection_t * connection)

Signal that connection has been lost.

Definition at line 316 of file src/client/server.c.

316 {
317 ASCII_OTEL_SCOPE(CONNECTION_LOST);
318 if (!atomic_exchange_bool(&connection->connection_lost, true))
319 ascii_otel_metric(ASCII_OTEL_METRIC_DISCONNECT, 1);
320 atomic_store_bool(&connection->connection_active, false);
321
322 // Don't re-enable terminal logging here - let the splash screen handle it
323 // The reconnection splash will capture and display logs properly
325}
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
void display_full_reset()
Perform full display reset.
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:159

References ascii_otel_metric(), ASCII_OTEL_SCOPE, atomic_exchange_bool(), atomic_store_bool(), client_connection::connection_active, client_connection::connection_lost, and display_full_reset().

Referenced by threaded_send_audio_batch_packet(), threaded_send_audio_opus(), threaded_send_audio_opus_batch(), threaded_send_image_frame(), threaded_send_image_frame_encoded(), and threaded_send_packet().

◆ server_connection_pong_received()

void server_connection_pong_received ( client_connection_t * connection)

Signal that connection has been lost.

Called by other modules (typically protocol handlers) when they detect connection failure. Triggers reconnection logic in main loop.

Definition at line 309 of file src/client/server.c.

309 {
310 uint64_t sent = atomic_load_u64(&connection->telemetry_ping_ns);
311 if (sent && sent != UINT64_MAX && atomic_cas_u64(&connection->telemetry_ping_ns, &sent, 0)) {
312 uint64_t now = time_get_ns();
313 stats_duration_record(stats_runtime_scope(), STATS_DURATION_RTT, now >= sent ? now - sent : 0);
314 }
315}
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
unsigned long long uint64_t
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78

References atomic_cas_u64(), atomic_load_u64(), stats_duration_record(), STATS_DURATION_RTT, stats_runtime_scope(), and client_connection::telemetry_ping_ns.

◆ server_connection_set_ip()

void server_connection_set_ip ( client_connection_t * connection,
const char * ip )

Set the server IP address.

Parameters
ipServer IP address string

Updates the global server IP address for the active transport connection.

Parameters
ipServer IP address string

Definition at line 253 of file src/client/server.c.

253 {
254 if (ip) {
255 SAFE_STRNCPY(connection->server_ip, ip, sizeof(connection->server_ip));
256 log_debug("Server IP set to: %s", connection->server_ip);
257 } else {
258 connection->server_ip[0] = '\0';
259 log_debug("Server IP cleared");
260 }
261}
#define SAFE_STRNCPY(dst, src, size)
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589

References log_debug, SAFE_STRNCPY, and client_connection::server_ip.

◆ server_connection_set_port()

void server_connection_set_port ( client_connection_t * connection,
int port )

Set the server port.

Parameters
portServer port number

Updates the global server port for the active transport connection.

Parameters
portServer port number

Definition at line 272 of file src/client/server.c.

272 {
273 connection->server_port = port;
274 log_debug("Server port set to: %d", connection->server_port);
275}

References log_debug, and client_connection::server_port.

◆ server_connection_set_remote_error()

void server_connection_set_remote_error ( client_connection_t * connection,
asciichat_error_t code )

Atomic flag indicating if connection is currently active.

Thread-safe flag indicating whether the connection is established and active. Checked by all threads to determine if they can use the socket safely. Set to true on successful connection, false on disconnection.

Definition at line 127 of file src/client/server.c.

127 {
128 atomic_store_int(&connection->remote_error, code);
129}
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.

References atomic_store_int(), and client_connection::remote_error.

◆ server_connection_set_transport()

void server_connection_set_transport ( client_connection_t * connection,
struct acip_transport * transport )

Set ACIP transport instance from connection fallback.

Parameters
transportTransport instance created by connection_attempt_with_fallback()

Used to integrate the transport from the 3-stage connection fallback orchestrator (TCP → STUN → TURN) into the server connection management layer.

Definition at line 212 of file src/client/server.c.

212 {
213 atomic_ptr_store(&connection->transport, transport);
214 atomic_store_bool(&connection->connection_active, transport != NULL);
215 if (transport)
216 atomic_store_bool(&connection->connection_lost, false);
217}

References atomic_ptr_store(), atomic_store_bool(), client_connection::connection_active, client_connection::connection_lost, and client_connection::transport.

Referenced by client_connection_start().

◆ server_connection_shutdown()

void server_connection_shutdown ( client_connection_t * connection)

Interrupt connection I/O from normal thread context.

Definition at line 292 of file src/client/server.c.

292 {
293 ASCII_OTEL_SCOPE(SERVER_CONNECTION_SHUTDOWN);
294 if (!connection)
295 return;
296 atomic_store_bool(&connection->connection_active, false);
297 atomic_store_bool(&connection->connection_lost, true);
299}
void session_connection_interrupt_transport(acip_transport_t *transport)

References ASCII_OTEL_SCOPE, atomic_ptr_load(), atomic_store_bool(), client_connection::connection_active, client_connection::connection_lost, session_connection_interrupt_transport(), and client_connection::transport.

◆ server_send_audio()

int server_send_audio ( const float * samples,
int num_samples )

Send audio data to server.

Parameters
samplesAudio sample buffer
num_samplesNumber of samples
Returns
0 on success, negative on error

Referenced by client_audio_render_thread().

◆ server_send_audio_batch()

int server_send_audio_batch ( const float * samples,
int num_samples,
int batch_count )

Send batched audio data to server.

Parameters
samplesBatched audio samples
num_samplesTotal sample count
batch_countNumber of packets in batch
Returns
0 on success, negative on error

◆ server_send_packet()

int server_send_packet ( packet_type_t type,
const void * data,
size_t len )

Send general packet to server.

Parameters
typePacket type identifier
dataPacket payload
lenPayload length
Returns
0 on success, negative on error

◆ server_send_ping()

int server_send_ping ( )

Send ping keepalive packet.

Returns
0 on success, negative on error

◆ server_send_pong()

int server_send_pong ( )

Send pong response packet.

Returns
0 on success, negative on error

◆ server_send_stream_start()

int server_send_stream_start ( uint32_t stream_type)

Send stream start notification.

Parameters
stream_typeType of stream (audio/video)
Returns
0 on success, negative on error

◆ server_send_stream_stop()

int server_send_stream_stop ( uint32_t stream_type)

Send stream stop notification.

Parameters
stream_typeType of stream (audio/video)
Returns
0 on success, negative on error

◆ server_send_terminal_capabilities()

int server_send_terminal_capabilities ( unsigned short width,
unsigned short height )

Send terminal capabilities to server.

Parameters
widthTerminal width in characters
heightTerminal height in characters
Returns
0 on success, negative on error

References height, and width.

◆ threaded_send_audio_batch_packet()

asciichat_error_t threaded_send_audio_batch_packet ( client_connection_t * connection,
const float * samples,
int num_samples,
int batch_count )

Thread-safe batched audio packet transmission.

Parameters
samplesAudio sample buffer containing batched samples
num_samplesTotal number of samples in the batch
batch_countNumber of audio chunks in this batch
Returns
0 on success, negative on error

Sends a batched audio packet to the server with proper mutex protection and connection state checking. Automatically handles encryption if crypto is ready.

Parameters
samplesAudio sample buffer containing batched samples
num_samplesTotal number of samples in the batch
batch_countNumber of audio chunks in this batch
Returns
0 on success, negative on error

Definition at line 400 of file src/client/server.c.

400 {
401 // Check connection status and get transport reference
402 acip_transport_t *transport = server_connection_get_transport(connection);
403 if (!atomic_load_bool(&connection->connection_active) || !transport) {
404 return SET_ERRNO(ERROR_NETWORK, "Connection not active");
405 }
406
407 // The ACIP outbound scheduler serializes transport admission and writes.
408 asciichat_error_t result = acip_send_audio_batch(transport, samples, (uint32_t)num_samples, (uint32_t)batch_count);
409
410 // If send failed due to network error, signal connection loss
411 if (result != ASCIICHAT_OK) {
413 server_connection_lost(connection);
414 return result;
415 }
416
417 return ASCIICHAT_OK;
418}
#define SET_ERRNO(code,...)
unsigned int uint32_t
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
bool network_error_is_local_rejection(asciichat_error_t code)
asciichat_error_t acip_send_audio_batch(acip_transport_t *transport, const float *samples, uint32_t num_samples, uint32_t batch_count)
Send audio batch packet.
Definition send.c:286
void server_connection_lost(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.

References acip_send_audio_batch(), ASCIICHAT_OK, atomic_load_bool(), client_connection::connection_active, ERROR_NETWORK, network_error_is_local_rejection(), server_connection_get_transport(), server_connection_lost(), and SET_ERRNO.

◆ threaded_send_audio_opus()

asciichat_error_t threaded_send_audio_opus ( client_connection_t * connection,
const uint8_t * opus_data,
size_t opus_size,
int sample_rate,
int frame_duration )

Thread-safe Opus audio frame transmission.

Sends a single Opus-encoded audio frame to the server with proper synchronization and encryption support.

Parameters
opus_dataOpus-encoded audio data
opus_sizeSize of encoded frame
sample_rateSample rate in Hz
frame_durationFrame duration in milliseconds
Returns
ASCIICHAT_OK on success, error code on failure

Sends a single Opus-encoded audio frame to the server with proper synchronization and encryption support.

Parameters
opus_dataOpus-encoded audio data
opus_sizeSize of encoded frame
sample_rateSample rate in Hz
frame_durationFrame duration in milliseconds
Returns
0 on success, negative on error

Definition at line 434 of file src/client/server.c.

434 {
435 // Check connection status and get transport reference
436 acip_transport_t *transport = server_connection_get_transport(connection);
437 if (!atomic_load_bool(&connection->connection_active) || !transport) {
438 return SET_ERRNO(ERROR_NETWORK, "Connection not active or transport unavailable");
439 }
440
441 // The protocol carries Opus through batches, including a one-frame batch.
442 // Reuse its serializer so the count and frame-size table are always present.
443 if (opus_size > UINT16_MAX)
444 return SET_ERRNO(ERROR_INVALID_PARAM, "Opus frame exceeds its wire size field");
445 uint16_t frame_size = (uint16_t)opus_size;
446 asciichat_error_t result = acip_send_audio_opus_batch(transport, opus_data, opus_size, &frame_size, 1, sample_rate, frame_duration);
447
448 // If send failed due to network error, signal connection loss
449 if (result != ASCIICHAT_OK) {
451 server_connection_lost(connection);
452 return result;
453 }
454
455 return ASCIICHAT_OK;
456}
unsigned short uint16_t
@ ERROR_INVALID_PARAM
asciichat_error_t acip_send_audio_opus_batch(acip_transport_t *transport, const void *opus_data, size_t opus_len, const uint16_t *frame_sizes, uint32_t frame_count, uint32_t sample_rate, uint32_t frame_duration)
Send batched Opus-encoded audio frames.
Definition send.c:338

References acip_send_audio_opus_batch(), ASCIICHAT_OK, atomic_load_bool(), client_connection::connection_active, ERROR_INVALID_PARAM, ERROR_NETWORK, network_error_is_local_rejection(), server_connection_get_transport(), server_connection_lost(), and SET_ERRNO.

◆ threaded_send_audio_opus_batch()

asciichat_error_t threaded_send_audio_opus_batch ( client_connection_t * connection,
const uint8_t * opus_data,
size_t opus_size,
const uint16_t * frame_sizes,
int frame_count )

Thread-safe Opus audio batch packet transmission.

Sends a batch of Opus-encoded audio frames to the server with proper synchronization and encryption support.

Parameters
opus_dataOpus-encoded audio data (multiple frames concatenated)
opus_sizeTotal size of Opus data in bytes
frame_sizesArray of individual frame sizes (variable-length frames)
frame_countNumber of Opus frames in the batch
Returns
ASCIICHAT_OK on success, error code on failure

Sends a batch of Opus-encoded audio frames to the server with proper synchronization and encryption support.

Parameters
opus_dataOpus-encoded audio data (multiple frames concatenated)
opus_sizeTotal size of Opus data in bytes
frame_sizesArray of individual frame sizes (variable-length frames)
frame_countNumber of Opus frames in the batch
Returns
0 on success, negative on error

Definition at line 472 of file src/client/server.c.

472 {
473 // Check connection status and get transport reference
474 acip_transport_t *transport = server_connection_get_transport(connection);
475 if (!atomic_load_bool(&connection->connection_active) || !transport) {
476 return SET_ERRNO(ERROR_NETWORK, "Connection not active or transport unavailable");
477 }
478
479 // Network I/O happens while holding mutex to prevent concurrent socket writes
480 // Opus uses 20ms frames at 48kHz (960 samples = 20ms)
481 asciichat_error_t result = acip_send_audio_opus_batch(transport, opus_data, opus_size, frame_sizes, frame_count, 48000, 20);
482
483 // If send failed due to network error, signal connection loss
484 if (result != ASCIICHAT_OK) {
486 server_connection_lost(connection);
487 return result;
488 }
489
490 return ASCIICHAT_OK;
491}

References acip_send_audio_opus_batch(), ASCIICHAT_OK, atomic_load_bool(), client_connection::connection_active, ERROR_NETWORK, network_error_is_local_rejection(), server_connection_get_transport(), server_connection_lost(), and SET_ERRNO.

◆ threaded_send_client_join_packet()

asciichat_error_t threaded_send_client_join_packet ( client_connection_t * connection,
const char * display_name,
uint32_t capabilities )

Thread-safe client join packet transmission.

Parameters
display_nameClient display name
capabilitiesClient capability flags
Returns
0 on success, negative on error

Sends client join packet with display name and capabilities to the server.

Parameters
display_nameClient display name
capabilitiesClient capability flags
Returns
0 on success, negative on error

Definition at line 692 of file src/client/server.c.

692 {
693 // Connection and transport availability is checked by threaded_send_packet()
694
695 // Build CLIENT_JOIN packet locally
696 client_info_packet_t join_packet;
697 SAFE_MEMSET(&join_packet, sizeof(join_packet), 0, sizeof(join_packet));
698 join_packet.client_id = HOST_TO_NET_U32(0); // Will be assigned by server
699 SAFE_SNPRINTF(join_packet.display_name, MAX_DISPLAY_NAME_LEN, "%s", display_name ? display_name : "Unknown");
700 join_packet.capabilities = HOST_TO_NET_U32(capabilities);
701
702 // Use threaded_send_packet() which handles encryption
703 int send_result = threaded_send_packet(connection, PACKET_TYPE_CLIENT_JOIN, &join_packet, sizeof(join_packet));
704 if (send_result == 0) {
705 bool active = atomic_load_u64(&connection->connection_active);
706 acip_transport_t *transport = server_connection_get_transport(connection);
707 if (active && transport) {
708 log_net_message(transport, LOG_INFO, REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER, __FILE__, __LINE__, __func__, "CLIENT_JOIN sent (display=\"%s\", capabilities=0x%x)", join_packet.display_name,
709 capabilities);
710 }
711 }
712 return send_result;
713}
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define SAFE_MEMSET(dest, dest_size, ch, count)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define MAX_DISPLAY_NAME_LEN
Maximum display name length in characters.
asciichat_error_t log_net_message(struct acip_transport *transport, log_level_t level, remote_log_direction_t direction, const char *file, int line, const char *func, const char *fmt,...)
Log a message to all destinations (network, file, and terminal).
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:20
@ PACKET_TYPE_CLIENT_JOIN
Client announces capability to send media.
Definition packet.h:425
asciichat_error_t threaded_send_packet(client_connection_t *connection, packet_type_t type, const void *data, size_t len)
Thread-safe packet transmission.
Client information packet structure.
Definition packet.h:703
char display_name[32]
User display name (null-terminated, max MAX_DISPLAY_NAME_LEN bytes).
Definition packet.h:707
uint32_t client_id
Unique client identifier (1-9, 0 = server).
Definition packet.h:705
uint32_t capabilities
Client capabilities bitmask (CLIENT_CAP_VIDEO | CLIENT_CAP_AUDIO | CLIENT_CAP_COLOR | CLIENT_CAP_STRE...
Definition packet.h:710
#define LOG_INFO
Definition types.h:44

References atomic_load_u64(), client_info_packet_t::capabilities, client_info_packet_t::client_id, client_connection::connection_active, client_info_packet_t::display_name, HOST_TO_NET_U32, LOG_INFO, log_net_message(), MAX_DISPLAY_NAME_LEN, PACKET_TYPE_CLIENT_JOIN, REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER, SAFE_MEMSET, SAFE_SNPRINTF, server_connection_get_transport(), and threaded_send_packet().

◆ threaded_send_image_frame()

asciichat_error_t threaded_send_image_frame ( client_connection_t * connection,
const void * pixel_data,
uint32_t width,
uint32_t height,
uint32_t pixel_format )

Thread-safe image frame transmission.

Sends image frames with serialization via mutex to prevent race conditions when multiple threads write to the same TCP socket.

Parameters
pixel_dataPixel data buffer (RGB24 format)
widthFrame width in pixels
heightFrame height in pixels
pixel_formatPixel format (1=RGB24)
Returns
ASCIICHAT_OK on success, error code on failure

Sends image frames with serialization via g_send_mutex to prevent race conditions when multiple threads write to the same TCP socket.

Parameters
pixel_dataPixel data buffer
widthFrame width in pixels
heightFrame height in pixels
pixel_formatPixel format (1=RGB24)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 507 of file src/client/server.c.

507 {
508 if (!pixel_data) {
509 return SET_ERRNO(ERROR_INVALID_PARAM, "Pixel data is NULL");
510 }
511
512 // Get transport reference - may be NULL if connection was lost
513 acip_transport_t *transport = server_connection_get_transport(connection);
514 if (!transport || !server_connection_is_active(connection)) {
515 return SET_ERRNO(ERROR_NETWORK, "Transport unavailable");
516 }
517
518 // Submit through the connection-owned outbound scheduler.
519 asciichat_error_t result = acip_send_image_frame(transport, pixel_data, width, height, pixel_format);
520
521 // Unlock after send completes
522 // If send failed due to network error, signal connection loss
523 if (result != ASCIICHAT_OK) {
525 server_connection_lost(connection);
526 return result;
527 }
528
529 return ASCIICHAT_OK;
530}
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
asciichat_error_t acip_send_image_frame(acip_transport_t *transport, const void *pixel_data, uint32_t width, uint32_t height, uint32_t pixel_format)
Send image frame to server (client → server).
bool server_connection_is_active(client_connection_t *connection)
Establish connection to ascii-chat server.

References acip_send_image_frame(), ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, height, network_error_is_local_rejection(), server_connection_get_transport(), server_connection_is_active(), server_connection_lost(), SET_ERRNO, and width.

◆ threaded_send_image_frame_encoded()

asciichat_error_t threaded_send_image_frame_encoded ( client_connection_t * connection,
const void * pixel_data,
uint32_t width,
uint32_t height,
video_codec_t codec,
bool * encoding_failed )

Send HEVC/H.264-encoded video frame to server (thread-safe).

Encodes RGB frame using HEVC/H.264 codec before transmission. Much more bandwidth-efficient than raw pixel transmission. Uses mutex to prevent interleaving with other packet sends.

Parameters
pixel_dataRGB pixel data from camera
widthFrame width in pixels
heightFrame height in pixels
codecHEVC or H.264 packet and encoder selection
encoding_failedSet only for encoder failures, never transport failures
Returns
ASCIICHAT_OK on success, error code on failure

Send HEVC/H.264-encoded video frame to server (thread-safe).

Encodes RGB frame using H.265 codec before transmission. Much more bandwidth-efficient than raw pixel transmission. Uses mutex to prevent interleaving with other packet sends.

Parameters
pixel_dataRGB pixel data from camera
widthFrame width in pixels
heightFrame height in pixels
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 546 of file src/client/server.c.

546 {
547 if (!encoding_failed)
548 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing video encoding status output");
549 *encoding_failed = false;
550 if (!pixel_data || width > UINT16_MAX || height > UINT16_MAX) {
551 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid video frame");
552 }
553 // The capture thread creates the selected encoder only when a frame is ready.
554 if (!connection->video_encoder) {
556 if (!connection->video_encoder) {
557 *encoding_failed = true;
558 return GET_ERRNO();
559 }
560 }
561 h265_encoder_t *encoder = connection->video_encoder;
562#ifndef __EMSCRIPTEN__
563 acip_transport_t *encoder_transport = server_connection_get_transport(connection);
566#endif
567 size_t output_buffer_size = 5 + ((size_t)width * height * 3) + 65536;
568 if (buffer_workspace_reserve(&connection->encoded_video_workspace, NULL, output_buffer_size) != ASCIICHAT_OK)
569 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate video output buffer: %zu bytes", output_buffer_size);
570 uint8_t *output_buffer = connection->encoded_video_workspace.data;
571
572 // h265_encode already writes the five-byte ACIP envelope for either codec.
573 size_t total_size = output_buffer_size;
574 asciichat_error_t encode_result = h265_encode(encoder, (uint16_t)width, (uint16_t)height, (const uint8_t *)pixel_data, output_buffer, &total_size);
575 if (encode_result != ASCIICHAT_OK || total_size == 0) {
576 *encoding_failed = encode_result != ASCIICHAT_OK;
577 return encode_result;
578 }
579
580 // NOW acquire the send mutex just for the actual network transmission
581 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_3] About to acquire g_send_mutex for network send");
582 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_4] ✅ Acquired g_send_mutex, checking transport");
583
584 // Get transport reference - may be NULL if connection was lost
585 acip_transport_t *transport = server_connection_get_transport(connection);
586 if (!transport || !server_connection_is_active(connection)) {
587 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_5] Transport unavailable, releasing mutex");
588 return SET_ERRNO(ERROR_NETWORK, "Transport unavailable");
589 }
590
591 // Submit through the connection-owned outbound scheduler.
592 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_6] Sending packet via transport (%zu bytes)", total_size);
594 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_7] packet_send_via_transport returned: %d", result);
595
596 // Unlock after send completes
597 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_8] ✅ Released g_send_mutex");
598
599 log_debug_every(US_PER_SEC_INT, "[H265_SEND_FRAME_9] Retained video output workspace");
600
601 // If send failed due to network error, signal connection loss
602 if (result != ASCIICHAT_OK) {
604 server_connection_lost(connection);
605 return result;
606 }
607
608 return ASCIICHAT_OK;
609}
#define GET_ERRNO()
bool acip_outbound_needs_keyframe(acip_transport_t *transport, uint16_t type, uint32_t id)
asciichat_error_t buffer_workspace_reserve(buffer_workspace_t *workspace, buffer_domain_t *domain, size_t capacity)
Definition buffer.c:353
@ VIDEO_CODEC_H264
H.264 (AVC) video codec.
Definition codecs.h:32
asciichat_error_t h265_encode(h265_encoder_t *encoder, uint16_t width, uint16_t height, const uint8_t *ascii_data, uint8_t *output_buf, size_t *output_size)
Definition encoder.c:316
void h265_encoder_request_keyframe(h265_encoder_t *encoder)
Definition encoder.c:436
struct h265_encoder h265_encoder_t
h265 encoder is intentionally a small, concrete record. Fields such as codec_ctx, codec,...
h265_encoder_t * video_encoder_create(video_codec_t codec_type, uint16_t initial_width, uint16_t initial_height)
Definition encoder.c:90
unsigned char uint8_t
@ ERROR_MEMORY
Definition error_codes.h:55
#define US_PER_SEC_INT
Definition time.h:177
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
buffer_workspace_t encoded_video_workspace
h265_encoder_t *volatile video_encoder

References acip_outbound_needs_keyframe(), ASCIICHAT_OK, buffer_workspace_reserve(), buffer_workspace_t::data, client_connection::encoded_video_workspace, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, GET_ERRNO, h265_encode(), h265_encoder_request_keyframe(), height, log_debug_every, network_error_is_local_rejection(), packet_send_via_transport(), PACKET_TYPE_IMAGE_FRAME_H264, PACKET_TYPE_IMAGE_FRAME_H265, server_connection_get_transport(), server_connection_is_active(), server_connection_lost(), SET_ERRNO, US_PER_SEC_INT, VIDEO_CODEC_H264, client_connection::video_encoder, video_encoder_create(), and width.

◆ threaded_send_packet()

asciichat_error_t threaded_send_packet ( client_connection_t * connection,
packet_type_t type,
const void * data,
size_t len )

Thread-safe packet transmission.

Sends a packet to the server with proper mutex protection and connection state checking. Automatically handles encryption if crypto is ready.

Parameters
typePacket type identifier
dataPacket payload
lenPayload length
Returns
ASCIICHAT_OK on success, error code on failure

Sends a packet to the server with proper mutex protection and connection state checking. Automatically handles encryption if crypto is ready.

Parameters
typePacket type identifier
dataPacket payload
lenPayload length
Returns
0 on success, negative on error

Definition at line 361 of file src/client/server.c.

361 {
362 // Check connection status and get transport reference
363 acip_transport_t *transport = server_connection_get_transport(connection);
364 if (!atomic_load_bool(&connection->connection_active) || !transport) {
365 log_debug("[TRANSPORT_LIFECYCLE] threaded_send_packet() check failed: active=%s, transport=%p", atomic_load_bool(&connection->connection_active) ? "true" : "false",
366 (void *)server_connection_get_transport(connection));
367 return SET_ERRNO(ERROR_NETWORK, "Connection not active or transport unavailable");
368 }
369 log_debug_every(LOG_RATE_SLOW, "[TRANSPORT_LIFECYCLE] threaded_send_packet() using transport=%p, is_connected=%s", (void *)transport, acip_transport_is_connected(transport) ? "true" : "false");
370
371 // The ACIP outbound scheduler serializes transport admission and writes.
372 asciichat_error_t result = packet_send_via_transport(transport, type, data, len, 0);
373
374 // Unlock after send completes
375 // If send failed due to network error, signal connection loss
376 if (result != ASCIICHAT_OK) {
377 log_debug("Packet send failed");
379 server_connection_lost(connection);
380 return result;
381 }
382
383 return ASCIICHAT_OK;
384}
#define LOG_RATE_SLOW
Log rate limit: 10 seconds (10,000,000 microseconds).
Definition log_rates.h:39

References ASCIICHAT_OK, atomic_load_bool(), client_connection::connection_active, ERROR_NETWORK, log_debug, log_debug_every, LOG_RATE_SLOW, network_error_is_local_rejection(), packet_send_via_transport(), server_connection_get_transport(), server_connection_lost(), and SET_ERRNO.

Referenced by threaded_send_client_join_packet(), threaded_send_ping_packet(), threaded_send_pong_packet(), threaded_send_stream_start_packet(), and threaded_send_terminal_size_with_auto_detect().

◆ threaded_send_ping_packet()

asciichat_error_t threaded_send_ping_packet ( client_connection_t * connection)

Thread-safe ping packet transmission.

Returns
0 on success, negative on error

Definition at line 618 of file src/client/server.c.

618 {
619 // Use threaded_send_packet which handles encryption, mutex locking, and connection state
620 // Without a probe ID, overlapping pings make subsequent pongs ambiguous.
621 // Keep sending normally, but suppress RTT samples for this connection.
622 client_connection_mark_ping_sent(connection, time_get_ns());
623 asciichat_error_t result = threaded_send_packet(connection, PACKET_TYPE_PING, NULL, 0);
624 if (result != ASCIICHAT_OK)
625 atomic_store_u64(&connection->telemetry_ping_ns, UINT64_MAX);
626 return result;
627}
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421

References ASCIICHAT_OK, atomic_store_u64(), PACKET_TYPE_PING, client_connection::telemetry_ping_ns, and threaded_send_packet().

◆ threaded_send_pong_packet()

asciichat_error_t threaded_send_pong_packet ( client_connection_t * connection)

Thread-safe pong packet transmission.

Returns
0 on success, negative on error

Definition at line 636 of file src/client/server.c.

636 {
637 // Use threaded_send_packet which handles encryption, mutex locking, and connection state
638 return threaded_send_packet(connection, PACKET_TYPE_PONG, NULL, 0);
639}
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423

References PACKET_TYPE_PONG, and threaded_send_packet().

◆ threaded_send_stream_start_packet()

asciichat_error_t threaded_send_stream_start_packet ( client_connection_t * connection,
uint32_t stream_type )

Thread-safe stream start packet transmission.

Parameters
stream_typeType of stream (audio/video)
Returns
0 on success, negative on error

Definition at line 649 of file src/client/server.c.

649 {
650 // Connection and transport availability is checked by threaded_send_packet()
651
652 // Build STREAM_START packet locally
653 uint32_t type_data = HOST_TO_NET_U32(stream_type);
654
655 // Use threaded_send_packet() which handles encryption
656 return threaded_send_packet(connection, PACKET_TYPE_STREAM_START, &type_data, sizeof(type_data));
657}
@ PACKET_TYPE_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429

References HOST_TO_NET_U32, PACKET_TYPE_STREAM_START, and threaded_send_packet().

Referenced by client_protocol_start().

◆ threaded_send_terminal_size_with_auto_detect()

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.

Parameters
widthTerminal width in characters
heightTerminal height in characters
Returns
0 on success, negative on error

Sends terminal capabilities packet to the server including terminal size, color capabilities, and rendering preferences. Auto-detects terminal capabilities if not explicitly specified.

Parameters
widthTerminal width in characters
heightTerminal height in characters
Returns
0 on success, negative on error

Definition at line 672 of file src/client/server.c.

672 {
675 asciichat_error_t result = threaded_send_packet(connection, PACKET_TYPE_CLIENT_CAPABILITIES, &packet, sizeof(packet));
676 if (result == ASCIICHAT_OK)
677 connection->advertised_dimensions = (terminal_size_t){.cols = width, .rows = height};
678 return result;
679}
void session_protocol_build_capabilities(unsigned short width, unsigned short height, terminal_capabilities_packet_t *packet)
@ PACKET_TYPE_CLIENT_CAPABILITIES
Client reports terminal capabilities.
Definition packet.h:419
terminal_size_t advertised_dimensions
Terminal capabilities packet structure (Packet Type 5).
Definition packet.h:1093

References client_connection::advertised_dimensions, ASCIICHAT_OK, height, PACKET_TYPE_CLIENT_CAPABILITIES, session_protocol_build_capabilities(), threaded_send_packet(), and width.

Referenced by client_protocol_start().