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.h File Reference

Server packet processing and protocol implementation. More...

Go to the source code of this file.

Functions

void handle_image_frame_packet (client_info_t *client, void *data, size_t len)
 Process IMAGE_FRAME packet - store client's video data for rendering.
void handle_image_frame_h264_packet (client_info_t *client, const void *data, size_t len)
void handle_image_frame_h265_packet (client_info_t *client, const void *data, size_t len)
 Process H.265-encoded image frame from client.
void handle_audio_batch_packet (client_info_t *client, const void *data, size_t len)
 Process AUDIO_BATCH packet - store efficiently batched audio samples.
void handle_audio_opus_batch_packet (client_info_t *client, const void *data, size_t len)
 Process AUDIO_OPUS_BATCH packet - efficient Opus-encoded audio batch from client.
void handle_audio_opus_packet (client_info_t *client, const void *data, size_t len)
 Process AUDIO_OPUS packet - decode single Opus frame from client.
void handle_audio_packet (client_info_t *client, const void *data, size_t len)
 Process AUDIO packet - store single audio sample batch (legacy format).
void handle_client_capabilities_packet (client_info_t *client, const void *data, size_t len)
void handle_size_packet (client_info_t *client, const void *data, size_t len)
 Process terminal size update packet - handle client window resize.
void handle_ping_packet (client_info_t *client, const void *data, size_t len)
 Handle PING packet - respond with PONG.
void handle_pong_packet (client_info_t *client, const void *data, size_t len)
 Handle PONG packet - client acknowledged our PING.
void handle_client_join_packet (client_info_t *client, const void *data, size_t len)
 Process CLIENT_JOIN packet - client announces identity and capabilities.
void handle_protocol_version_packet (client_info_t *client, const void *data, size_t len)
 Process PROTOCOL_VERSION packet - validate protocol compatibility.
void handle_stream_start_packet (client_info_t *client, const void *data, size_t len)
 Process STREAM_START packet - client requests to begin media transmission.
void handle_stream_stop_packet (client_info_t *client, const void *data, size_t len)
 Process STREAM_STOP packet - client requests to halt media transmission.
void handle_client_leave_packet (client_info_t *client, const void *data, size_t len)
 Process CLIENT_LEAVE packet - handle clean client disconnect.
void handle_remote_log_packet_from_client (client_info_t *client, const void *data, size_t len)
void disconnect_client_for_bad_data (client_info_t *client, const char *format,...)
int send_server_state_to_client (client_info_t *client)
 Send current server state to a specific client.
void broadcast_clear_console_to_all_clients (void)
 Signal all active clients to clear their displays before next video frame.
asciichat_error_t handle_runtime_settings (client_info_t *client, const void *data, size_t length)

Detailed Description

Server packet processing and protocol implementation.

Definition in file src/server/protocol.h.

Function Documentation

◆ broadcast_clear_console_to_all_clients()

void broadcast_clear_console_to_all_clients ( void )

Signal all active clients to clear their displays before next video frame.

Sets the needs_display_clear flag for all currently connected and active clients. This is used when the grid layout changes (clients join/leave) to ensure all clients clear their displays before receiving frames with the new layout.

ARCHITECTURE:

  • Uses atomic flag (needs_display_clear) instead of packet queue
  • Send thread checks flag and sends CLEAR_CONSOLE before next video frame
  • Guarantees CLEAR_CONSOLE arrives before new grid layout frame

SYNCHRONIZATION:

  • Acquires g_client_manager_rwlock for reading
  • Uses atomic operations for flag setting (no mutex needed)
  • Thread-safe access to client list

USAGE SCENARIO:

  • Called when active video source count changes
  • Ensures all clients clear before new grid layout is sent
  • Prevents visual artifacts from old content
Note
This function iterates all clients but only flags active ones
Non-blocking - just sets atomic flags

Definition at line 2043 of file server/protocol.c.

2043 {
2044 SET_ERRNO(ERROR_INVALID_STATE, "Unexpected console clear broadcast");
2045 log_warn("CLEAR_CONSOLE is now sent from render threads, not broadcast");
2046}
#define SET_ERRNO(code,...)
@ ERROR_INVALID_STATE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591

References ERROR_INVALID_STATE, log_warn, and SET_ERRNO.

◆ disconnect_client_for_bad_data()

void disconnect_client_for_bad_data ( client_info_t * client,
const char * format,
... )

Definition at line 167 of file server/protocol.c.

168 {
169 if (!client) {
170 return;
171 }
172
173 protocol_cleanup_thread_locals();
174
175 // Atomically set the disconnect flag and get the old value
176 // This ensures only one thread proceeds to disconnect (the first one)
177 bool already_requested =
179 if (already_requested) {
180 return; // Already disconnecting, don't do it again
181 }
182
183 char reason[BUFFER_SIZE_SMALL] = {0};
184 if (format) {
185 va_list args;
186 va_start(args, format);
187 safe_vsnprintf(reason, sizeof(reason), format, args);
188 va_end(args);
189 } else {
190 SAFE_STRNCPY(reason, "Protocol violation", sizeof(reason));
191 }
192
193 const char *reason_str = reason[0] != '\0' ? reason : "Protocol violation";
194 const char *client_id = client->client_id;
195
196 log_warn("Disconnecting client %s due to protocol violation: %s", client_id,
197 reason_str);
198 mutex_lock(&client->send_mutex);
199 if (client->transport)
201 mutex_unlock(&client->send_mutex);
202
203 log_debug("Setting active=false (client_id=%s, reason=%s)", client_id,
204 reason_str);
205 atomic_store_bool(&client->active, false);
206 atomic_store_bool(&client->shutting_down, true);
210}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_STRNCPY(dst, src, size)
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:81
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void network_connection_request_stop(network_connection_t *c)
action_args_t args
asciichat_error_t acip_send_error(acip_transport_t *transport, uint32_t error_code, const char *message)
Send error message packet.
Definition send.c:402
network_connection_t * network_connection
char client_id[MAX_CLIENT_ID_LEN]

◆ handle_audio_batch_packet()

void handle_audio_batch_packet ( client_info_t * client,
const void * data,
size_t len )

Process AUDIO_BATCH packet - store efficiently batched audio samples.

Handles the optimized audio packet format that bundles multiple sample chunks into a single packet. This reduces packet overhead and improves network efficiency for audio streaming.

PACKET STRUCTURE EXPECTED:

  • audio_batch_packet_t header:
    • uint32_t batch_count: Number of sample chunks in this batch
    • uint32_t total_samples: Total number of float samples
    • uint32_t sample_rate: Samples per second (typically 44100)
    • uint32_t channels: Number of audio channels (1 = mono)
  • float samples[total_samples]: IEEE 754 sample data

PERFORMANCE ADVANTAGES:

  • Reduces packet count by 5-10x compared to single audio packets
  • Lower network overhead and CPU context switching
  • Better burst tolerance with larger buffers

VALIDATION PERFORMED:

  • Header size matches audio_batch_packet_t
  • Total packet size matches header + samples
  • Sample count is within reasonable bounds
  • Client is authorized to send audio

BUFFER MANAGEMENT:

  • Extracts samples from packet payload
  • Stores in client->incoming_audio_buffer (same as single format)
  • Ring buffer automatically handles overflow
  • mixer.c consumes batched samples identically

ERROR HANDLING:

  • Invalid batch headers are logged and packet dropped
  • Oversized batches are rejected (prevents DoS)
  • Buffer allocation failures are handled gracefully
Parameters
clientSource client providing batched audio data
dataPacket payload containing batch header and samples
lenTotal size of packet payload in bytes
Note
This is the preferred audio packet format
Batching is transparent to audio processing pipeline
See also
handle_audio_packet() For legacy single-batch format
AUDIO_BATCH_SAMPLES For maximum batch size constant

Definition at line 1298 of file server/protocol.c.

1299 {
1300 // Log every audio batch packet reception
1302 "Received audio batch packet from client %s (len=%zu, "
1303 "is_sending_audio=%d)",
1304 client->client_id, len,
1306
1307 VALIDATE_NOTNULL_DATA(client, data, "AUDIO_BATCH");
1308 VALIDATE_MIN_SIZE(client, len, sizeof(audio_batch_packet_t), "AUDIO_BATCH");
1309 VALIDATE_AUDIO_STREAM_ENABLED(client, "AUDIO_BATCH");
1310
1311 // Parse batch header using utility function
1312 audio_batch_info_t batch_info;
1313 asciichat_error_t parse_result =
1314 audio_parse_batch_header(data, len, &batch_info);
1315 if (parse_result != ASCIICHAT_OK) {
1317 "Failed to parse audio batch header");
1318 return;
1319 }
1320
1321 uint32_t packet_batch_count = batch_info.batch_count;
1322 uint32_t total_samples = batch_info.total_samples;
1323 uint32_t sample_rate = batch_info.sample_rate;
1324 if (sample_rate != AUDIO_SAMPLE_RATE ||
1325 (batch_info.channels != 1 && batch_info.channels != 2) ||
1326 total_samples % batch_info.channels) {
1327 disconnect_client_for_bad_data(client, "Unsupported PCM audio format");
1328 return;
1329 }
1330
1331 (void)packet_batch_count;
1332 (void)sample_rate;
1333
1334 VALIDATE_NONZERO(client, packet_batch_count, "batch_count", "AUDIO_BATCH");
1335 VALIDATE_NONZERO(client, total_samples, "total_samples", "AUDIO_BATCH");
1336
1337 size_t samples_bytes = 0;
1338 if (safe_size_mul(total_samples, sizeof(uint32_t), &samples_bytes)) {
1340 client, "AUDIO_BATCH sample size overflow (samples=%u)", total_samples);
1341 return;
1342 }
1343
1344 size_t expected_size = sizeof(audio_batch_packet_t) + samples_bytes;
1345 if (len != expected_size) {
1347 client, "AUDIO_BATCH length mismatch: got %zu expected %zu", len,
1348 expected_size);
1349 return;
1350 }
1351
1352 // Bounds check to prevent integer overflow on allocation
1353 // Maximum allowed samples: AUDIO_BATCH_SAMPLES * 2 (2048 samples)
1354 // This prevents total_samples * sizeof(float) from exceeding 8KB
1355 const uint32_t MAX_AUDIO_SAMPLES = AUDIO_BATCH_SAMPLES * 2;
1356 if (total_samples > MAX_AUDIO_SAMPLES) {
1358 "AUDIO_BATCH too many samples: %u (max: %u)",
1359 total_samples, MAX_AUDIO_SAMPLES);
1360 return;
1361 }
1362
1363 const uint8_t *samples_ptr =
1364 (const uint8_t *)data + sizeof(audio_batch_packet_t);
1365
1366 // Safe allocation: total_samples is bounded above, so multiplication won't
1367 // overflow
1368 size_t alloc_size = (size_t)total_samples * AUDIO_CHANNELS * sizeof(float);
1369 float *samples = SAFE_MALLOC(alloc_size, float *);
1370 if (!samples) {
1372 "Failed to allocate memory for audio sample conversion");
1373 return;
1374 }
1375
1376 // Use helper function to dequantize samples
1377 asciichat_error_t dq_result =
1378 audio_dequantize_samples(samples_ptr, total_samples, samples);
1379 if (dq_result != ASCIICHAT_OK) {
1380 SAFE_FREE(samples);
1381 return;
1382 }
1383
1384#ifndef NDEBUG
1385 static int recv_count = 0;
1386 recv_count++;
1387 if (recv_count % 100 == 0) {
1388 uint32_t raw0 =
1389 bytes_read_u32_unaligned(samples_ptr + 0 * sizeof(uint32_t));
1390 uint32_t raw1 =
1391 bytes_read_u32_unaligned(samples_ptr + 1 * sizeof(uint32_t));
1392 uint32_t raw2 =
1393 bytes_read_u32_unaligned(samples_ptr + 2 * sizeof(uint32_t));
1394 int32_t scaled0 = (int32_t)NET_TO_HOST_U32(raw0);
1395 int32_t scaled1 = (int32_t)NET_TO_HOST_U32(raw1);
1396 int32_t scaled2 = (int32_t)NET_TO_HOST_U32(raw2);
1399 "RECV: network[0]=0x%08x, network[1]=0x%08x, network[2]=0x%08x", raw0,
1400 raw1, raw2);
1402 "RECV: scaled[0]=%d, scaled[1]=%d, scaled[2]=%d", scaled0,
1403 scaled1, scaled2);
1405 "RECV: samples[0]=%.6f, samples[1]=%.6f, samples[2]=%.6f",
1406 samples[0], samples[1], samples[2]);
1407 }
1408#endif
1409
1410 if (client->incoming_audio_buffer) {
1411 uint32_t frames = total_samples / batch_info.channels;
1412 (void)audio_convert_channels(samples, frames, batch_info.channels, samples,
1415 client->incoming_audio_buffer, samples, frames * AUDIO_CHANNELS);
1416 if (write_result != ASCIICHAT_OK) {
1417 log_error("Failed to write decoded audio batch to buffer: %s",
1418 asciichat_error_format(NULL, write_result));
1419 }
1420 }
1421
1422 SAFE_FREE(samples);
1423}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
asciichat_error_t audio_convert_channels(const float *input, size_t frames, unsigned input_channels, float *output, unsigned output_channels)
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:9
#define AUDIO_CHANNELS
#define NET_TO_HOST_U32(val)
Definition endian.h:85
asciichat_error_t audio_ring_buffer_write(audio_ring_buffer_t *rb, const float *data, int samples)
Write audio samples to ring buffer.
asciichat_error_t audio_parse_batch_header(const void *data, size_t len, audio_batch_info_t *out_batch)
Parse an audio batch packet header from raw packet data.
asciichat_error_t audio_dequantize_samples(const uint8_t *samples_ptr, uint32_t total_samples, float *out_samples)
Dequantize network audio samples from int32 to float.
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define safe_size_mul
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
#define LOG_RATE_DEFAULT
Log rate limit: 5 seconds (5,000,000 microseconds) - default for audio/video packets.
Definition log_rates.h:38
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define US_PER_SEC_INT
Definition time.h:177
#define AUDIO_BATCH_SAMPLES
Total samples in audio batch (8192 samples).
Definition packet.h:245
#define VALIDATE_AUDIO_STREAM_ENABLED(client, packet_name)
#define VALIDATE_NONZERO(client, value, value_name, packet_name)
#define VALIDATE_MIN_SIZE(client, len, min_size, packet_name)
#define VALIDATE_NOTNULL_DATA(client, data, packet_name)
void disconnect_client_for_bad_data(client_info_t *client, const char *format,...)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
Parsed audio batch packet header information.
uint32_t batch_count
Number of audio frames in this batch.
uint32_t channels
Number of channels (1=mono, 2=stereo).
uint32_t sample_rate
Sample rate in Hz (e.g., 48000).
uint32_t total_samples
Total number of samples across all frames.
The metadata prefix for a batch of encoded audio samples. batch_count, total_samples,...
Definition packet.h:983
audio_ring_buffer_t * incoming_audio_buffer

References asciichat_error_format(), ASCIICHAT_OK, atomic_load_bool(), AUDIO_BATCH_SAMPLES, AUDIO_CHANNELS, audio_convert_channels(), audio_dequantize_samples(), audio_parse_batch_header(), audio_ring_buffer_write(), AUDIO_SAMPLE_RATE, audio_batch_info_t::batch_count, audio_batch_info_t::channels, client_info::client_id, disconnect_client_for_bad_data(), ERROR_MEMORY, client_info::incoming_audio_buffer, client_info::is_sending_audio, log_debug_every, log_error, LOG_RATE_DEFAULT, NET_TO_HOST_U32, SAFE_FREE, SAFE_MALLOC, safe_size_mul, audio_batch_info_t::sample_rate, SET_ERRNO, audio_batch_info_t::total_samples, US_PER_SEC_INT, VALIDATE_AUDIO_STREAM_ENABLED, VALIDATE_MIN_SIZE, VALIDATE_NONZERO, and VALIDATE_NOTNULL_DATA.

◆ handle_audio_opus_batch_packet()

void handle_audio_opus_batch_packet ( client_info_t * client,
const void * data,
size_t len )

Process AUDIO_OPUS_BATCH packet - efficient Opus-encoded audio batch from client.

Handles batched Opus-encoded audio frames sent by the client. This provides ~98% bandwidth reduction compared to raw PCM audio while maintaining excellent audio quality.

PACKET STRUCTURE EXPECTED:

  • opus_batch_header_t (16 bytes):
    • sample_rate (4 bytes)
    • frame_duration (4 bytes)
    • frame_count (4 bytes)
    • reserved (4 bytes)
  • Opus encoded data (variable size, typically ~60 bytes/frame @ 24kbps)

PROCESSING FLOW:

  1. Parse batch header
  2. Decode each Opus frame back to PCM samples (OPUS_FRAME_SAMPLES samples/frame @ 48kHz)
  3. Write decoded samples to client's incoming audio buffer

PERFORMANCE:

  • Bandwidth: ~60 bytes/frame vs ~3840 bytes/frame for raw PCM (64:1 compression)
  • Quality: Excellent at 24 kbps VOIP mode
  • Latency: 20ms frames for real-time audio
Parameters
clientClient that sent the audio packet
dataPacket payload data
lenPacket payload length
See also
av_receive_audio_opus_batch() For packet parsing
opus_codec_decode() For Opus decoding
handle_audio_batch_packet() For raw PCM Audio batch handling

Definition at line 1463 of file server/protocol.c.

1464 {
1466 "Received Opus audio batch from client %s (len=%zu)",
1467 client->client_id, len);
1468
1469 VALIDATE_NOTNULL_DATA(client, data, "AUDIO_OPUS_BATCH");
1470 VALIDATE_AUDIO_STREAM_ENABLED(client, "AUDIO_OPUS_BATCH");
1471 VALIDATE_RESOURCE_INITIALIZED(client, client->opus_decoder, "Opus decoder");
1472
1473 // Parse Opus batch packet
1474 const uint8_t *opus_data = NULL;
1475 size_t opus_size = 0;
1476 const uint16_t *frame_sizes = NULL;
1477 int sample_rate = 0;
1478 int frame_duration = 0;
1479 int frame_count = 0;
1480
1481 asciichat_error_t result =
1482 packet_parse_opus_batch(data, len, &opus_data, &opus_size, &frame_sizes,
1483 &sample_rate, &frame_duration, &frame_count);
1484
1485 if (result != ASCIICHAT_OK) {
1487 "Failed to parse AUDIO_OPUS_BATCH packet");
1488 return;
1489 }
1490
1491 VALIDATE_NONZERO(client, frame_count, "frame_count", "AUDIO_OPUS_BATCH");
1492 VALIDATE_NONZERO(client, opus_size, "opus_size", "AUDIO_OPUS_BATCH");
1493
1494 // Calculate samples per frame (20ms @ 48kHz = OPUS_FRAME_SAMPLES samples)
1495 int samples_per_frame =
1496 (sample_rate * frame_duration) / 1000 * AUDIO_CHANNELS;
1497 VALIDATE_RANGE(client, samples_per_frame, 1,
1499 "samples_per_frame", "AUDIO_OPUS_BATCH");
1500
1501 // Use static buffer for common case to avoid malloc in hot path
1502 // Typical batches: 1-32 frames of OPUS_FRAME_SAMPLES samples = up to 30,720
1503 // samples Static buffer holds 32 frames @ 48kHz 20ms = 30,720 samples (120KB)
1504#define OPUS_DECODE_STATIC_MAX_SAMPLES \
1505 (32 * OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)
1506 // Each client receive thread decodes independently. Sharing this scratch
1507 // buffer lets concurrent clients overwrite one another's PCM before it is
1508 // written to their source rings.
1509 static _Thread_local float
1510 static_decode_buffer[OPUS_DECODE_STATIC_MAX_SAMPLES];
1511
1512 size_t total_samples = (size_t)samples_per_frame * (size_t)frame_count;
1513 float *decoded_samples;
1514 bool used_malloc = false;
1515
1516 if (total_samples <= OPUS_DECODE_STATIC_MAX_SAMPLES) {
1517 decoded_samples = static_decode_buffer;
1518 } else {
1519 // Unusual large batch - fall back to malloc
1520 log_warn("Client %s: Large audio batch requires malloc (%zu samples)",
1521 client->client_id, total_samples);
1522 decoded_samples = SAFE_MALLOC(total_samples * sizeof(float), float *);
1523 if (!decoded_samples) {
1525 "Failed to allocate buffer for Opus decoded samples");
1526 return;
1527 }
1528 used_malloc = true;
1529 }
1530
1531 // Decode each Opus frame using frame_sizes array
1532 int total_decoded = 0;
1533 size_t opus_offset = 0;
1534
1535 for (int i = 0; i < frame_count; i++) {
1536 // Get exact frame size from frame_sizes array (convert from network byte
1537 // order)
1538 size_t frame_size = (size_t)NET_TO_HOST_U16(frame_sizes[i]);
1539
1540 // DEBUG: Log the actual bytes of each Opus frame
1541 if (frame_size > 0) {
1543 "Client %s: Opus frame %d: size=%zu, "
1544 "first_bytes=[0x%02x,0x%02x,0x%02x,0x%02x]",
1545 client->client_id, i, frame_size,
1546 opus_data[opus_offset] & 0xFF,
1547 frame_size > 1 ? (opus_data[opus_offset + 1] & 0xFF) : 0,
1548 frame_size > 2 ? (opus_data[opus_offset + 2] & 0xFF) : 0,
1549 frame_size > 3 ? (opus_data[opus_offset + 3] & 0xFF) : 0);
1550 }
1551
1552 if (opus_offset + frame_size > opus_size) {
1553 log_error("Client %s: Frame %d size overflow (offset=%zu, "
1554 "frame_size=%zu, total=%zu)",
1555 client->client_id, i + 1, opus_offset, frame_size, opus_size);
1556 if (used_malloc) {
1557 SAFE_FREE(decoded_samples);
1558 }
1559 return;
1560 }
1561
1562 // SECURITY: Bounds check before writing decoded samples to prevent buffer
1563 // overflow An attacker could send malicious Opus frames that decode to more
1564 // samples than expected
1565 if ((size_t)total_decoded + (size_t)samples_per_frame > total_samples) {
1566 log_error("Client %s: Opus decode would overflow buffer (decoded=%d, "
1567 "frame_samples=%d, max=%zu)",
1568 client->client_id, total_decoded, samples_per_frame,
1569 total_samples);
1570 if (used_malloc) {
1571 SAFE_FREE(decoded_samples);
1572 }
1573 return;
1574 }
1575
1576 int decoded_count = opus_codec_decode(
1577 (opus_codec_t *)client->opus_decoder, &opus_data[opus_offset],
1578 frame_size, &decoded_samples[total_decoded], samples_per_frame);
1579
1580 if (decoded_count < 0) {
1581 log_error("Client %s: Opus decoding failed for frame %d/%d (size=%zu)",
1582 client->client_id, i + 1, frame_count, frame_size);
1583 if (used_malloc) {
1584 SAFE_FREE(decoded_samples);
1585 }
1586 return;
1587 }
1588
1589 total_decoded += decoded_count;
1590 opus_offset += frame_size;
1591 }
1592
1594 "Client %s: Decoded %d Opus frames -> %d samples",
1595 client->client_id, frame_count, total_decoded);
1596
1597 // DEBUG: Log sample values to detect all-zero issue
1598 static _Thread_local int server_decode_count = 0;
1599 server_decode_count++;
1600 if (total_decoded > 0 &&
1601 (server_decode_count <= 10 || server_decode_count % 100 == 0)) {
1602 float peak = 0.0f, rms = 0.0f;
1603 for (int i = 0; i < total_decoded && i < 100; i++) {
1604 float abs_val = fabsf(decoded_samples[i]);
1605 if (abs_val > peak)
1606 peak = abs_val;
1607 rms += decoded_samples[i] * decoded_samples[i];
1608 }
1609 rms = sqrtf(rms / (total_decoded > 100 ? 100 : total_decoded));
1610 // Log first 4 bytes of Opus data to compare with client encode
1613 "SERVER OPUS DECODE #%d from client %s: decoded_rms=%.6f, "
1614 "opus_first4=[0x%02x,0x%02x,0x%02x,0x%02x]",
1615 server_decode_count, client->client_id, rms,
1616 opus_size > 0 ? opus_data[0] : 0, opus_size > 1 ? opus_data[1] : 0,
1617 opus_size > 2 ? opus_data[2] : 0, opus_size > 3 ? opus_data[3] : 0);
1618 }
1619
1620 // Write decoded samples to client's incoming audio buffer
1621 // Note: audio_ring_buffer_write returns error code, not sample count
1622 // Buffer overflow warnings are logged inside audio_ring_buffer_write if
1623 // buffer is full
1624 if (client->incoming_audio_buffer && total_decoded > 0) {
1626 client->incoming_audio_buffer, decoded_samples, total_decoded);
1627 if (write_result != ASCIICHAT_OK) {
1628 log_error("Client %s: Failed to write decoded audio to buffer: %s",
1629 client->client_id, asciichat_error_format(NULL, write_result));
1630 }
1631 }
1632
1633 if (used_malloc) {
1634 SAFE_FREE(decoded_samples);
1635 }
1636}
#define AUDIO_OPUS_MAX_DECODE_SAMPLES
#define NET_TO_HOST_U16(val)
Definition endian.h:115
int opus_codec_decode(opus_codec_t *codec, const uint8_t *data, size_t data_len, float *out_samples, int out_num_samples)
Decode Opus audio frame.
Definition opus.c:198
unsigned short uint16_t
#define LOG_RATE_SLOW
Log rate limit: 10 seconds (10,000,000 microseconds).
Definition log_rates.h:41
asciichat_error_t packet_parse_opus_batch(const void *packet_data, size_t packet_len, const uint8_t **out_opus_data, size_t *out_opus_size, const uint16_t **out_frame_sizes, int *out_sample_rate, int *out_frame_duration, int *out_frame_count)
Parse Opus audio batch packet header and extract frame data.
#define VALIDATE_RESOURCE_INITIALIZED(client, resource, resource_name)
#define VALIDATE_RANGE(client, value, min_val, max_val, value_name, packet_name)
#define OPUS_DECODE_STATIC_MAX_SAMPLES
State for one Opus encoding or decoding direction.
Definition opus.h:113

References asciichat_error_format(), ASCIICHAT_OK, AUDIO_CHANNELS, AUDIO_OPUS_MAX_DECODE_SAMPLES, audio_ring_buffer_write(), client_info::client_id, disconnect_client_for_bad_data(), ERROR_MEMORY, client_info::incoming_audio_buffer, log_debug_every, log_error, LOG_RATE_DEFAULT, LOG_RATE_SLOW, log_warn, NET_TO_HOST_U16, opus_codec_decode(), OPUS_DECODE_STATIC_MAX_SAMPLES, client_info::opus_decoder, packet_parse_opus_batch(), SAFE_FREE, SAFE_MALLOC, SET_ERRNO, US_PER_SEC_INT, VALIDATE_AUDIO_STREAM_ENABLED, VALIDATE_NONZERO, VALIDATE_NOTNULL_DATA, VALIDATE_RANGE, and VALIDATE_RESOURCE_INITIALIZED.

◆ handle_audio_opus_packet()

void handle_audio_opus_packet ( client_info_t * client,
const void * data,
size_t len )

Process AUDIO_OPUS packet - decode single Opus frame from client.

Handles single Opus-encoded audio frames sent by clients. The packet format includes a 16-byte header followed by the Opus-encoded data.

PACKET STRUCTURE:

  • Offset 0: sample_rate (uint32_t, native byte order - bug in client)
  • Offset 4: frame_duration (uint32_t, native byte order - bug in client)
  • Offset 8: reserved (8 bytes)
  • Offset 16: Opus-encoded audio data
Parameters
clientClient info structure
dataPacket payload
lenPacket length

Definition at line 1656 of file server/protocol.c.

1657 {
1659 "Received Opus audio from client %s (len=%zu)",
1660 client->client_id, len);
1661
1662 if (VALIDATE_PACKET_NOT_NULL(client, data, "AUDIO_OPUS")) {
1663 return;
1664 }
1665
1666 // Minimum size: 16-byte header + at least 1 byte of Opus data
1667 if (len < 17) {
1669 client, "AUDIO_OPUS packet too small: %zu bytes", len);
1670 return;
1671 }
1672
1673 if (!atomic_load_bool(&client->is_sending_audio)) {
1675 client, "AUDIO_OPUS received before audio stream enabled");
1676 return;
1677 }
1678
1679 if (!client->opus_decoder) {
1680 disconnect_client_for_bad_data(client, "Opus decoder not initialized");
1681 return;
1682 }
1683
1684 // Parse header (16 bytes) - convert from network byte order
1685 const uint8_t *buf = (const uint8_t *)data;
1686 uint32_t sample_rate_net, frame_duration_net;
1687 memcpy(&sample_rate_net, buf, 4);
1688 memcpy(&frame_duration_net, buf + 4, 4);
1689 uint32_t sample_rate = NET_TO_HOST_U32(sample_rate_net);
1690 uint32_t frame_duration = NET_TO_HOST_U32(frame_duration_net);
1691
1692 // Extract Opus data (after 16-byte header)
1693 const uint8_t *opus_data = buf + 16;
1694 size_t opus_size = len - 16;
1695
1696 // Validate parameters
1697 if (sample_rate == 0 || sample_rate > 192000) {
1698 disconnect_client_for_bad_data(client, "AUDIO_OPUS invalid sample_rate: %u",
1699 sample_rate);
1700 return;
1701 }
1702
1703 if (frame_duration == 0 || frame_duration > 120) {
1705 client, "AUDIO_OPUS invalid frame_duration: %u ms", frame_duration);
1706 return;
1707 }
1708
1709 // Calculate expected samples per frame
1710 int samples_per_frame =
1711 (int)((sample_rate * frame_duration) / 1000) * AUDIO_CHANNELS;
1712 if (samples_per_frame <= 0 ||
1713 samples_per_frame >
1714 AUDIO_OPUS_MAX_DECODE_SAMPLES * AUDIO_CHANNELS) { // Max 120ms @ 48kHz
1716 client, "AUDIO_OPUS invalid samples_per_frame: %d", samples_per_frame);
1717 return;
1718 }
1719
1720 // Decode Opus frame
1721 float decoded_samples[AUDIO_OPUS_MAX_DECODE_SAMPLES *
1722 AUDIO_CHANNELS]; // Max Opus frame size (120ms @ 48kHz)
1723 int decoded_count =
1724 opus_codec_decode((opus_codec_t *)client->opus_decoder, opus_data,
1725 opus_size, decoded_samples, samples_per_frame);
1726
1727 if (decoded_count < 0) {
1728 log_error("Client %s: Opus decoding failed (size=%zu)", client->client_id,
1729 opus_size);
1730 return;
1731 }
1732
1734 "Client %s: Decoded Opus frame -> %d samples",
1735 client->client_id, decoded_count);
1736
1737 // Write decoded samples to client's incoming audio buffer
1738 if (client->incoming_audio_buffer && decoded_count > 0) {
1740 client->incoming_audio_buffer, decoded_samples, decoded_count);
1741 if (write_result != ASCIICHAT_OK) {
1742 log_error("Failed to write decoded Opus samples to buffer: %s",
1743 asciichat_error_format(NULL, write_result));
1744 }
1745 }
1746}
#define LOG_RATE_VERY_FAST
Log rate limit: 0.1 seconds (100,000 microseconds) - for very high frequency operations.
Definition log_rates.h:28
#define VALIDATE_PACKET_NOT_NULL(client, data, packet_name)

References asciichat_error_format(), ASCIICHAT_OK, atomic_load_bool(), AUDIO_CHANNELS, AUDIO_OPUS_MAX_DECODE_SAMPLES, audio_ring_buffer_write(), client_info::client_id, disconnect_client_for_bad_data(), client_info::incoming_audio_buffer, client_info::is_sending_audio, log_debug_every, log_error, LOG_RATE_DEFAULT, LOG_RATE_VERY_FAST, NET_TO_HOST_U32, opus_codec_decode(), client_info::opus_decoder, and VALIDATE_PACKET_NOT_NULL.

◆ handle_audio_packet()

void handle_audio_packet ( client_info_t * client,
const void * data,
size_t len )

Process AUDIO packet - store single audio sample batch (legacy format).

Handles the original audio packet format that sends one batch of float samples per packet. This format is less efficient than AUDIO_BATCH but still supported for backward compatibility.

PACKET STRUCTURE:

  • float samples[len/sizeof(float)] (IEEE 754 format)
  • Sample rate assumed to be 44100 Hz
  • Mono audio (single channel)

PERFORMANCE CHARACTERISTICS:

BUFFER MANAGEMENT:

  • Stores samples in client->incoming_audio_buffer (lock-free ring buffer)
  • Buffer overflow drops oldest samples to maintain real-time behavior
  • mixer.c consumes samples for multi-client audio mixing

STATE VALIDATION:

  • Only processes if client->is_sending_audio is true
  • Requires valid buffer pointer and non-zero length
  • Handles buffer pointer safely during shutdown

ERROR HANDLING:

  • Invalid packets are silently ignored
  • Buffer overflow is handled by ring buffer (drops old data)
  • Graceful shutdown behavior
Parameters
clientSource client providing audio data
dataPacket payload containing float audio samples
lenSize of packet payload in bytes
Note
Prefer AUDIO_BATCH format for better efficiency
Audio processing happens in mixer threads, not here
See also
handle_audio_batch_packet() For efficient batched format
audio_ring_buffer_write() For storage implementation

Definition at line 1185 of file server/protocol.c.

1185 {
1186 VALIDATE_NOTNULL_DATA(client, data, "AUDIO");
1187 VALIDATE_AUDIO_ALIGNMENT(client, len, sizeof(float), "AUDIO");
1188 VALIDATE_AUDIO_STREAM_ENABLED(client, "AUDIO");
1189
1190 int num_samples = (int)(len / sizeof(float));
1192 "AUDIO");
1194 "audio buffer");
1195
1196 const float *samples = (const float *)data;
1198 float *stereo = SAFE_MALLOC(
1199 (size_t)num_samples * AUDIO_CHANNELS * sizeof(float), float *);
1200 if (audio_convert_channels(samples, (size_t)num_samples, 1, stereo,
1202 result = audio_ring_buffer_write(client->incoming_audio_buffer, stereo,
1203 num_samples * AUDIO_CHANNELS);
1204 SAFE_FREE(stereo);
1205 if (result != ASCIICHAT_OK) {
1206 log_error("Failed to write audio samples to buffer: %s",
1207 asciichat_error_format(NULL, result));
1208 }
1209}
#define AUDIO_SAMPLES_PER_PACKET
Samples per audio packet (256 samples).
Definition packet.h:264
#define VALIDATE_AUDIO_SAMPLE_COUNT(client, num_samples, max_samples, packet_name)
#define VALIDATE_AUDIO_ALIGNMENT(client, len, sample_size, packet_name)

References asciichat_error_format(), ASCIICHAT_OK, AUDIO_CHANNELS, audio_convert_channels(), audio_ring_buffer_write(), AUDIO_SAMPLES_PER_PACKET, client_info::incoming_audio_buffer, log_error, SAFE_FREE, SAFE_MALLOC, VALIDATE_AUDIO_ALIGNMENT, VALIDATE_AUDIO_SAMPLE_COUNT, VALIDATE_AUDIO_STREAM_ENABLED, VALIDATE_NOTNULL_DATA, and VALIDATE_RESOURCE_INITIALIZED.

◆ handle_client_capabilities_packet()

void handle_client_capabilities_packet ( client_info_t * client,
const void * data,
size_t len )

Bootstrap a viewer's rendering state from its initial terminal capabilities. Later advertisements update codecs while SETTINGS_SYNC owns live preferences. Publish under the client mutex, then send the initial effective settings unlocked.

Definition at line 1782 of file server/protocol.c.

1783 {
1784 if (!data || len != sizeof(terminal_capabilities_packet_t)) {
1785 disconnect_client_for_bad_data(client, "Invalid capabilities size");
1786 return;
1787 }
1789 memcpy(&packet, data, sizeof(packet));
1790 mutex_lock(&client->client_state_mutex);
1791 client->codec_capabilities_video =
1793 client->codec_capabilities_audio =
1795 // Encoder changes advertise codec support without overwriting live
1796 // preferences.
1797 if (client->has_terminal_caps) {
1798 mutex_unlock(&client->client_state_mutex);
1799 return;
1800 }
1801 client->render_settings.fps_limit =
1802 (uint16_t)(GET_OPTION(fps) > 0 ? GET_OPTION(fps) : DEFAULT_MAX_FPS);
1803 asciichat_error_t result =
1805 if (result == ASCIICHAT_OK) {
1806 publish_render_settings(client);
1807 log_info(
1808 "Client %s rendering configured: %ux%u, color=%u, palette=%u, mode=%u, "
1809 "fps=%u",
1810 client->client_id, client->width, client->height,
1811 client->terminal_caps.color_level, client->terminal_caps.palette_type,
1812 client->terminal_caps.render_mode, client->terminal_caps.desired_fps);
1813 }
1814 mutex_unlock(&client->client_state_mutex);
1815 if (result != ASCIICHAT_OK)
1816 disconnect_client_for_bad_data(client, "Invalid render capabilities");
1817 else {
1819 size_t query_length;
1820 acip_settings_header_t header = {.schema = 1,
1821 .expected_revision = UINT32_MAX};
1822 if (acip_settings_encode(&header, "", query, sizeof(query),
1823 &query_length) == ASCIICHAT_OK)
1824 (void)handle_runtime_settings(client, query, query_length);
1825 }
1826}
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second).
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define GET_OPTION(field)
Definition options.h:1339
asciichat_error_t acip_render_settings_capabilities(acip_render_settings_t *state, const terminal_capabilities_packet_t *packet)
asciichat_error_t acip_settings_encode(const acip_settings_header_t *header, const char *json, uint8_t *buffer, size_t capacity, size_t *length)
asciichat_error_t handle_runtime_settings(client_info_t *client, const void *data, size_t length)
acip settings header keeps the values that move through the subsystem: schema, request,...
terminal_capabilities_t terminal_caps
acip_render_settings_t render_settings
Terminal capabilities packet structure (Packet Type 5).
Definition packet.h:1097
uint32_t codec_capabilities_video
Video codec capabilities bitmask (VIDEO_CODEC_CAP_*).
Definition packet.h:1129
uint32_t codec_capabilities_audio
Audio codec capabilities bitmask (AUDIO_CODEC_CAP_*).
Definition packet.h:1131

References acip_render_settings_capabilities(), acip_settings_encode(), ACIP_SETTINGS_HEADER_SIZE, ASCIICHAT_OK, client_info::client_id, client_info::client_state_mutex, client_info::codec_capabilities_audio, terminal_capabilities_packet_t::codec_capabilities_audio, client_info::codec_capabilities_video, terminal_capabilities_packet_t::codec_capabilities_video, DEFAULT_MAX_FPS, disconnect_client_for_bad_data(), acip_render_settings_t::fps_limit, GET_OPTION, handle_runtime_settings(), client_info::has_terminal_caps, client_info::height, log_info, NET_TO_HOST_U32, client_info::render_settings, client_info::terminal_caps, and client_info::width.

◆ handle_client_join_packet()

void handle_client_join_packet ( client_info_t * client,
const void * data,
size_t len )

Process CLIENT_JOIN packet - client announces identity and capabilities.

This is the first substantive packet clients send after establishing a TCP connection. It provides the server with essential information for managing the client throughout its session.

PACKET STRUCTURE EXPECTED:

  • client_info_packet_t containing:
    • display_name: Human-readable client identifier
    • capabilities: Bitmask of CLIENT_CAP_* flags

STATE CHANGES PERFORMED:

  • Updates client->display_name from packet
  • Sets client->can_send_video based on CLIENT_CAP_VIDEO
  • Sets client->can_send_audio based on CLIENT_CAP_AUDIO
  • Sets client->wants_stretch based on CLIENT_CAP_STRETCH

PROTOCOL BEHAVIOR:

  • Does NOT automatically start media streams (requires STREAM_START)
  • Does NOT send CLEAR_CONSOLE to other clients (prevents flicker)
  • Logs client capabilities for debugging

ERROR HANDLING:

  • Silently ignores packets with wrong size
  • Invalid display names are truncated safely
  • Missing capabilities default to false
Parameters
clientTarget client whose state will be updated
dataPacket payload (should be client_info_packet_t)
lenSize of packet payload in bytes
Note
This function should only be called by client receive threads
Client state is already protected by receive thread serialization
See also
handle_stream_start_packet() For enabling Media transmission

Definition at line 255 of file server/protocol.c.

256 {
257 VALIDATE_PACKET_SIZE(client, data, len, sizeof(client_info_packet_t),
258 "CLIENT_JOIN");
259
260 const client_info_packet_t *join_info = (const client_info_packet_t *)data;
261
262 // Validate display name is present and not just whitespace
263 if (join_info->display_name[0] == '\0') {
265 "CLIENT_JOIN display_name cannot be empty");
266 return;
267 }
268
269 uint32_t capabilities = NET_TO_HOST_U32(join_info->capabilities);
270
271 // Validate at least one capability flag is set
272 const uint32_t VALID_CAP_MASK = CLIENT_CAP_VIDEO | CLIENT_CAP_AUDIO |
274 VALIDATE_CAPABILITY_FLAGS(client, capabilities, VALID_CAP_MASK,
275 "CLIENT_JOIN");
276
277 // Validate no unknown capability bits are set
278 VALIDATE_FLAGS_MASK(client, capabilities, VALID_CAP_MASK, "CLIENT_JOIN");
279
280 SAFE_STRNCPY(client->display_name, join_info->display_name,
282
283 client->can_send_video = (capabilities & CLIENT_CAP_VIDEO) != 0;
284 client->can_send_audio = (capabilities & CLIENT_CAP_AUDIO) != 0;
285 client->wants_stretch = (capabilities & CLIENT_CAP_STRETCH) != 0;
286
287 log_info("Client %s joined: %s (video=%d, audio=%d, stretch=%d)",
288 client->client_id, client->display_name, client->can_send_video,
289 client->can_send_audio, client->wants_stretch);
290
291 // Notify client of successful join (encrypted channel)
292 if (client->transport != NULL) {
293 log_info_client(client, "Joined as '%s' (video=%s, audio=%s)",
294 client->display_name, client->can_send_video ? "yes" : "no",
295 client->can_send_audio ? "yes" : "no");
296 }
297}
#define MAX_DISPLAY_NAME_LEN
Maximum display name length in characters.
#define log_info_client(client, fmt,...)
Server sends INFO log message to client.
Definition network/log.h:74
#define CLIENT_CAP_STRETCH
Client can stretch frames to fill terminal.
Definition packet.h:1005
#define CLIENT_CAP_COLOR
Client supports color rendering.
Definition packet.h:1004
#define CLIENT_CAP_AUDIO
Client can send/receive audio.
Definition packet.h:1003
#define CLIENT_CAP_VIDEO
Client can send/receive video.
Definition packet.h:1002
#define VALIDATE_PACKET_SIZE(client, data, len, expected_size, packet_name)
#define VALIDATE_FLAGS_MASK(client, flags, valid_mask, packet_name)
#define VALIDATE_CAPABILITY_FLAGS(client, flags, valid_mask, packet_name)
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 capabilities
Client capabilities bitmask (CLIENT_CAP_VIDEO | CLIENT_CAP_AUDIO | CLIENT_CAP_COLOR | CLIENT_CAP_STRE...
Definition packet.h:710
char display_name[MAX_DISPLAY_NAME_LEN]

References client_info::can_send_audio, client_info::can_send_video, client_info_packet_t::capabilities, CLIENT_CAP_AUDIO, CLIENT_CAP_COLOR, CLIENT_CAP_STRETCH, CLIENT_CAP_VIDEO, client_info::client_id, disconnect_client_for_bad_data(), client_info::display_name, client_info_packet_t::display_name, log_info, log_info_client, MAX_DISPLAY_NAME_LEN, NET_TO_HOST_U32, SAFE_STRNCPY, client_info::transport, VALIDATE_CAPABILITY_FLAGS, VALIDATE_FLAGS_MASK, VALIDATE_PACKET_SIZE, and client_info::wants_stretch.

◆ handle_client_leave_packet()

void handle_client_leave_packet ( client_info_t * client,
const void * data,
size_t len )

Process CLIENT_LEAVE packet - handle clean client disconnect.

Clients may send this packet before disconnecting to allow the server to log the disconnect reason and perform clean state management. This is optional but preferred over abrupt disconnects.

PACKET STRUCTURE EXPECTED:

  • Optional string containing disconnect reason (0-256 bytes)

PROTOCOL BEHAVIOR:

  • Client logs the disconnect reason if provided
  • Server deactivates the client and requests transport shutdown
  • The normal connection-closed callback performs final removal

ERROR HANDLING:

  • Empty payload is handled gracefully
  • Oversized payloads are rejected
  • Invalid UTF-8 in reason is handled gracefully (logged as-is)
Parameters
clientClient that sent the leave packet
dataPacket payload (optional reason string)
lenSize of packet payload in bytes (0-256)
Note
The transport shutdown request is asynchronous; final removal occurs from the connection-closed callback.

Definition at line 424 of file server/protocol.c.

425 {
426 if (!client) {
427 return;
428 }
429
430 const char *client_id = client->client_id;
431
432 if (len == 0) {
433 // Empty reason - client disconnecting without explanation
434 log_info("Client %s sent leave notification (no reason)", client_id);
435 } else if (len <= 256) {
436 // Reason provided - extract and log it
437 if (!data) {
439 "Client %s sent leave notification with non-zero length but "
440 "NULL data",
441 client_id);
442 return;
443 }
444
445 char reason[SERVER_PROTOCOL_REASON_BUFFER_SIZE] = {0};
446 memcpy(reason, data, len);
447 reason[len] = '\0';
448
449 // Validate reason is printable (handle potential non-UTF8 gracefully)
450 bool all_printable = true;
451 for (size_t i = 0; i < len; i++) {
452 uint8_t c = (uint8_t)reason[i];
453 if (c < 32 && c != '\t' && c != '\n') {
454 all_printable = false;
455 break;
456 }
457 }
458
459 if (all_printable) {
460 log_info("Client %s sent leave notification: %s", client_id, reason);
461 } else {
462 log_info("Client %s sent leave notification (reason contains "
463 "non-printable characters)",
464 client_id);
465 }
466 } else {
467 // Oversized reason - shouldn't happen with validation.h checks
468 log_warn("Client %s sent oversized leave reason (%zu bytes, max 256)",
469 client_id, len);
470 }
471
472 // Deactivate client to stop processing packets
473 // Sets client->active = false immediately - triggers client cleanup
474 // procedures
475 log_debug("Setting active=false (client_id=%s)", client_id);
476 atomic_store_bool(&client->active, false);
477
478 // Request transport shutdown immediately. This keeps the server's client
479 // accounting from depending on the peer closing its socket after sending
480 // CLIENT_LEAVE. Final resource removal remains serialized in the normal
481 // connection-closed callback.
482 if (client->network_connection) {
484 }
485}
#define SERVER_PROTOCOL_REASON_BUFFER_SIZE

References client_info::active, atomic_store_bool(), client_info::client_id, ERROR_INVALID_STATE, log_debug, log_info, log_warn, client_info::network_connection, network_connection_request_stop(), SERVER_PROTOCOL_REASON_BUFFER_SIZE, and SET_ERRNO.

◆ handle_image_frame_h264_packet()

void handle_image_frame_h264_packet ( client_info_t * client,
const void * data,
size_t len )

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

1443 {
1444 asciichat_error_t result =
1446 data, len, client, &g_acip_server_callbacks);
1447 if (result != ASCIICHAT_OK)
1448 disconnect_client_for_bad_data(client, "Invalid H.264 packet");
1449}
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
asciichat_error_t acip_handle_server_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks)
Handle incoming packet on server side.
Definition handlers.c:730

References acip_handle_server_packet(), ASCIICHAT_OK, disconnect_client_for_bad_data(), PACKET_TYPE_IMAGE_FRAME_H264, and client_info::transport.

◆ handle_image_frame_h265_packet()

void handle_image_frame_h265_packet ( client_info_t * client,
const void * data,
size_t len )

Process H.265-encoded image frame from client.

Handles incoming H.265/HEVC-encoded video frames from clients. Frames are decoded to ASCII art and added to the compositing pipeline.

FLOW:

  1. Validate packet structure and minimum size
  2. Auto-enable video stream on first frame
  3. Decode H.265 packet to ASCII grid
  4. Convert ASCII to frame buffer format for rendering
  5. Store in client's incoming_video_buffer
Parameters
clientClient connection info
dataH.265 packet payload (includes header with frame dimensions)
lenPayload size in bytes

PACKET FORMAT: [flags: u8][width: u16][height: u16][x265_data...]

  • flags: H265_FLAG_KEYFRAME, H265_FLAG_SIZE_CHANGE
  • width/height: Frame dimensions in characters
  • x265_data: H.265-encoded frame data

Definition at line 1004 of file server/protocol.c.

1005 {
1006 // Validate codec capability for H.265 frames
1009 log_error("Client %s sent H.265 frame but does not support "
1010 "VIDEO_CODEC_H265 (capabilities=0x%x)",
1011 client->client_id, client->codec_capabilities_video);
1013 client, "VIDEO_CODEC_H265 not supported by client (capabilities=0x%x)",
1014 client->codec_capabilities_video);
1015 return;
1016 }
1017
1018 if (!data || len < 5) {
1020 client, "H265_FRAME payload too small: %zu bytes (min 5)", len);
1021 return;
1022 }
1023
1024 // Auto-enable video stream if not already enabled
1025 // Use atomic_exchange to atomically set flag and check old value
1026 bool was_sending_video =
1027 atomic_exchange_bool(&client->is_sending_video, true);
1028 if (!was_sending_video) {
1029 log_info(
1030 "Client %s auto-enabled H.265 video stream (received IMAGE_FRAME_H265)",
1031 client->client_id);
1032 if (client->transport != NULL) {
1033 log_info_client(client,
1034 "First H.265 video frame received - streaming active");
1035 }
1036 }
1037
1038 uint8_t flags = *(const uint8_t *)data;
1039 bool is_keyframe = (flags & 0x01) != 0;
1040 bool size_changed = (flags & 0x02) != 0;
1041
1044 "H265_FRAME: flags=0x%02x, keyframe=%s, size_change=%s, len=%zu", flags,
1045 is_keyframe ? "yes" : "no", size_changed ? "yes" : "no", len);
1046
1047 if (!client->incoming_video_buffer) {
1048 log_error("Client %s has no incoming video buffer for H.265 frames",
1049 client->client_id);
1050 return;
1051 }
1052
1053 // Get H.265 server context (may be NULL during shutdown)
1055 if (!h265_ctx) {
1057 log_error("H.265 codec server context not initialized");
1058 }
1059 return;
1060 }
1061
1062 // Get or create decoder for this client
1063 uint32_t client_id_num = 0;
1064 char *end = NULL;
1065 unsigned long parsed = strtoul(client->client_id, &end, 10);
1066 if (end != client->client_id && *end == '\0') {
1067 client_id_num = (uint32_t)parsed;
1068 } else {
1069 // Fallback to string hash if can't parse as number
1070 client_id_num = 0;
1071 for (int i = 0; client->client_id[i]; i++) {
1072 client_id_num = (uint32_t)((uint64_t)client_id_num * 31 +
1073 (unsigned char)client->client_id[i]);
1074 }
1075 }
1076
1077 h265_server_client_t *client_decoder =
1078 h265_server_get_client_decoder(h265_ctx, client_id_num);
1079 if (!client_decoder) {
1080 log_error("Failed to get H.265 decoder for client %s", client->client_id);
1082 "Failed to initialize H.265 decoder");
1083 return;
1084 }
1085
1086 // Allocate temporary RGBA buffer for decoding
1087 // H.265 frames from client are sent as
1088 // [flags:u8][width:u16][height:u16][h265_data...] Existing scratch budget for
1089 // a 512-by-512 RGBA image.
1091 if (!rgba_buf) {
1092 log_error("Failed to allocate RGBA buffer for H.265 decoding");
1094 "Out of memory for H.265 frame decoding");
1095 return;
1096 }
1097
1098 uint16_t frame_width = 0;
1099 uint16_t frame_height = 0;
1100 size_t rgba_size = SERVER_H265_RGBA_BUFFER_SIZE;
1101
1102 // Decode H.265 packet to RGBA
1104 client_decoder, (const uint8_t *)data, len, rgba_buf, &frame_width,
1105 &frame_height, &rgba_size);
1106
1107 if (decode_result != ASCIICHAT_OK) {
1108 log_error("H.265 decoding failed for client %s: %s", client->client_id,
1109 asciichat_error_format(NULL, decode_result));
1110 SAFE_FREE(rgba_buf);
1111 disconnect_client_for_bad_data(client, "H.265 frame decode error");
1112 return;
1113 }
1114
1115 // Write decoded frame to video buffer
1117 if (frame && frame->data) {
1118 memcpy(frame->data, rgba_buf, rgba_size);
1119 frame->size = rgba_size;
1120 frame->width = frame_width;
1121 frame->height = frame_height;
1122 frame->is_keyframe = is_keyframe;
1123
1124 // Update frame metadata
1125 frame->receive_timestamp_ns = time_get_realtime_ns();
1126 frame->sequence_number = client->frames_received++;
1127
1130 "RECV_H265 #%llu: client_id=%s size=%zu dims=%ux%u keyframe=%s",
1131 (unsigned long long)frame->sequence_number, client->client_id,
1132 rgba_size, frame_width, frame_height, is_keyframe ? "yes" : "no");
1133
1135 } else {
1136 log_warn(
1137 "Failed to get write buffer for client %s (frame=%p, frame->data=%p)",
1138 client->client_id, (void *)frame, frame ? frame->data : NULL);
1139 }
1140
1141 SAFE_FREE(rgba_buf);
1142}
@ VIDEO_CODEC_H265
H.265 (HEVC) video codec.
Definition codecs.h:30
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:32
unsigned long long uint64_t
#define VIDEO_CODEC_SUPPORTED(cap, codec)
Check if a video codec is supported in capabilities bitmask.
Definition codecs.h:99
video_frame_t * video_frame_begin_write(video_frame_buffer_t *vfb)
Writer API: Start writing a new frame.
void video_frame_commit(video_frame_buffer_t *vfb)
Writer API: Commit the frame and swap buffers.
h265_server_context_t *volatile g_h265_server
Global H.265 codec server context.
#define SERVER_H265_RGBA_BUFFER_SIZE
struct h265_server_context h265_server_context_t
The useful part of h265 client decoder is in client_id, decoder, last_width, last_height: together th...
asciichat_error_t h265_server_decode_and_convert(h265_server_client_t *client, const uint8_t *h265_packet, size_t packet_size, uint8_t *output_rgba, uint16_t *output_width, uint16_t *output_height, size_t *output_size)
h265_server_client_t * h265_server_get_client_decoder(h265_server_context_t *ctx, uint32_t client_id)
struct h265_server_client h265_server_client_t
video_frame_buffer_t * incoming_video_buffer
When code needs to work with simple frame swap, it keeps current_frame, frame_a, frame_b,...
uint64_t sequence_number
Frame sequence number (for drop detection).
uint32_t height
Frame height in pixels.
bool is_keyframe
True if this is a keyframe (important frame).
size_t size
Size of frame data in bytes.
uint64_t receive_timestamp_ns
Timestamp when frame was received (nanoseconds).
uint32_t width
Frame width in pixels.
void * data
Frame data pointer (points to pre-allocated buffer).

References asciichat_error_format(), ASCIICHAT_OK, atomic_exchange_bool(), atomic_load_bool(), client_info::client_id, client_info::codec_capabilities_video, video_frame_t::data, disconnect_client_for_bad_data(), client_info::frames_received, g_h265_server, g_should_exit, h265_server_decode_and_convert(), h265_server_get_client_decoder(), video_frame_t::height, client_info::incoming_video_buffer, video_frame_t::is_keyframe, client_info::is_sending_video, log_debug_every, log_error, log_info, log_info_client, log_warn, video_frame_t::receive_timestamp_ns, SAFE_FREE, SAFE_MALLOC, video_frame_t::sequence_number, SERVER_H265_RGBA_BUFFER_SIZE, video_frame_t::size, client_info::transport, US_PER_SEC_INT, VIDEO_CODEC_H265, VIDEO_CODEC_SUPPORTED, video_frame_begin_write(), video_frame_commit(), and video_frame_t::width.

◆ handle_image_frame_packet()

void handle_image_frame_packet ( client_info_t * client,
void * data,
size_t len )

Process IMAGE_FRAME packet - store client's video data for rendering.

This is the most performance-critical packet handler, processing real-time video data from clients. It validates, stores, and tracks video frames for subsequent ASCII conversion and grid layout.

PACKET STRUCTURE EXPECTED:

PERFORMANCE CHARACTERISTICS:

  • Called at 30fps per active client
  • Uses zero-copy storage when possible
  • Validates packet size before processing
  • Implements frame counting for debug logging

STATE CHANGES PERFORMED:

  • Auto-enables client->is_sending_video if not already set
  • Increments client->frames_received counter
  • Updates client dimensions if changed

BUFFER MANAGEMENT:

  • Stores entire packet (including dimensions) in client->incoming_video_buffer
  • Uses multi-frame ringbuffer for burst handling
  • Buffer overflow drops oldest frames (maintains real-time performance)
  • render.c threads consume frames for ASCII conversion

VALIDATION PERFORMED:

  • Packet size matches width * height * 3 + 8 bytes
  • Width and height are reasonable (prevents memory exhaustion)
  • Buffer pointers are valid before access

ERROR HANDLING:

  • Invalid packets are logged and dropped
  • Buffer overflow is handled gracefully
  • Shutdown conditions don't generate error spam

PERFORMANCE OPTIMIZATIONS:

  • Debug logging is throttled (every 25000 frames)
  • Fast path for common case (valid packet with buffer space)
  • Minimal CPU work in receive thread (storage only)
Parameters
clientSource client providing video data
dataPacket payload containing image dimensions and RGB data
lenTotal size of packet payload in bytes
Note
This function is called by client receive threads at high frequency
Actual ASCII conversion happens in render threads (render.c)
Frame timestamps are added for synchronization purposes
See also
framebuffer_write_multi_frame() For Owned Buffers storage implementation
create_mixed_ascii_frame_for_client() For frame consumption

Definition at line 761 of file server/protocol.c.

761 {
762 // Handle incoming image data from client
763 // New format:
764 // [width:4][height:4][compressed_flag:4][data_size:4][rgb_data:data_size] Old
765 // format: [width:4][height:4][rgb_data:w*h*3] (for backward compatibility)
766 // Use atomic compare-and-swap to avoid race condition - ensures thread-safe
767 // auto-enabling of video stream
768
769 log_debug_every(US_PER_SEC_INT, "RECV_IMAGE_FRAME: client_id=%s, len=%zu",
770 client->client_id, len);
771
772 // Validate codec capability for RGBA frames
775 log_error("Client %s sent RGBA frame but does not support VIDEO_CODEC_RGBA "
776 "(capabilities=0x%x)",
777 client->client_id, client->codec_capabilities_video);
779 client, "VIDEO_CODEC_RGBA not supported by client (capabilities=0x%x)",
781 return;
782 }
783
784 if (!data || len < sizeof(uint32_t) * 2) {
786 client, "IMAGE_FRAME payload too small: %zu bytes", len);
787 return;
788 }
789 bool was_sending_video = atomic_load_bool(&client->is_sending_video);
790 if (!was_sending_video) {
791 // Try to atomically enable video sending
792 // Use atomic_compare_exchange_strong to avoid spurious failures
793 if (atomic_cas_bool(&client->is_sending_video, &was_sending_video, true)) {
794 log_info("Client %s auto-enabled video stream (received IMAGE_FRAME)",
795 client->client_id);
796 // Notify client that their first video frame was received
797 if (client->transport != NULL) {
798 log_info_client(client,
799 "First video frame received - streaming active");
800 }
801 }
802 } else {
803 // Log periodically to confirm we're receiving frames
804 // Use per-client counter protected by client_state_mutex to avoid race
805 // conditions
806 mutex_lock(&client->client_state_mutex);
807 client->frames_received_logged++;
808 if (client->frames_received_logged % 25000 == 0) {
810 format_bytes_pretty(len, pretty, sizeof(pretty));
811 log_debug("Client %s has sent %u IMAGE_FRAME packets (%s)",
812 client->client_id, client->frames_received_logged, pretty);
813 }
814 mutex_unlock(&client->client_state_mutex);
815 }
816
817 // Parse image dimensions (use memcpy to avoid unaligned access)
818 uint32_t img_width_net, img_height_net;
819 memcpy(&img_width_net, data, sizeof(uint32_t));
820 memcpy(&img_height_net, (char *)data + sizeof(uint32_t), sizeof(uint32_t));
821 uint32_t img_width = NET_TO_HOST_U32(img_width_net);
822 uint32_t img_height = NET_TO_HOST_U32(img_height_net);
823
825 "IMAGE_FRAME packet: width=%u, height=%u, payload_len=%zu",
826 img_width, img_height, len);
827
828 // Validate dimensions using image utility functions
829 if (image_validate_dimensions((size_t)img_width, (size_t)img_height) !=
830 ASCIICHAT_OK) {
831 log_error("IMAGE_FRAME validation failed for dimensions: %u x %u",
832 img_width, img_height);
833 disconnect_client_for_bad_data(client, "IMAGE_FRAME invalid dimensions");
834 return;
835 }
836
837 // Calculate RGB buffer size with overflow checking
838 size_t rgb_size = 0;
839 if (image_calc_rgb_size((size_t)img_width, (size_t)img_height, &rgb_size) !=
840 ASCIICHAT_OK) {
842 client, "IMAGE_FRAME buffer size calculation failed");
843 return;
844 }
845
846 // Validate final buffer size against maximum
847 if (image_validate_buffer_size(rgb_size) != ASCIICHAT_OK) {
849 "IMAGE_FRAME buffer size exceeds maximum");
850 return;
851 }
852
853 // Only support legacy format: [width:4][height:4][rgb_data:w*h*3]
854 if (rgb_size > SIZE_MAX - FRAME_HEADER_SIZE_LEGACY) {
856 format_bytes_pretty(rgb_size, size_str, sizeof(size_str));
858 client, "IMAGE_FRAME legacy packet size overflow: %s", size_str);
859 return;
860 }
861 size_t expected_size = FRAME_HEADER_SIZE_LEGACY + rgb_size;
862
863 if (len != expected_size) {
865 client, "IMAGE_FRAME size mismatch: expected %zu bytes got %zu",
866 expected_size, len);
867 return;
868 }
869
870 // Validate legacy format
871 asciichat_error_t validate_result = frame_validate_legacy(len, rgb_size);
872 if (validate_result != ASCIICHAT_OK) {
874 "IMAGE_FRAME legacy validation failed");
875 return;
876 }
877
878 void *rgb_data = (char *)data + FRAME_HEADER_SIZE_LEGACY;
879 size_t rgb_data_size = rgb_size;
880 bool needs_free = false;
881
882 if (client->incoming_video_buffer) {
883 // Get the write buffer
884 video_frame_t *frame =
886
887 if (frame && frame->data) {
888 // Build the packet in the old format for internal storage:
889 // [width:4][height:4][rgb_data:w*h*3] Use frame_check_size_overflow to
890 // validate overflow before repacking
891 asciichat_error_t overflow_check =
893 if (overflow_check != ASCIICHAT_OK) {
894 if (needs_free && rgb_data) {
895 SAFE_FREE(rgb_data);
896 }
898 client, "IMAGE_FRAME size overflow while repacking");
899 return;
900 }
901 size_t old_packet_size = FRAME_HEADER_SIZE_LEGACY + rgb_data_size;
902
903 if (old_packet_size <= MAX_FRAME_BUFFER_SIZE) { // Max frame buffer size
904 uint32_t width_net = HOST_TO_NET_U32(img_width);
905 uint32_t height_net = HOST_TO_NET_U32(img_height);
906
907 // Pack in old format for internal consistency
908 memcpy(frame->data, &width_net, sizeof(uint32_t));
909 memcpy((char *)frame->data + sizeof(uint32_t), &height_net,
910 sizeof(uint32_t));
911 memcpy((char *)frame->data + sizeof(uint32_t) * 2, rgb_data,
912 rgb_data_size);
913
914 frame->size = old_packet_size;
915 frame->width = img_width;
916 frame->height = img_height;
917 frame->capture_timestamp_ns = (uint64_t)time(NULL) * NS_PER_SEC_INT;
918 frame->sequence_number = ++client->frames_received;
919
920 // DEBUG: Compute hash of incoming RGB data to detect duplicates
921 uint32_t incoming_rgb_hash = 0;
922 for (size_t i = 0; i < rgb_data_size && i < 1000; i++) {
923 incoming_rgb_hash = (uint32_t)((uint64_t)incoming_rgb_hash * 31 +
924 ((unsigned char *)rgb_data)[i]);
925 }
926
927 // Per-client hash tracking (not static!) to avoid cross-client
928 // interference
929 const char *client_id = client->client_id;
930 bool is_new_frame =
931 (incoming_rgb_hash != client->last_received_frame_hash);
932
933 if (is_new_frame) {
935 "RECV_FRAME #%llu NEW: Client %s size=%zu dims=%ux%u "
936 "hash=0x%08x (prev=0x%08x)",
937 (unsigned long long)client->frames_received,
938 client_id, rgb_data_size, img_width, img_height,
939 incoming_rgb_hash, client->last_received_frame_hash);
940 client->last_received_frame_hash = incoming_rgb_hash;
941 } else {
944 "RECV_FRAME #%llu DUP: Client %s size=%zu dims=%ux%u hash=0x%08x",
945 (unsigned long long)client->frames_received, client_id,
946 rgb_data_size, img_width, img_height, incoming_rgb_hash);
947 }
948
950 } else {
951 if (needs_free && rgb_data) {
952 SAFE_FREE(rgb_data);
953 }
955 client, "IMAGE_FRAME repacked frame too large (%zu bytes)",
956 old_packet_size);
957 return;
958 }
959 } else {
960 log_warn(
961 "Failed to get write buffer for client %s (frame=%p, frame->data=%p)",
962 client->client_id, (void *)frame, frame ? frame->data : NULL);
963 }
964 } else {
965 // During shutdown, this is expected - don't spam error logs
967 SET_ERRNO(ERROR_INVALID_STATE, "Client %s has no incoming video buffer!",
968 client->client_id);
969 } else {
970 log_debug("Client %s: ignoring video packet during shutdown",
971 client->client_id);
972 }
973 }
974
975 // Clean up decompressed data if allocated
976 if (needs_free && rgb_data) {
977 SAFE_FREE(rgb_data);
978 }
979}
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.
@ VIDEO_CODEC_RGBA
Raw RGBA (4 bytes per pixel, uncompressed).
Definition codecs.h:29
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define MAX_FRAME_BUFFER_SIZE
Maximum frame buffer size including headers and compression.
#define NS_PER_SEC_INT
Definition time.h:173
asciichat_error_t frame_validate_legacy(size_t len, size_t expected_rgb_size)
Validate legacy frame format.
asciichat_error_t frame_check_size_overflow(size_t header_size, size_t data_size)
Check for overflow when adding header to data.
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:12
#define FRAME_HEADER_SIZE_LEGACY
Legacy frame header size (width:4 + height:4).
#define SERVER_PROTOCOL_SIZE_BUFFER_SIZE
#define SERVER_PROTOCOL_PRETTY_BUFFER_SIZE
uint64_t capture_timestamp_ns
Timestamp when frame was captured (nanoseconds).
asciichat_error_t image_validate_buffer_size(size_t requested_size)
Validate buffer size against maximum allocation limit.
Definition util/image.c:134
asciichat_error_t image_validate_dimensions(size_t width, size_t height)
Validate image dimensions (non-zero, within limits).
Definition util/image.c:116
asciichat_error_t image_calc_rgb_size(size_t width, size_t height, size_t *out_size)
Calculate total RGB buffer size from dimensions.
Definition util/image.c:64

References ASCIICHAT_OK, atomic_cas_bool(), atomic_load_bool(), video_frame_t::capture_timestamp_ns, client_info::client_id, client_info::client_state_mutex, client_info::codec_capabilities_video, video_frame_t::data, disconnect_client_for_bad_data(), ERROR_INVALID_STATE, format_bytes_pretty(), frame_check_size_overflow(), FRAME_HEADER_SIZE_LEGACY, frame_validate_legacy(), client_info::frames_received, client_info::frames_received_logged, g_should_exit, video_frame_t::height, HOST_TO_NET_U32, image_calc_rgb_size(), image_validate_buffer_size(), image_validate_dimensions(), client_info::incoming_video_buffer, client_info::is_sending_video, client_info::last_received_frame_hash, log_debug, log_debug_every, log_error, log_info, log_info_client, log_warn, MAX_FRAME_BUFFER_SIZE, NET_TO_HOST_U32, NS_PER_SEC_INT, SAFE_FREE, video_frame_t::sequence_number, SERVER_PROTOCOL_PRETTY_BUFFER_SIZE, SERVER_PROTOCOL_SIZE_BUFFER_SIZE, SET_ERRNO, video_frame_t::size, client_info::transport, US_PER_SEC_INT, VIDEO_CODEC_RGBA, VIDEO_CODEC_SUPPORTED, video_frame_begin_write(), video_frame_commit(), and video_frame_t::width.

◆ handle_ping_packet()

void handle_ping_packet ( client_info_t * client,
const void * data,
size_t len )

Handle PING packet - respond with PONG.

Definition at line 671 of file server/protocol.c.

671 {
672 (void)data;
673 (void)len;
674
675 // Serialize the complete PONG write with the sender. TCP packets cannot be
676 // sent concurrently without risking byte-stream interleaving.
677 mutex_lock(&client->send_mutex);
678 if (atomic_load_bool(&client->shutting_down) || !client->transport) {
679 mutex_unlock(&client->send_mutex);
680 return;
681 }
682 acip_transport_t *pong_transport = client->transport;
683 asciichat_error_t pong_result = acip_send_pong(pong_transport);
684 mutex_unlock(&client->send_mutex);
685 if (pong_result != ASCIICHAT_OK) {
686 SET_ERRNO(ERROR_NETWORK, "Failed to send PONG response to client %s: %s",
687 client->client_id, asciichat_error_string(pong_result));
688 }
689}
@ ERROR_NETWORK
Definition error_codes.h:77
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
asciichat_error_t acip_send_pong(acip_transport_t *transport)
Send pong packet.
Definition send.c:382

References acip_send_pong(), ASCIICHAT_OK, atomic_load_bool(), client_info::client_id, ERROR_NETWORK, client_info::send_mutex, SET_ERRNO, client_info::shutting_down, and client_info::transport.

◆ handle_pong_packet()

void handle_pong_packet ( client_info_t * client,
const void * data,
size_t len )

Handle PONG packet - client acknowledged our PING.

Definition at line 694 of file server/protocol.c.

694 {
695 (void)client;
696 (void)data;
697 (void)len;
698 // No action needed - client acknowledged our PING
699}

◆ handle_protocol_version_packet()

void handle_protocol_version_packet ( client_info_t * client,
const void * data,
size_t len )

Process PROTOCOL_VERSION packet - validate protocol compatibility.

Clients send this packet to announce their protocol version and capabilities. The server validates that the major version matches and logs any version mismatches for debugging purposes.

PACKET STRUCTURE EXPECTED:

  • protocol_version_packet_t containing:
    • protocol_version: Major version number (must match PROTOCOL_VERSION_MAJOR)
    • protocol_revision: Minor version number
    • protocol_patch: Patch version number
    • supports_encryption: Encryption capability flag
    • compression_algorithms: Supported compression bitmask
    • feature_flags: Optional feature flags

VALIDATION PERFORMED:

  • Packet size matches sizeof(protocol_version_packet_t)
  • Major protocol version matches (PROTOCOL_VERSION_MAJOR)
  • Reserved bytes are zero (future-proofing)

ERROR HANDLING:

  • Version mismatch is logged but NOT fatal (backward compatibility)
  • Invalid packet size triggers disconnect
Parameters
clientClient that sent the packet
dataPacket payload (protocol_version_packet_t)
lenSize of packet payload in bytes
Note
This is typically the first packet in the handshake
Protocol version validation ensures compatibility

Definition at line 332 of file server/protocol.c.

333 {
334 if (!data) {
335 disconnect_client_for_bad_data(client, "PROTOCOL_VERSION payload missing");
336 return;
337 }
338
339 if (len != sizeof(protocol_version_packet_t)) {
341 client, "PROTOCOL_VERSION invalid size: %zu (expected %zu)", len,
343 return;
344 }
345
346 const protocol_version_packet_t *version =
347 (const protocol_version_packet_t *)data;
348 uint16_t client_major = NET_TO_HOST_U16(version->protocol_version);
349 uint16_t client_minor = NET_TO_HOST_U16(version->protocol_revision);
350 uint16_t client_patch = NET_TO_HOST_U16(version->protocol_patch);
351
352 // Validate major version match (minor version can differ for backward compat)
353 if (client_major != PROTOCOL_VERSION_MAJOR) {
354 log_warn(
355 "Client %s protocol version mismatch: client=%u.%u.%u, server=%u.%u.%u",
356 client->client_id, client_major, client_minor, client_patch,
358 // Note: We don't disconnect on version mismatch for backward compatibility
359 // Clients may be older or newer than server
360 } else if (client_minor != PROTOCOL_VERSION_MINOR) {
361 log_info("Client %s has different protocol revision: client=%u.%u.%u, "
362 "server=%u.%u.%u",
363 client->client_id, client_major, client_minor, client_patch,
366 }
367
368 // Validate reserved bytes are zero
369 for (size_t i = 0; i < sizeof(version->reserved); i++) {
370 if (version->reserved[i] != 0) {
371 log_warn(
372 "Client %s sent non-zero reserved bytes in PROTOCOL_VERSION packet",
373 client->client_id);
374 // Don't disconnect - reserved bytes may be used in future versions
375 break;
376 }
377 }
378
379 // Log supported features
381 log_debug("Client %s supports encryption", client->client_id);
382 }
383 if (version->compression_algorithms != 0) {
384 log_debug("Client %s supports compression: 0x%02x", client->client_id,
385 version->compression_algorithms);
386 }
387 if (version->feature_flags != 0) {
388 uint16_t feature_flags = NET_TO_HOST_U16(version->feature_flags);
390 (feature_flags & PROTOCOL_FEATURE_RECOVERABLE_ERRORS) !=
391 0);
392 log_debug("Client %s supports features: 0x%04x", client->client_id,
393 feature_flags);
394 }
395}
#define ACIP_CRYPTO_HAS_ENCRYPT(mode)
Check if crypto mode includes payload encryption.
Definition packet.h:1171
#define PROTOCOL_FEATURE_RECOVERABLE_ERRORS
Definition packet.h:855
#define PROTOCOL_VERSION_MAJOR
Major protocol version number.
#define PROTOCOL_VERSION_MINOR
Minor protocol version number.
#define PROTOCOL_VERSION_PATCH
Patch protocol version number.
Protocol version negotiation packet structure (Packet Type 1).
Definition packet.h:871
uint16_t protocol_patch
Patch protocol revision.
Definition packet.h:877
uint16_t protocol_revision
Minor protocol revision (server can be newer).
Definition packet.h:875
uint16_t protocol_version
Major protocol version (must match for compatibility).
Definition packet.h:873
uint8_t reserved[5]
Reserved bytes for future expansion (must be zero).
Definition packet.h:887
uint16_t feature_flags
Feature flags bitmask (FEATURE_RLE_ENCODING, etc.).
Definition packet.h:885
uint8_t compression_algorithms
Supported compression algorithms bitmask (COMPRESS_ALGO_*).
Definition packet.h:881
uint8_t supports_encryption
Encryption & authentication mode bitmask (ACIP_CRYPTO_* constants: NONE, ENCRYPT, AUTH,...
Definition packet.h:879

References ACIP_CRYPTO_HAS_ENCRYPT, atomic_store_bool(), client_info::client_id, protocol_version_packet_t::compression_algorithms, disconnect_client_for_bad_data(), protocol_version_packet_t::feature_flags, log_debug, log_info, log_warn, NET_TO_HOST_U16, PROTOCOL_FEATURE_RECOVERABLE_ERRORS, protocol_version_packet_t::protocol_patch, protocol_version_packet_t::protocol_revision, protocol_version_packet_t::protocol_version, PROTOCOL_VERSION_MAJOR, PROTOCOL_VERSION_MINOR, PROTOCOL_VERSION_PATCH, protocol_version_packet_t::reserved, protocol_version_packet_t::supports_encryption, and client_info::supports_recoverable_errors.

◆ handle_remote_log_packet_from_client()

void handle_remote_log_packet_from_client ( client_info_t * client,
const void * data,
size_t len )

Definition at line 1211 of file server/protocol.c.

1212 {
1213 if (!client) {
1214 return;
1215 }
1216
1217 log_level_t remote_level = LOG_INFO;
1219 uint16_t flags = 0;
1220 char message[MAX_REMOTE_LOG_MESSAGE_LENGTH + 1] = {0};
1221
1222 asciichat_error_t parse_result =
1223 packet_parse_remote_log(data, len, &remote_level, &direction, &flags,
1224 message, sizeof(message), NULL);
1225 if (parse_result != ASCIICHAT_OK) {
1226 disconnect_client_for_bad_data(client, "Invalid REMOTE_LOG packet: %s",
1227 asciichat_error_string(parse_result));
1228 return;
1229 }
1230
1231 if (direction != REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER) {
1232 disconnect_client_for_bad_data(client, "REMOTE_LOG direction mismatch: %u",
1233 direction);
1234 return;
1235 }
1236
1237 const bool truncated = (flags & REMOTE_LOG_FLAG_TRUNCATED) != 0;
1238 const char *display_name =
1239 client->display_name[0] ? client->display_name : "(unnamed)";
1240 const char *client_id = client->client_id;
1241
1242 if (truncated) {
1243 log_msg(remote_level, __FILE__, __LINE__, __func__,
1244 "[REMOTE CLIENT %s \"%s\"] %s [message truncated]", client_id,
1245 display_name, message);
1246 } else {
1247 log_msg(remote_level, __FILE__, __LINE__, __func__,
1248 "[REMOTE CLIENT %s \"%s\"] %s", client_id, display_name, message);
1249 }
1250}
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.
log_level_t
Logging levels enumeration.
Definition log/types.h:33
@ REMOTE_LOG_DIRECTION_UNKNOWN
Definition network/log.h:21
@ REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER
Definition network/log.h:23
#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 LOG_INFO
Definition log/types.h:44
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

References ASCIICHAT_OK, client_info::client_id, disconnect_client_for_bad_data(), client_info::display_name, LOG_INFO, log_msg(), MAX_REMOTE_LOG_MESSAGE_LENGTH, packet_parse_remote_log(), REMOTE_LOG_DIRECTION_CLIENT_TO_SERVER, REMOTE_LOG_DIRECTION_UNKNOWN, and REMOTE_LOG_FLAG_TRUNCATED.

◆ handle_runtime_settings()

asciichat_error_t handle_runtime_settings ( client_info_t * client,
const void * data,
size_t length )

Definition at line 1828 of file server/protocol.c.

1829 {
1831 size_t reply_length = 0;
1832 mutex_lock(&client->client_state_mutex);
1833 if (!client->has_terminal_caps || atomic_load_bool(&client->shutting_down)) {
1834 mutex_unlock(&client->client_state_mutex);
1836 "Settings require an active bootstrapped viewer");
1837 }
1838 asciichat_error_t result =
1839 acip_settings_request(&client->render_settings, data, length, reply,
1840 sizeof(reply), &reply_length);
1841 if (result == ASCIICHAT_OK)
1842 publish_render_settings(client);
1843 mutex_unlock(&client->client_state_mutex);
1844 if (result == ASCIICHAT_OK) {
1845 // Teardown takes this mutex before releasing the transport.
1846 mutex_lock(&client->send_mutex);
1847 if (atomic_load_bool(&client->shutting_down) || !client->transport)
1848 result = SET_ERRNO(ERROR_INVALID_STATE, "Viewer is shutting down");
1849 else
1850 result = packet_send_via_transport(client->transport,
1852 reply_length, 0);
1853 mutex_unlock(&client->send_mutex);
1854 }
1855 return result;
1856}
@ PACKET_TYPE_ACIP_SETTINGS_ACK
Settings acknowledgment (Participant -> Initiator).
Definition packet.h:501
asciichat_error_t acip_settings_request(acip_render_settings_t *state, const void *payload, size_t length, uint8_t *reply, size_t capacity, size_t *reply_length)
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

References ACIP_SETTINGS_MAX_SIZE, acip_settings_request(), ASCIICHAT_OK, atomic_load_bool(), client_info::client_state_mutex, ERROR_INVALID_STATE, client_info::has_terminal_caps, packet_send_via_transport(), PACKET_TYPE_ACIP_SETTINGS_ACK, client_info::render_settings, client_info::send_mutex, SET_ERRNO, client_info::shutting_down, and client_info::transport.

Referenced by handle_client_capabilities_packet(), and server_dispatch_packet().

◆ handle_size_packet()

void handle_size_packet ( client_info_t * client,
const void * data,
size_t len )

Process terminal size update packet - handle client window resize.

Clients send this packet when their terminal window is resized, allowing the server to adjust ASCII frame dimensions accordingly. This ensures optimal use of the client's display area.

PACKET STRUCTURE EXPECTED:

STATE CHANGES PERFORMED:

  • Updates client->width with new dimensions
  • Updates client->height with new dimensions
  • Thread-safe update using client state mutex

RENDERING IMPACT:

  • Subsequent ASCII frames will use new dimensions
  • Grid layout calculations will incorporate new size
  • No immediate frame regeneration (happens on next cycle)

ERROR HANDLING:

  • Invalid packet sizes are ignored silently
  • Extreme dimensions are accepted (client responsibility)
  • Concurrent updates are handled safely
Parameters
clientTarget client whose terminal was resized
dataPacket payload containing new dimensions
lenSize of packet payload (should be sizeof(size_packet_t))
Note
Changes take effect on the next rendering cycle
No validation of reasonable dimension ranges

Definition at line 1892 of file server/protocol.c.

1892 {
1893 VALIDATE_PACKET_SIZE(client, data, len, sizeof(size_packet_t), "SIZE");
1894
1895 const size_packet_t *size_pkt = (const size_packet_t *)data;
1896
1897 // Extract and validate new dimensions
1900
1901 VALIDATE_NONZERO(client, width, "width", "SIZE");
1902 VALIDATE_NONZERO(client, height, "height", "SIZE");
1903 VALIDATE_RANGE(client, width, 1, 4096, "width", "SIZE");
1904 VALIDATE_RANGE(client, height, 1, 4096, "height", "SIZE");
1905
1906 mutex_lock(&client->client_state_mutex);
1907 client->width = width;
1908 client->height = height;
1909 mutex_unlock(&client->client_state_mutex);
1910
1911 log_info("Client %s updated terminal size: %ux%u", client->client_id, width,
1912 height);
1913}
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
Terminal size update packet.
Definition packet.h:687
uint32_t height
Terminal height in characters.
Definition packet.h:691
uint32_t width
Terminal width in characters.
Definition packet.h:689

References client_info::client_id, client_info::client_state_mutex, client_info::height, height, size_packet_t::height, log_info, NET_TO_HOST_U16, VALIDATE_NONZERO, VALIDATE_PACKET_SIZE, VALIDATE_RANGE, client_info::width, size_packet_t::width, and width.

◆ handle_stream_start_packet()

void handle_stream_start_packet ( client_info_t * client,
const void * data,
size_t len )

Process STREAM_START packet - client requests to begin media transmission.

Clients send this packet to indicate they're ready to start sending video and/or audio data. The server updates its internal state to expect and process media packets from this client.

PACKET STRUCTURE EXPECTED:

  • uint32_t stream_type (network byte order)
  • Bitmask containing STREAM_TYPE_VIDEO and/or STREAM_TYPE_AUDIO

STATE CHANGES PERFORMED:

  • VIDEO: Records intention to send video (is_sending_video set by first IMAGE_FRAME)
  • AUDIO: Sets client->is_sending_audio = true if STREAM_TYPE_AUDIO present
  • Enables render threads to include this client in output generation

PROTOCOL BEHAVIOR:

  • Client must have announced capabilities via CLIENT_JOIN first
  • Server will start processing IMAGE_FRAME and AUDIO packets
  • Render threads will begin generating output for this client
  • Grid layout will be recalculated to include this client

ERROR HANDLING:

  • Ignores packets with incorrect size
  • Invalid stream types are silently ignored
  • Graceful handling if client lacks necessary capabilities
Parameters
clientTarget client starting media transmission
dataPacket payload containing stream type flags
lenSize of packet payload (should be sizeof(uint32_t))
Note
Changes take effect immediately for subsequent media packets
Render threads will detect the state change on their next cycle
See also
handle_stream_stop_packet() For stopping Media transmission
handle_image_frame_packet() For Video to ASCII Conversion data processing

Definition at line 525 of file server/protocol.c.

526 {
527 VALIDATE_PACKET_SIZE(client, data, len, sizeof(uint32_t), "STREAM_START");
528
529 uint32_t stream_type;
530 memcpy(&stream_type, data, sizeof(uint32_t));
531 stream_type = NET_TO_HOST_U32(stream_type);
532
533 /* Older browser/WASM packet serializers emitted this control payload in
534 * host order while the enclosing ACIP header remained in network order.
535 * Accept that unambiguous two-bit form so a connected browser is not
536 * disconnected before it can send its first frame. */
537 const uint32_t VALID_STREAM_MASK = STREAM_TYPE_VIDEO | STREAM_TYPE_AUDIO;
538 if ((stream_type & VALID_STREAM_MASK) == 0) {
539 uint32_t host_order_stream_type = HOST_TO_NET_U32(stream_type);
540 if ((host_order_stream_type & ~VALID_STREAM_MASK) == 0 &&
541 host_order_stream_type != 0) {
542 log_debug("Normalizing legacy host-order STREAM_START flags 0x%x",
543 stream_type);
544 stream_type = host_order_stream_type;
545 }
546 }
547
548 // Validate at least one stream type flag is set
549 VALIDATE_CAPABILITY_FLAGS(client, stream_type, VALID_STREAM_MASK,
550 "STREAM_START");
551
552 // Validate no unknown stream type bits are set
553 VALIDATE_FLAGS_MASK(client, stream_type, VALID_STREAM_MASK, "STREAM_START");
554
555 if (stream_type & STREAM_TYPE_VIDEO) {
556 atomic_store_bool(&client->is_sending_video, true);
557 }
558 if (stream_type & STREAM_TYPE_AUDIO) {
559 atomic_store_bool(&client->is_sending_audio, true);
560
561 // Create Opus decoder for this client if not already created
562 if (!client->opus_decoder) {
563 client->opus_decoder =
565 if (client->opus_decoder) {
566 log_info("Client %s: Opus decoder created (48kHz)", client->client_id);
567 } else {
568 log_error("Client %s: Failed to create Opus decoder",
569 client->client_id);
570 }
571 }
572 }
573
574 if (stream_type & STREAM_TYPE_VIDEO) {
575 log_info("Client %s announced video stream (waiting for first frame)",
576 client->client_id);
577 }
578 if (stream_type & STREAM_TYPE_AUDIO) {
579 log_info("Client %s started audio stream", client->client_id);
580 }
581
582 // Notify client of stream start acknowledgment
583 const char *streams =
584 (stream_type & STREAM_TYPE_VIDEO) && (stream_type & STREAM_TYPE_AUDIO)
585 ? "video+audio"
586 : ((stream_type & STREAM_TYPE_VIDEO) ? "video" : "audio");
587 if (client->transport != NULL) {
588 log_info_client(client, "Stream started: %s", streams);
589 }
590}
opus_codec_t * opus_codec_create_decoder_channels(int sample_rate, int channels)
Definition opus.c:107
#define STREAM_TYPE_VIDEO
Video stream.
Definition packet.h:1016
#define STREAM_TYPE_AUDIO
Audio stream.
Definition packet.h:1017

References atomic_store_bool(), AUDIO_CHANNELS, AUDIO_SAMPLE_RATE, client_info::client_id, HOST_TO_NET_U32, client_info::is_sending_audio, client_info::is_sending_video, log_debug, log_error, log_info, log_info_client, NET_TO_HOST_U32, opus_codec_create_decoder_channels(), client_info::opus_decoder, STREAM_TYPE_AUDIO, STREAM_TYPE_VIDEO, client_info::transport, VALIDATE_CAPABILITY_FLAGS, VALIDATE_FLAGS_MASK, and VALIDATE_PACKET_SIZE.

◆ handle_stream_stop_packet()

void handle_stream_stop_packet ( client_info_t * client,
const void * data,
size_t len )

Process STREAM_STOP packet - client requests to halt media transmission.

Clients send this packet to gracefully stop sending video and/or audio data. The server updates its state to exclude this client from active media processing and grid layout calculations.

PACKET STRUCTURE EXPECTED:

  • uint32_t stream_type (network byte order)
  • Bitmask containing STREAM_TYPE_VIDEO and/or STREAM_TYPE_AUDIO

STATE CHANGES PERFORMED:

  • Sets client->is_sending_video = false if STREAM_TYPE_VIDEO present
  • Sets client->is_sending_audio = false if STREAM_TYPE_AUDIO present
  • Render threads will stop including this client in output

PROTOCOL BEHAVIOR:

  • Client remains connected but won't appear in video grid
  • Existing buffered media from this client will still be processed
  • Grid layout recalculates to exclude this client
  • Client can restart streaming with STREAM_START packet

ERROR HANDLING:

  • Ignores packets with incorrect size
  • Invalid stream types are silently ignored
  • Safe to call multiple times or when not streaming
Parameters
clientTarget client stopping media transmission
dataPacket payload containing stream type flags
lenSize of packet payload (should be sizeof(uint32_t))
Note
Changes take effect immediately
Render threads will detect the state change on their next cycle
See also
handle_stream_start_packet() For starting Media transmission

Definition at line 628 of file server/protocol.c.

629 {
630 VALIDATE_PACKET_SIZE(client, data, len, sizeof(uint32_t), "STREAM_STOP");
631
632 uint32_t stream_type;
633 memcpy(&stream_type, data, sizeof(uint32_t));
634 stream_type = NET_TO_HOST_U32(stream_type);
635
636 // Validate at least one stream type flag is set
637 const uint32_t VALID_STREAM_MASK = STREAM_TYPE_VIDEO | STREAM_TYPE_AUDIO;
638 VALIDATE_CAPABILITY_FLAGS(client, stream_type, VALID_STREAM_MASK,
639 "STREAM_STOP");
640
641 // Validate no unknown stream type bits are set
642 VALIDATE_FLAGS_MASK(client, stream_type, VALID_STREAM_MASK, "STREAM_STOP");
643
644 if (stream_type & STREAM_TYPE_VIDEO) {
645 atomic_store_bool(&client->is_sending_video, false);
646 }
647 if (stream_type & STREAM_TYPE_AUDIO) {
648 atomic_store_bool(&client->is_sending_audio, false);
649 }
650
651 if (stream_type & STREAM_TYPE_VIDEO) {
652 log_info("Client %s stopped video stream", client->client_id);
653 }
654 if (stream_type & STREAM_TYPE_AUDIO) {
655 log_info("Client %s stopped audio stream", client->client_id);
656 }
657
658 // Notify client of stream stop acknowledgment
659 const char *streams =
660 (stream_type & STREAM_TYPE_VIDEO) && (stream_type & STREAM_TYPE_AUDIO)
661 ? "video+audio"
662 : ((stream_type & STREAM_TYPE_VIDEO) ? "video" : "audio");
663 if (client->transport != NULL) {
664 log_info_client(client, "Stream stopped: %s", streams);
665 }
666}

References atomic_store_bool(), client_info::client_id, client_info::is_sending_audio, client_info::is_sending_video, log_info, log_info_client, NET_TO_HOST_U32, STREAM_TYPE_AUDIO, STREAM_TYPE_VIDEO, client_info::transport, VALIDATE_CAPABILITY_FLAGS, VALIDATE_FLAGS_MASK, and VALIDATE_PACKET_SIZE.

◆ send_server_state_to_client()

int send_server_state_to_client ( client_info_t * client)

Send current server state to a specific client.

Generates and queues a SERVER_STATE packet containing information about the current number of connected and active clients. This helps clients understand the multi-user environment and adjust their behavior accordingly.

PACKET CONTENT GENERATED:

  • server_state_packet_t containing:
    • connected_client_count: Total clients connected to server
    • active_client_count: Clients actively sending video/audio
    • reserved: Padding for future extensions

USAGE SCENARIOS:

  • Initial state after client joins server
  • Periodic updates when client count changes
  • Response to client requests for server information

IMPLEMENTATION DETAILS:

  • Counts active clients by scanning global client manager
  • Converts data to network byte order before queuing
  • Uses client's video queue for delivery
  • Non-blocking operation (queues for later delivery)

THREAD SAFETY:

  • Uses reader lock on global client manager
  • Safe to call from any thread
  • Atomic snapshot of client counts

ERROR HANDLING:

  • Returns -1 if client or queue is invalid
  • Queue overflow handled by packet_queue_push_copy()
  • No side effects on failure
Parameters
clientTarget client to receive server state information
Returns
0 on successful queuing, -1 on error
Note
Packet delivery happens asynchronously via send thread
Client count may change between queuing and delivery
See also
broadcast_server_state_to_all_clients() For multi-client updates

Definition at line 1967 of file server/protocol.c.

1967 {
1968 if (!client) {
1969 return -1;
1970 }
1971
1972 // Count active clients - LOCK OPTIMIZATION: Use atomic reads, no rwlock
1973 // needed
1974 int active_count = 0;
1975 for (int i = 0; i < MAX_CLIENTS; i++) {
1976 if (atomic_load_bool(&g_client_manager.clients[i].active)) {
1977 active_count++;
1978 }
1979 }
1980
1981 // Prepare server state packet
1983 state.connected_client_count = active_count;
1984 state.active_client_count = active_count; // For now, all connected are active
1985 memset(state.reserved, 0, sizeof(state.reserved));
1986
1987 // Convert to network byte order
1988 server_state_packet_t net_state;
1989 net_state.connected_client_count =
1992 memset(net_state.reserved, 0, sizeof(net_state.reserved));
1993
1994 // Send server state via ACIP transport
1995 // Protect socket writes with send_mutex to prevent race with send_thread.
1996 mutex_lock(&client->send_mutex);
1997 asciichat_error_t result =
1998 acip_send_server_state(client->transport, &net_state);
1999 mutex_unlock(&client->send_mutex);
2000
2001 if (result != ASCIICHAT_OK) {
2002 SET_ERRNO(ERROR_NETWORK, "Failed to send server state to client %s: %s",
2003 client->client_id, asciichat_error_string(result));
2004 return -1;
2005 }
2006
2007 log_debug("Sent server state to client %s: %u connected, %u active",
2008 client->client_id, state.connected_client_count,
2009 state.active_client_count);
2010 return 0;
2011}
#define MAX_CLIENTS
Maximum possible clients (static array size) - actual runtime limit set by –max-clients (1-128).
asciichat_error_t acip_send_server_state(acip_transport_t *transport, const server_state_packet_t *state)
Send server state update to client (server → client).
client_manager_t g_client_manager
Hash table entry for client packet dispatch.
Server state packet structure.
Definition packet.h:757
uint32_t reserved[6]
Reserved fields for future use (must be zero).
Definition packet.h:763
uint32_t active_client_count
Number of clients actively sending video/audio streams.
Definition packet.h:761
uint32_t connected_client_count
Total number of currently connected clients.
Definition packet.h:759

References acip_send_server_state(), server_state_packet_t::active_client_count, ASCIICHAT_OK, atomic_load_bool(), client_info::client_id, server_state_packet_t::connected_client_count, ERROR_NETWORK, g_client_manager, HOST_TO_NET_U32, log_debug, MAX_CLIENTS, server_state_packet_t::reserved, client_info::send_mutex, SET_ERRNO, and client_info::transport.