ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
handlers.c
Go to the documentation of this file.
1
12
13/* Storage capacities in elements; text buffers include the terminating NUL. */
14#define NETWORK_ACIP_HANDLERS_MSG_BUFFER_SIZE 512
15#define NETWORK_ACIP_HANDLERS_HEX_BUFFER_SIZE 512
16
24#include <ascii-chat/log/log.h>
26#include <ascii-chat/common.h>
28#include <string.h>
29
30// =============================================================================
31// Handler Function Pointer Types
32// =============================================================================
33
34typedef asciichat_error_t (*acip_client_handler_func_t)(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
35
36typedef asciichat_error_t (*acip_server_handler_func_t)(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
37
38// =============================================================================
39// Packet Type to Handler Index Mapping (O(1) hash table lookup)
40// =============================================================================
41// Open-addressing hash table with linear probing. key=0 means empty slot.
42// Stores handler_idx+1 so that 0 can indicate "not found" after lookup.
43
44#define HANDLER_HASH_SIZE 32 // ~50% load factor for 14-16 entries
45#define CLIENT_HANDLER_COUNT 20 // Added 6 crypto handshake handlers
46#define SERVER_HANDLER_COUNT 21
47
56
57// Hash function: simple modulo
58#define HANDLER_HASH(type) ((type) % HANDLER_HASH_SIZE)
59
60// Lookup function: linear probing with full table scan
61// Must check all HANDLER_HASH_SIZE slots because gaps can exist in the hash table
62static inline int handler_hash_lookup(const handler_hash_entry_t *table, packet_type_t type) {
63 uint32_t h = HANDLER_HASH(type);
64 log_dev_every(4500 * US_PER_MS_INT, "type=%d, hash=%u", type, h);
65 for (int i = 0; i < HANDLER_HASH_SIZE; i++) {
66 uint32_t slot = (h + i) % HANDLER_HASH_SIZE;
67 log_dev_every(4500 * US_PER_MS_INT, " Checking slot %u: key=%d, handler_idx=%d", slot, table[slot].key, table[slot].handler_idx);
68 // Match found - return handler index immediately
69 if (table[slot].key == type) {
70 log_dev_every(4500 * US_PER_MS_INT, " Found match at slot %u, handler_idx=%d", slot, table[slot].handler_idx);
71 return table[slot].handler_idx;
72 }
73 // NOTE: Do NOT return on empty slot! Hash table can have gaps due to collision chains.
74 // Continue probing through entire table to find the key.
75 }
76 log_debug(" No match found after scanning all %u slots", HANDLER_HASH_SIZE);
77 return -1; // Not found after checking all slots
78}
79
80// Client packet type -> handler index hash table
81// Slots computed via linear probing: hash = type % 32
82// clang-format off
83static const handler_hash_entry_t g_client_handler_hash[HANDLER_HASH_SIZE] = {
84 [0] = {PACKET_TYPE_AUDIO_BATCH, 1}, // hash(4000)=0
85 [1] = {PACKET_TYPE_AUDIO_OPUS_BATCH, 2}, // hash(4001)=1
86 [7] = {PACKET_TYPE_CRYPTO_AUTH_CHALLENGE, 15}, // hash(1104)=16, probed->7
87 [8] = {PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP, 16}, // hash(1107)=19, probed->8
88 [9] = {PACKET_TYPE_PING, 6}, // hash(5001)=9
89 [10] = {PACKET_TYPE_PONG, 7}, // hash(5002)=10
90 [11] = {PACKET_TYPE_CRYPTO_AUTH_FAILED, 17}, // hash(1106)=18, probed->11
91 [13] = {PACKET_TYPE_CRYPTO_PARAMETERS, 19}, // hash(1101)=13
92 [14] = {PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE, 18}, // hash(1108)=20, probed->14
93 [15] = {PACKET_TYPE_CLEAR_CONSOLE, 8}, // hash(5007)=15
94 [16] = {PACKET_TYPE_SERVER_STATE, 3}, // hash(5008)=16
95 [17] = {PACKET_TYPE_CRYPTO_REKEY_REQUEST, 9}, // hash(1201)=17
96 [18] = {PACKET_TYPE_CRYPTO_REKEY_RESPONSE, 10}, // hash(1202)=18
97 [19] = {PACKET_TYPE_ERROR_MESSAGE, 4}, // hash(2003)=19
98 [20] = {PACKET_TYPE_REMOTE_LOG, 5}, // hash(2004)=20
99 [21] = {PACKET_TYPE_ACIP_SESSION_JOINED, 13}, // hash(6005)=21
100 [22] = {PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT, 14}, // hash(1102)=14, probed->22
101 [24] = {PACKET_TYPE_ASCII_FRAME, 0}, // hash(3000)=24
102 [25] = {PACKET_TYPE_ACIP_WEBRTC_SDP, 11}, // hash(6009)=25
103 [26] = {PACKET_TYPE_ACIP_WEBRTC_ICE, 12}, // hash(6010)=26
104};
105// clang-format on
106
107// Server packet type -> handler index hash table
108// clang-format off
109static const handler_hash_entry_t g_server_handler_hash[HANDLER_HASH_SIZE] = {
110 [0] = {PACKET_TYPE_AUDIO_BATCH, 3}, // hash(4000)=0
111 [1] = {PACKET_TYPE_PROTOCOL_VERSION, 0}, // hash(1)=1
112 [2] = {PACKET_TYPE_AUDIO_OPUS_BATCH, 4}, // hash(4001)=1, probed->2
113 [8] = {PACKET_TYPE_CLIENT_CAPABILITIES, 5}, // hash(5000)=8
114 [9] = {PACKET_TYPE_PING, 6}, // hash(5001)=9
115 [10] = {PACKET_TYPE_PONG, 7}, // hash(5002)=10
116 [11] = {PACKET_TYPE_CLIENT_JOIN, 8}, // hash(5003)=11
117 [12] = {PACKET_TYPE_CLIENT_LEAVE, 9}, // hash(5004)=12
118 [13] = {PACKET_TYPE_STREAM_START, 10}, // hash(5005)=13
119 [14] = {PACKET_TYPE_STREAM_STOP, 11}, // hash(5006)=14
120 [15] = {PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP, 17}, // hash(1103)=15
121 [17] = {PACKET_TYPE_CRYPTO_REKEY_REQUEST, 14}, // hash(1201)=17
122 [18] = {PACKET_TYPE_CRYPTO_REKEY_RESPONSE, 15}, // hash(1202)=18
123 [19] = {PACKET_TYPE_ERROR_MESSAGE, 13}, // hash(2003)=19
124 [20] = {PACKET_TYPE_REMOTE_LOG, 12}, // hash(2004)=20
125 [21] = {PACKET_TYPE_CRYPTO_REKEY_COMPLETE, 16}, // hash(1203)=19, probed->21
126 [22] = {PACKET_TYPE_CRYPTO_AUTH_RESPONSE, 18}, // hash(1105)=17, probed->22
127 [23] = {PACKET_TYPE_CRYPTO_NO_ENCRYPTION, 19}, // hash(1109)=21, probed->23
128 [25] = {PACKET_TYPE_IMAGE_FRAME, 1}, // hash(3001)=25
129 [27] = {PACKET_TYPE_IMAGE_FRAME_H264, 20},
130 [26] = {PACKET_TYPE_IMAGE_FRAME_H265, 2}, // hash(3002)=26
131};
132// clang-format on
133
134// =============================================================================
135// Client-Side Packet Handlers
136// =============================================================================
137
138// Forward declarations for client handlers
139static asciichat_error_t handle_client_ascii_frame(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
140static asciichat_error_t handle_client_audio_batch(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
141static asciichat_error_t handle_client_audio_opus_batch(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
142static asciichat_error_t handle_client_server_state(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
143static asciichat_error_t handle_client_error_message(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
144static asciichat_error_t handle_client_remote_log(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
145static asciichat_error_t handle_client_ping(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
146static asciichat_error_t handle_client_pong(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
147static asciichat_error_t handle_client_clear_console(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
148static asciichat_error_t handle_client_webrtc_sdp(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
149static asciichat_error_t handle_client_webrtc_ice(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
150static asciichat_error_t handle_client_session_joined(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
151static asciichat_error_t handle_client_crypto_key_exchange_init(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
152static asciichat_error_t handle_client_crypto_auth_challenge(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
153static asciichat_error_t handle_client_crypto_server_auth_resp(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
154static asciichat_error_t handle_client_crypto_auth_failed(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
155static asciichat_error_t handle_client_crypto_handshake_complete(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
156static asciichat_error_t handle_client_crypto_parameters(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks);
157
158// Client handler dispatch table (indexed by client_handler_index())
159static const acip_client_handler_func_t g_client_handlers[CLIENT_HANDLER_COUNT] = {
160 handle_client_ascii_frame, // 0
161 handle_client_audio_batch, // 1
162 handle_client_audio_opus_batch, // 2
163 handle_client_server_state, // 3
164 handle_client_error_message, // 4
165 handle_client_remote_log, // 5
166 handle_client_ping, // 6
167 handle_client_pong, // 7
168 handle_client_clear_console, // 8
169 NULL, // 9
170 NULL, // 10
171 handle_client_webrtc_sdp, // 11
172 handle_client_webrtc_ice, // 12
173 handle_client_session_joined, // 13
174 handle_client_crypto_key_exchange_init, // 14
175 handle_client_crypto_auth_challenge, // 15
176 handle_client_crypto_server_auth_resp, // 16
177 handle_client_crypto_auth_failed, // 17
178 handle_client_crypto_handshake_complete, // 18
179 handle_client_crypto_parameters, // 19
180};
181
182asciichat_error_t acip_handle_client_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
183 stats_runtime_packet(transport ? transport->stats_peer : NULL, type, payload_len, false, true);
184 if (!transport || !callbacks) {
185 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport or callbacks");
186 }
187 (void)transport;
188
189 // ACDS broadcasts participant lifecycle notifications to peers. The generic
190 // client callback set does not expose them, so ignore them while keeping the
191 // signaling receive loop alive for subsequent SDP and ICE packets.
193 return ASCIICHAT_OK;
194 }
195
196 // O(1) dispatch via hash table lookup
197 int idx = handler_hash_lookup(g_client_handler_hash, type);
198 if (idx < 0) {
199 return SET_ERRNO(ERROR_INVALID_PARAM, "Unhandled client packet type: %d", type);
200 }
201
202 return g_client_handlers[idx](payload, payload_len, callbacks);
203}
204
205// =============================================================================
206// Client Handler Implementations (extracted from switch cases)
207// =============================================================================
208
209static asciichat_error_t handle_client_ascii_frame(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
210 if (!callbacks->on_ascii_frame) {
211 return ASCIICHAT_OK;
212 }
213
214 if (payload_len < sizeof(ascii_frame_packet_t)) {
215 return SET_ERRNO(ERROR_INVALID_PARAM, "ASCII_FRAME payload too small");
216 }
217
218 // Extract header
220 memcpy(&header, payload, sizeof(header));
221
222 // Convert from network byte order
223 header.width = NET_TO_HOST_U32(header.width);
224 header.height = NET_TO_HOST_U32(header.height);
225 header.original_size = NET_TO_HOST_U32(header.original_size);
226 header.compressed_size = NET_TO_HOST_U32(header.compressed_size);
227 header.checksum = NET_TO_HOST_U32(header.checksum);
228 header.flags = NET_TO_HOST_U32(header.flags);
229
230 // Get frame data (after header)
231 const void *frame_data = (const uint8_t *)payload + sizeof(ascii_frame_packet_t);
232 size_t frame_data_len = payload_len - sizeof(ascii_frame_packet_t);
233
234 // Validate frame dimensions to prevent DoS and buffer overflow attacks
235 if (header.width == 0 || header.height == 0) {
236 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid frame dimensions: %ux%u (width and height must be > 0)", header.width, header.height);
237 }
238
239 // Sanity check: prevent unreasonably large frames (e.g., > 16K resolution)
240 // This protects against resource exhaustion attacks
241 const uint32_t MAX_WIDTH = 16384; // 16K
242 const uint32_t MAX_HEIGHT = 16384; // 16K
243 if (header.width > MAX_WIDTH || header.height > MAX_HEIGHT) {
244 return SET_ERRNO(ERROR_INVALID_PARAM, "Frame dimensions too large: %ux%u (max: %ux%u)", header.width, header.height, MAX_WIDTH, MAX_HEIGHT);
245 }
246
247 log_debug_once("Received first ASCII frame");
248 callbacks->on_ascii_frame(&header, frame_data, frame_data_len, callbacks->app_ctx);
249 return ASCIICHAT_OK;
250}
251
252static asciichat_error_t handle_client_audio_batch(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
253 if (!callbacks->on_audio_batch) {
254 return ASCIICHAT_OK;
255 }
256
257 if (payload_len < sizeof(audio_batch_packet_t)) {
258 return SET_ERRNO(ERROR_INVALID_PARAM, "AUDIO_BATCH payload too small");
259 }
260
261 // Parse batch header
262 const audio_batch_packet_t *batch_header = (const audio_batch_packet_t *)payload;
263 uint32_t batch_count = NET_TO_HOST_U32(batch_header->batch_count);
264 uint32_t total_samples = NET_TO_HOST_U32(batch_header->total_samples);
265 uint32_t sample_rate = NET_TO_HOST_U32(batch_header->sample_rate);
266 uint32_t channels = NET_TO_HOST_U32(batch_header->channels);
267
268 // Validate sample rate and channels
269 // Supported sample rates: 8000, 16000, 24000, 32000, 44100, 48000, 96000, 192000 Hz
270 if (sample_rate == 0 || (sample_rate < 8000 || sample_rate > 192000) ||
271 (sample_rate != 8000 && sample_rate != 16000 && sample_rate != 24000 && sample_rate != 32000 && sample_rate != 44100 && sample_rate != 48000 && sample_rate != 96000 && sample_rate != 192000)) {
272 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid audio sample rate: %u Hz (expected: 8000, 16000, 24000, 32000, 44100, 48000, 96000, or 192000)", sample_rate);
273 }
274
275 // Validate channel count (1-8 channels supported)
276 if (channels == 0 || channels > 8) {
277 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid audio channel count: %u (expected: 1-8)", channels);
278 }
279
280 // Validate batch count
281 (void)batch_count;
282
283 // Validate size
284 size_t expected_size = sizeof(audio_batch_packet_t) + (total_samples * sizeof(uint32_t));
285 if (payload_len != expected_size) {
286 return SET_ERRNO(ERROR_INVALID_PARAM, "AUDIO_BATCH size mismatch");
287 }
288
289 // Extract quantized samples
290 const uint8_t *samples_ptr = (const uint8_t *)payload + sizeof(audio_batch_packet_t);
291
292 // Dequantize samples to float
293 float *samples = SAFE_MALLOC(total_samples * sizeof(float), float *);
294 if (!samples) {
295 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate audio batch buffer");
296 }
297
298 asciichat_error_t result = audio_dequantize_samples(samples_ptr, total_samples, samples);
299 if (result != ASCIICHAT_OK) {
300 SAFE_FREE(samples);
301 return result;
302 }
303
304 // Copy header for callback
305 audio_batch_packet_t header_copy = *batch_header;
306 header_copy.batch_count = batch_count;
307 header_copy.total_samples = total_samples;
308 header_copy.sample_rate = sample_rate;
309 header_copy.channels = channels;
310
311 callbacks->on_audio_batch(&header_copy, samples, total_samples, callbacks->app_ctx);
312
313 SAFE_FREE(samples);
314 return ASCIICHAT_OK;
315}
316
317static asciichat_error_t handle_client_audio_opus_batch(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
318 if (!callbacks->on_audio_opus_batch) {
319 return ASCIICHAT_OK;
320 }
321
322 // Opus batch data (header + sizes + opus frames)
323 callbacks->on_audio_opus_batch(payload, payload_len, callbacks->app_ctx);
324 return ASCIICHAT_OK;
325}
326
327static asciichat_error_t handle_client_server_state(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
328 if (!callbacks->on_server_state) {
329 return ASCIICHAT_OK;
330 }
331
332 if (payload_len != sizeof(server_state_packet_t)) {
333 return SET_ERRNO(ERROR_INVALID_PARAM, "SERVER_STATE size mismatch");
334 }
335
336 callbacks->on_server_state((const server_state_packet_t *)payload, callbacks->app_ctx);
337 return ASCIICHAT_OK;
338}
339
340static asciichat_error_t handle_client_error_message(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
341 if (!callbacks->on_error) {
342 return ASCIICHAT_OK;
343 }
344
345 if (payload_len < sizeof(error_packet_t)) {
346 return SET_ERRNO(ERROR_INVALID_PARAM, "ERROR_MESSAGE payload too small");
347 }
348
349 const error_packet_t *header = (const error_packet_t *)payload;
350 const char *message = (const char *)payload + sizeof(error_packet_t);
351 size_t msg_len = payload_len - sizeof(error_packet_t);
352
353 // Ensure null-terminated message
354 char msg_buffer[MAX_ERROR_MESSAGE_LENGTH + 1];
355 size_t copy_len = msg_len < MAX_ERROR_MESSAGE_LENGTH ? msg_len : MAX_ERROR_MESSAGE_LENGTH;
356 memcpy(msg_buffer, message, copy_len);
357 msg_buffer[copy_len] = '\0';
358
359 callbacks->on_error(header, msg_buffer, callbacks->app_ctx);
360 return ASCIICHAT_OK;
361}
362
363static asciichat_error_t handle_client_remote_log(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
364 if (!callbacks->on_remote_log) {
365 return ASCIICHAT_OK;
366 }
367
368 if (payload_len < sizeof(remote_log_packet_t)) {
369 return SET_ERRNO(ERROR_INVALID_PARAM, "REMOTE_LOG payload too small");
370 }
371
372 const remote_log_packet_t *header = (const remote_log_packet_t *)payload;
373 const char *message = (const char *)payload + sizeof(remote_log_packet_t);
374 size_t msg_len = payload_len - sizeof(remote_log_packet_t);
375
376 // Ensure null-terminated message
378 size_t copy_len = msg_len < sizeof(msg_buffer) - 1 ? msg_len : sizeof(msg_buffer) - 1;
379 memcpy(msg_buffer, message, copy_len);
380 msg_buffer[copy_len] = '\0';
381
382 callbacks->on_remote_log(header, msg_buffer, callbacks->app_ctx);
383 return ASCIICHAT_OK;
384}
385
386static asciichat_error_t handle_client_ping(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
387 (void)payload;
388 (void)payload_len;
389
390 if (callbacks->on_ping) {
391 callbacks->on_ping(callbacks->app_ctx);
392 }
393 return ASCIICHAT_OK;
394}
395
396static asciichat_error_t handle_client_pong(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
397 (void)payload;
398 (void)payload_len;
399
400 if (callbacks->on_pong) {
401 callbacks->on_pong(callbacks->app_ctx);
402 }
403 return ASCIICHAT_OK;
404}
405
406static asciichat_error_t handle_client_clear_console(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
407 (void)payload;
408 (void)payload_len;
409
410 if (callbacks->on_clear_console) {
411 callbacks->on_clear_console(callbacks->app_ctx);
412 }
413 return ASCIICHAT_OK;
414}
415
416static asciichat_error_t handle_client_webrtc_sdp(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
417 if (!callbacks->on_webrtc_sdp) {
418 return ASCIICHAT_OK;
419 }
420
421 if (payload_len < sizeof(acip_webrtc_sdp_t)) {
422 return SET_ERRNO(ERROR_INVALID_PARAM, "WEBRTC_SDP payload too small");
423 }
424
425 const acip_webrtc_sdp_t *sdp = (const acip_webrtc_sdp_t *)payload;
426 callbacks->on_webrtc_sdp(sdp, payload_len, callbacks->app_ctx);
427 return ASCIICHAT_OK;
428}
429
430static asciichat_error_t handle_client_webrtc_ice(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
431 if (!callbacks->on_webrtc_ice) {
432 return ASCIICHAT_OK;
433 }
434
435 if (payload_len < sizeof(acip_webrtc_ice_t)) {
436 return SET_ERRNO(ERROR_INVALID_PARAM, "WEBRTC_ICE payload too small");
437 }
438
439 const acip_webrtc_ice_t *ice = (const acip_webrtc_ice_t *)payload;
440 callbacks->on_webrtc_ice(ice, payload_len, callbacks->app_ctx);
441 return ASCIICHAT_OK;
442}
443
444static asciichat_error_t handle_client_session_joined(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
445 if (!callbacks->on_session_joined) {
446 return ASCIICHAT_OK;
447 }
448
449 if (payload_len < sizeof(acip_session_joined_t)) {
450 return SET_ERRNO(ERROR_INVALID_PARAM, "SESSION_JOINED payload too small (got %zu, need %zu)", payload_len, sizeof(acip_session_joined_t));
451 }
452
453 // Parse the session_joined response
454 const acip_session_joined_t *joined = (const acip_session_joined_t *)payload;
455
456 // Log the result
457 if (joined->success) {
458 log_debug("Session join succeeded: session_id=%.16s, participant_id=%.16s, server=%s:%u, type=%s", (const char *)joined->session_id, (const char *)joined->participant_id, joined->server_address,
459 joined->server_port, joined->session_type == 1 ? "WebRTC" : "DirectTCP");
460 } else {
461 log_warn("Session join failed: error %d: %s", joined->error_code, joined->error_message);
462 }
463
464 // Dispatch to application callback
465 callbacks->on_session_joined(joined, callbacks->app_ctx);
466 return ASCIICHAT_OK;
467}
468
469static asciichat_error_t handle_client_crypto_key_exchange_init(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
470 if (!callbacks->on_crypto_key_exchange_init) {
471 return ASCIICHAT_OK;
472 }
473
474 // Dispatch to application callback with packet type
475 callbacks->on_crypto_key_exchange_init(PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT, payload, payload_len, callbacks->app_ctx);
476 return ASCIICHAT_OK;
477}
478
479static asciichat_error_t handle_client_crypto_auth_challenge(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
480 if (!callbacks->on_crypto_auth_challenge) {
481 return ASCIICHAT_OK;
482 }
483
484 // Dispatch to application callback with packet type
485 callbacks->on_crypto_auth_challenge(PACKET_TYPE_CRYPTO_AUTH_CHALLENGE, payload, payload_len, callbacks->app_ctx);
486 return ASCIICHAT_OK;
487}
488
489static asciichat_error_t handle_client_crypto_server_auth_resp(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
490 if (!callbacks->on_crypto_server_auth_resp) {
491 return ASCIICHAT_OK;
492 }
493
494 // Dispatch to application callback with packet type
495 callbacks->on_crypto_server_auth_resp(PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP, payload, payload_len, callbacks->app_ctx);
496 return ASCIICHAT_OK;
497}
498
499static asciichat_error_t handle_client_crypto_auth_failed(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
500 if (!callbacks->on_crypto_auth_failed) {
501 return ASCIICHAT_OK;
502 }
503
504 // Dispatch to application callback with packet type
505 callbacks->on_crypto_auth_failed(PACKET_TYPE_CRYPTO_AUTH_FAILED, payload, payload_len, callbacks->app_ctx);
506 return ASCIICHAT_OK;
507}
508
509static asciichat_error_t handle_client_crypto_handshake_complete(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
510 if (!callbacks->on_crypto_handshake_complete) {
511 return ASCIICHAT_OK;
512 }
513
514 // Dispatch to application callback with packet type
515 callbacks->on_crypto_handshake_complete(PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE, payload, payload_len, callbacks->app_ctx);
516 return ASCIICHAT_OK;
517}
518
519static asciichat_error_t handle_client_crypto_parameters(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks) {
520 if (!callbacks->on_crypto_parameters) {
521 return ASCIICHAT_OK;
522 }
523
524 // Dispatch to application callback with packet type
525 callbacks->on_crypto_parameters(PACKET_TYPE_CRYPTO_PARAMETERS, payload, payload_len, callbacks->app_ctx);
526 return ASCIICHAT_OK;
527}
528
529// =============================================================================
530// Server-Side Packet Handlers
531// =============================================================================
532
533// Forward declarations for server handlers
534static asciichat_error_t handle_server_image_frame(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
535static asciichat_error_t handle_server_image_frame_h264(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
536static asciichat_error_t handle_server_image_frame_h265(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
537static asciichat_error_t handle_server_audio_batch(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
538static asciichat_error_t handle_server_audio_opus_batch(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
539static asciichat_error_t handle_server_client_join(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
540static asciichat_error_t handle_server_client_leave(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
541static asciichat_error_t handle_server_stream_start(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
542static asciichat_error_t handle_server_stream_stop(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
543static asciichat_error_t handle_server_capabilities(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
544static asciichat_error_t handle_server_ping(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
545static asciichat_error_t handle_server_remote_log(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
546static asciichat_error_t handle_server_protocol_version(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
547static asciichat_error_t handle_server_pong(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
548static asciichat_error_t handle_server_error_message(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
549static asciichat_error_t handle_server_crypto_key_exchange_resp(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
550static asciichat_error_t handle_server_crypto_auth_response(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
551static asciichat_error_t handle_server_crypto_no_encryption(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks);
552
553// Server handler dispatch table (indexed by server_handler_index())
554static const acip_server_handler_func_t g_server_handlers[SERVER_HANDLER_COUNT] = {
555 handle_server_protocol_version, // 0
556 handle_server_image_frame, // 1
557 handle_server_image_frame_h265, // 2
558 handle_server_audio_batch, // 3
559 handle_server_audio_opus_batch, // 4
560 handle_server_capabilities, // 5
561 handle_server_ping, // 6
562 handle_server_pong, // 7
563 handle_server_client_join, // 8
564 handle_server_client_leave, // 9
565 handle_server_stream_start, // 10
566 handle_server_stream_stop, // 11
567 handle_server_remote_log, // 12
568 handle_server_error_message, // 13
569 NULL, // 14
570 NULL, // 15
571 NULL, // 16
572 handle_server_crypto_key_exchange_resp, // 17
573 handle_server_crypto_auth_response, // 18
574 handle_server_crypto_no_encryption, // 19
575 handle_server_image_frame_h264, // 20
576};
577
578// Canonical names for the wire packet types.
580 switch (type) {
582 return "PROTOCOL_VERSION";
584 return "CRYPTO_CLIENT_HELLO";
586 return "CRYPTO_CAPABILITIES";
588 return "CRYPTO_PARAMETERS";
590 return "CRYPTO_KEY_EXCHANGE_INIT";
592 return "CRYPTO_KEY_EXCHANGE_RESP";
594 return "CRYPTO_AUTH_CHALLENGE";
596 return "CRYPTO_AUTH_RESPONSE";
598 return "CRYPTO_AUTH_FAILED";
600 return "CRYPTO_SERVER_AUTH_RESP";
602 return "CRYPTO_HANDSHAKE_COMPLETE";
604 return "CRYPTO_NO_ENCRYPTION";
606 return "ENCRYPTED";
608 return "CRYPTO_REKEY_REQUEST";
610 return "CRYPTO_REKEY_RESPONSE";
612 return "CRYPTO_REKEY_COMPLETE";
614 return "SIZE_MESSAGE";
616 return "AUDIO_MESSAGE";
618 return "TEXT_MESSAGE";
620 return "ERROR_MESSAGE";
622 return "REMOTE_LOG";
624 return "ASCII_FRAME";
626 return "IMAGE_FRAME";
628 return "IMAGE_FRAME_H265";
630 return "IMAGE_FRAME_H264";
632 return "AUDIO_BATCH";
634 return "AUDIO_OPUS_BATCH";
636 return "CLIENT_CAPABILITIES";
637 case PACKET_TYPE_PING:
638 return "PING";
639 case PACKET_TYPE_PONG:
640 return "PONG";
642 return "CLIENT_JOIN";
644 return "CLIENT_LEAVE";
646 return "STREAM_START";
648 return "STREAM_STOP";
650 return "CLEAR_CONSOLE";
652 return "SERVER_STATE";
654 return "ACIP_SESSION_CREATE";
656 return "ACIP_SESSION_CREATED";
658 return "ACIP_SESSION_LOOKUP";
660 return "ACIP_SESSION_INFO";
662 return "ACIP_SESSION_JOIN";
664 return "ACIP_SESSION_JOINED";
666 return "ACIP_SESSION_LEAVE";
668 return "ACIP_SESSION_END";
670 return "ACIP_SESSION_RECONNECT";
672 return "ACIP_WEBRTC_SDP";
674 return "ACIP_WEBRTC_ICE";
676 return "ACIP_STRING_RESERVE";
678 return "ACIP_STRING_RESERVED";
680 return "ACIP_STRING_RENEW";
682 return "ACIP_STRING_RELEASE";
684 return "ACIP_PARTICIPANT_LIST";
686 return "ACIP_RING_COLLECT";
688 return "ACIP_NETWORK_QUALITY";
690 return "ACIP_HOST_ANNOUNCEMENT";
692 return "ACIP_HOST_DESIGNATED";
694 return "ACIP_SETTINGS_SYNC";
696 return "ACIP_SETTINGS_ACK";
698 return "ACIP_HOST_LOST";
700 return "ACIP_FUTURE_HOST_ELECTED";
702 return "ACIP_PARTICIPANT_JOINED";
704 return "ACIP_PARTICIPANT_LEFT";
706 return "ACIP_BANDWIDTH_TEST";
708 return "ACIP_BANDWIDTH_RESULT";
710 return "ACIP_BROADCAST_ACK";
712 return "RING_MEMBERS";
714 return "STATS_COLLECTION_START";
716 return "STATS_UPDATE";
718 return "RING_ELECTION_RESULT";
720 return "STATS_ACK";
722 return "ACIP_DISCOVERY_PING";
724 return "ACIP_ERROR";
725 default:
726 return "UNKNOWN";
727 }
728}
729
730asciichat_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) {
731 stats_runtime_packet(transport ? transport->stats_peer : NULL, type, payload_len, false, true);
732 if (!transport || !callbacks) {
733 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport or callbacks");
734 }
735 (void)transport;
736
737 // DEBUG: Log all packet types received
738 log_dev("ACIP_HANDLE: type=%d payload_len=%zu", type, payload_len);
739
740 // O(1) dispatch via hash table lookup
741 int idx = handler_hash_lookup(g_server_handler_hash, type);
742 if (idx < 0) {
743 log_error("ACIP_HANDLER_NOT_FOUND: No handler for packet type=%d (0x%04x, name=%s)", type, type, acip_packet_type_name(type));
744 return SET_ERRNO(ERROR_INVALID_PARAM, "Unhandled server packet type: %d", type);
745 }
746
747 log_dev("HANDLER_DISPATCH: type=%d (%s), handler_idx=%d, payload=%zu bytes", type, acip_packet_type_name(type), idx, payload_len);
748 asciichat_error_t result = g_server_handlers[idx](payload, payload_len, client_ctx, callbacks);
749
750 if (result != ASCIICHAT_OK) {
751 log_error("❌ [HANDLER_ERROR] Handler failed: type=%d (%s), result=%s", type, acip_packet_type_name(type), asciichat_error_format(NULL, result));
752 } else {
753 log_dev("HANDLER_COMPLETE: type=%d (%s), payload=%zu bytes", type, acip_packet_type_name(type), payload_len);
754 }
755
756 return result;
757}
758
759// =============================================================================
760// Server Handler Implementations (extracted from switch cases)
761// =============================================================================
762
763static asciichat_error_t handle_server_image_frame(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
764 log_dev("ACIP_IMAGE_FRAME_HANDLER: payload_len=%zu", payload_len);
765
766 if (!callbacks->on_image_frame) {
767 log_warn("ACIP_IMAGE_FRAME_HANDLER: No callback registered for on_image_frame");
768 return ASCIICHAT_OK;
769 }
770
771 log_dev("ACIP_IMAGE_FRAME_HANDLER: Callback registered (header=%zu)", sizeof(image_frame_packet_t));
772
773 if (payload_len < sizeof(uint32_t) * 2) {
774 log_error("ACIP_IMAGE_FRAME_HANDLER: Payload too small: %zu bytes (need at least 8)", payload_len);
775 return SET_ERRNO(ERROR_INVALID_PARAM, "IMAGE_FRAME payload too small: %zu bytes (need at least 8)", payload_len);
776 }
777
778 // Debug: Log raw payload bytes
779 const uint8_t *payload_bytes = (const uint8_t *)payload;
780 log_dev_every(4500 * US_PER_MS_INT, "IMAGE_FRAME payload (%zu bytes):", payload_len);
782 size_t hex_pos = 0;
783 size_t max_bytes = (payload_len < 48) ? payload_len : 48;
784 for (size_t i = 0; i < max_bytes && hex_pos < sizeof(hex_buf) - 4; i++) {
785 hex_pos += snprintf(hex_buf + hex_pos, sizeof(hex_buf) - hex_pos, "%02x ", payload_bytes[i]);
786 }
787 log_dev_every(4500 * US_PER_MS_INT, " First bytes: %s", hex_buf);
788
789 // Older browser clients send [width:u32][height:u32][RGB24 pixels]. Accept
790 // that exact size alongside the current image_frame_packet_t wire header.
791 uint32_t legacy_width_net;
792 uint32_t legacy_height_net;
793 memcpy(&legacy_width_net, payload_bytes, sizeof(legacy_width_net));
794 memcpy(&legacy_height_net, payload_bytes + sizeof(legacy_width_net), sizeof(legacy_height_net));
795 uint32_t legacy_width = NET_TO_HOST_U32(legacy_width_net);
796 uint32_t legacy_height = NET_TO_HOST_U32(legacy_height_net);
797 size_t legacy_pixels = 0;
798 size_t legacy_rgb_size = 0;
799 size_t legacy_payload_size = 0;
800 if (legacy_width > 0 && legacy_height > 0 && legacy_width <= 8192 && legacy_height <= 8192 && checked_size_mul(legacy_width, legacy_height, &legacy_pixels) == ASCIICHAT_OK &&
801 checked_size_mul(legacy_pixels, 3, &legacy_rgb_size) == ASCIICHAT_OK && checked_size_add(sizeof(uint32_t) * 2, legacy_rgb_size, &legacy_payload_size) == ASCIICHAT_OK &&
802 payload_len == legacy_payload_size) {
803 image_frame_packet_t legacy_header = {0};
804 legacy_header.width = legacy_width;
805 legacy_header.height = legacy_height;
806 legacy_header.pixel_format = 1; // RGB24
807 callbacks->on_image_frame(&legacy_header, payload_bytes + sizeof(uint32_t) * 2, legacy_rgb_size, client_ctx, callbacks->app_ctx);
808 return ASCIICHAT_OK;
809 }
810
811 if (payload_len < sizeof(image_frame_packet_t)) {
812 return SET_ERRNO(ERROR_INVALID_PARAM, "IMAGE_FRAME payload too small: %zu bytes (need %zu)", payload_len, sizeof(image_frame_packet_t));
813 }
814
815 // Extract header
817 memcpy(&header, payload, sizeof(header));
818
819 // Debug: Log raw header before byte order conversion
820 log_dev_every(4500 * US_PER_MS_INT, "IMAGE_FRAME header (raw network order):");
821 log_dev_every(4500 * US_PER_MS_INT, " width=0x%08x height=0x%08x pixel_format=0x%08x compressed_size=0x%08x", header.width, header.height, header.pixel_format, header.compressed_size);
822
823 // Convert from network byte order
824 header.width = NET_TO_HOST_U32(header.width);
825 header.height = NET_TO_HOST_U32(header.height);
826 header.pixel_format = NET_TO_HOST_U32(header.pixel_format);
827 header.compressed_size = NET_TO_HOST_U32(header.compressed_size);
828 header.checksum = NET_TO_HOST_U32(header.checksum);
829 header.timestamp = NET_TO_HOST_U32(header.timestamp);
830
831 // Debug: Log header after byte order conversion
832 log_dev_every(4500 * US_PER_MS_INT, "IMAGE_FRAME header (after host byte order):");
833 log_dev_every(4500 * US_PER_MS_INT, " width=%u height=%u pixel_format=%u compressed_size=%u", header.width, header.height, header.pixel_format, header.compressed_size);
834
835 // Get pixel data (after header)
836 const void *pixel_data = (const uint8_t *)payload + sizeof(image_frame_packet_t);
837 size_t pixel_data_len = payload_len - sizeof(image_frame_packet_t);
838
839 // Validate frame dimensions to prevent DoS and buffer overflow attacks
840 if (header.width == 0 || header.height == 0) {
841 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid image dimensions: %ux%u (width and height must be > 0)", header.width, header.height);
842 }
843
844 // Sanity check: prevent unreasonably large frames (e.g., > 8K resolution for RGB)
845 // This protects against resource exhaustion attacks
846 const uint32_t MAX_WIDTH = 8192; // 8K for RGB data
847 const uint32_t MAX_HEIGHT = 8192; // 8K for RGB data
848 if (header.width > MAX_WIDTH || header.height > MAX_HEIGHT) {
849 return SET_ERRNO(ERROR_INVALID_PARAM, "Image dimensions too large: %ux%u (max: %ux%u)", header.width, header.height, MAX_WIDTH, MAX_HEIGHT);
850 }
851
852 // Validate pixel format
853 // Valid formats: RGB24 (3), RGBA32 (4), YUV420 (1.5)
854 if (header.pixel_format == 0 || header.pixel_format > 4) {
855 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid pixel format: %u (expected: 1-4)", header.pixel_format);
856 }
857
858 log_dev("📹 [IMAGE_FRAME_CALLBACK] Invoking on_image_frame callback: %ux%u pixels, format=%u, %zu bytes, client_ctx=%p", header.width, header.height, header.pixel_format, pixel_data_len,
859 client_ctx);
860
861 callbacks->on_image_frame(&header, pixel_data, pixel_data_len, client_ctx, callbacks->app_ctx);
862
863 log_dev("IMAGE_FRAME_DONE");
864 return ASCIICHAT_OK;
865}
866
867static asciichat_error_t handle_server_encoded_frame(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks, bool h264) {
868 if (!payload || payload_len <= 5)
869 return SET_ERRNO(ERROR_INVALID_PARAM, "Encoded video payload must contain a five-byte header and access unit");
870 const uint8_t *bytes = payload;
871 uint8_t flags = bytes[0];
872 uint16_t width = ((uint16_t)bytes[1] << 8) | bytes[2];
873 uint16_t height = ((uint16_t)bytes[3] << 8) | bytes[4];
874 if (!width || !height || width > 8192 || height > 8192 || (flags & ~3))
875 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid encoded video dimensions or flags");
876 if (h264) {
877 if (callbacks->on_image_frame_h264)
878 callbacks->on_image_frame_h264(width, height, flags, bytes + 5, payload_len - 5, client_ctx, callbacks->app_ctx);
879 } else if (callbacks->on_image_frame_h265) {
880 callbacks->on_image_frame_h265(width, height, flags, bytes + 5, payload_len - 5, client_ctx, callbacks->app_ctx);
881 }
882 return ASCIICHAT_OK;
883}
884
885static asciichat_error_t handle_server_image_frame_h264(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
886 return handle_server_encoded_frame(payload, payload_len, client_ctx, callbacks, true);
887}
888
889static asciichat_error_t handle_server_image_frame_h265(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
890 return handle_server_encoded_frame(payload, payload_len, client_ctx, callbacks, false);
891}
892
893static asciichat_error_t handle_server_audio_batch(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
894 if (!callbacks->on_audio_batch) {
895 return ASCIICHAT_OK;
896 }
897
898 if (payload_len < sizeof(audio_batch_packet_t)) {
899 return SET_ERRNO(ERROR_INVALID_PARAM, "AUDIO_BATCH payload too small");
900 }
901
902 // Parse batch header
903 const audio_batch_packet_t *batch_header = (const audio_batch_packet_t *)payload;
904 uint32_t batch_count = NET_TO_HOST_U32(batch_header->batch_count);
905 uint32_t total_samples = NET_TO_HOST_U32(batch_header->total_samples);
906 uint32_t sample_rate = NET_TO_HOST_U32(batch_header->sample_rate);
907 uint32_t channels = NET_TO_HOST_U32(batch_header->channels);
908
909 // Validate size
910 size_t expected_size = sizeof(audio_batch_packet_t) + (total_samples * sizeof(uint32_t));
911 if (payload_len != expected_size) {
912 return SET_ERRNO(ERROR_INVALID_PARAM, "AUDIO_BATCH size mismatch");
913 }
914
915 // Extract quantized samples
916 const uint8_t *samples_ptr = (const uint8_t *)payload + sizeof(audio_batch_packet_t);
917
918 // Dequantize samples to float
919 float *samples = SAFE_MALLOC(total_samples * sizeof(float), float *);
920 if (!samples) {
921 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate audio batch buffer");
922 }
923
924 asciichat_error_t result = audio_dequantize_samples(samples_ptr, total_samples, samples);
925 if (result != ASCIICHAT_OK) {
926 SAFE_FREE(samples);
927 return result;
928 }
929
930 // Copy header for callback
931 audio_batch_packet_t header_copy = *batch_header;
932 header_copy.batch_count = batch_count;
933 header_copy.total_samples = total_samples;
934 header_copy.sample_rate = sample_rate;
935 header_copy.channels = channels;
936
937 callbacks->on_audio_batch(&header_copy, samples, total_samples, client_ctx, callbacks->app_ctx);
938
939 SAFE_FREE(samples);
940 return ASCIICHAT_OK;
941}
942
943static asciichat_error_t handle_server_audio_opus_batch(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
944 if (!callbacks->on_audio_opus_batch) {
945 return ASCIICHAT_OK;
946 }
947
948 callbacks->on_audio_opus_batch(payload, payload_len, client_ctx, callbacks->app_ctx);
949 return ASCIICHAT_OK;
950}
951
952static asciichat_error_t handle_server_client_join(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
953 if (!callbacks->on_client_join) {
954 return ASCIICHAT_OK;
955 }
956
957 callbacks->on_client_join(payload, payload_len, client_ctx, callbacks->app_ctx);
958 return ASCIICHAT_OK;
959}
960
961static asciichat_error_t handle_server_client_leave(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
962 (void)payload;
963 (void)payload_len;
964
965 if (!callbacks->on_client_leave) {
966 return ASCIICHAT_OK;
967 }
968
969 callbacks->on_client_leave(client_ctx, callbacks->app_ctx);
970 return ASCIICHAT_OK;
971}
972
973static asciichat_error_t handle_server_stream_start(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
974 if (!callbacks->on_stream_start) {
975 return ASCIICHAT_OK;
976 }
977
978 if (payload_len < sizeof(uint32_t)) {
979 return SET_ERRNO(ERROR_INVALID_PARAM, "STREAM_START payload too small (got %zu, expected %zu)", payload_len, sizeof(uint32_t));
980 }
981
982 // Read stream_types as uint32_t (network byte order)
983 uint32_t stream_types_net;
984 memcpy(&stream_types_net, payload, sizeof(uint32_t));
985 uint32_t stream_types = NET_TO_HOST_U32(stream_types_net);
986
987 callbacks->on_stream_start(stream_types, client_ctx, callbacks->app_ctx);
988 return ASCIICHAT_OK;
989}
990
991static asciichat_error_t handle_server_stream_stop(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
992 if (!callbacks->on_stream_stop) {
993 return ASCIICHAT_OK;
994 }
995
996 if (payload_len < sizeof(uint32_t)) {
997 return SET_ERRNO(ERROR_INVALID_PARAM, "STREAM_STOP payload too small (got %zu, expected %zu)", payload_len, sizeof(uint32_t));
998 }
999
1000 // Read stream_types as uint32_t (network byte order)
1001 uint32_t stream_types_net;
1002 memcpy(&stream_types_net, payload, sizeof(uint32_t));
1003 uint32_t stream_types = NET_TO_HOST_U32(stream_types_net);
1004
1005 callbacks->on_stream_stop(stream_types, client_ctx, callbacks->app_ctx);
1006 return ASCIICHAT_OK;
1007}
1008
1009static asciichat_error_t handle_server_capabilities(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1010 log_debug("payload_len=%zu, client_ctx=%p, callbacks=%p", payload_len, client_ctx, (const void *)callbacks);
1011
1012 if (!callbacks->on_capabilities) {
1013 log_error("on_capabilities callback is NULL!");
1014 return ASCIICHAT_OK;
1015 }
1016
1017 log_error("Calling on_capabilities callback...");
1018 callbacks->on_capabilities(payload, payload_len, client_ctx, callbacks->app_ctx);
1019 log_error("on_capabilities callback returned");
1020 return ASCIICHAT_OK;
1021}
1022
1023static asciichat_error_t handle_server_ping(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1024 (void)payload;
1025 (void)payload_len;
1026
1027 if (callbacks->on_ping) {
1028 callbacks->on_ping(client_ctx, callbacks->app_ctx);
1029 }
1030 return ASCIICHAT_OK;
1031}
1032
1033static asciichat_error_t handle_server_remote_log(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1034 if (!callbacks->on_remote_log) {
1035 return ASCIICHAT_OK;
1036 }
1037
1038 if (payload_len < sizeof(remote_log_packet_t)) {
1039 return SET_ERRNO(ERROR_INVALID_PARAM, "REMOTE_LOG payload too small");
1040 }
1041
1042 const remote_log_packet_t *header = (const remote_log_packet_t *)payload;
1043 const char *message = (const char *)payload + sizeof(remote_log_packet_t);
1044 size_t msg_len = payload_len - sizeof(remote_log_packet_t);
1045
1046 // Ensure null-terminated message
1048 size_t copy_len = msg_len < sizeof(msg_buffer) - 1 ? msg_len : sizeof(msg_buffer) - 1;
1049 memcpy(msg_buffer, message, copy_len);
1050 msg_buffer[copy_len] = '\0';
1051
1052 callbacks->on_remote_log(header, msg_buffer, client_ctx, callbacks->app_ctx);
1053 return ASCIICHAT_OK;
1054}
1055
1056static asciichat_error_t handle_server_protocol_version(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1057 if (!callbacks->on_protocol_version) {
1058 return ASCIICHAT_OK;
1059 }
1060
1061 if (payload_len != sizeof(protocol_version_packet_t)) {
1062 return SET_ERRNO(ERROR_INVALID_PARAM, "PROTOCOL_VERSION size mismatch");
1063 }
1064
1065 callbacks->on_protocol_version((const protocol_version_packet_t *)payload, client_ctx, callbacks->app_ctx);
1066 return ASCIICHAT_OK;
1067}
1068
1069static asciichat_error_t handle_server_pong(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1070 (void)payload;
1071 (void)payload_len;
1072
1073 if (callbacks->on_pong) {
1074 callbacks->on_pong(client_ctx, callbacks->app_ctx);
1075 }
1076 return ASCIICHAT_OK;
1077}
1078
1079static asciichat_error_t handle_server_error_message(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1080 if (!callbacks->on_error) {
1081 return ASCIICHAT_OK;
1082 }
1083
1084 if (payload_len < sizeof(error_packet_t)) {
1085 return SET_ERRNO(ERROR_INVALID_PARAM, "ERROR_MESSAGE payload too small");
1086 }
1087
1088 const error_packet_t *header = (const error_packet_t *)payload;
1089 const char *message = (const char *)payload + sizeof(error_packet_t);
1090 size_t msg_len = payload_len - sizeof(error_packet_t);
1091
1092 // Ensure null-terminated message
1093 char msg_buffer[MAX_ERROR_MESSAGE_LENGTH + 1];
1094 size_t copy_len = msg_len < MAX_ERROR_MESSAGE_LENGTH ? msg_len : MAX_ERROR_MESSAGE_LENGTH;
1095 memcpy(msg_buffer, message, copy_len);
1096 msg_buffer[copy_len] = '\0';
1097
1098 callbacks->on_error(header, msg_buffer, client_ctx, callbacks->app_ctx);
1099 return ASCIICHAT_OK;
1100}
1101
1102static asciichat_error_t handle_server_crypto_key_exchange_resp(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1103 if (!callbacks->on_crypto_key_exchange_resp) {
1104 return ASCIICHAT_OK;
1105 }
1106
1107 // Dispatch to application callback with packet type
1108 callbacks->on_crypto_key_exchange_resp(PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP, payload, payload_len, client_ctx, callbacks->app_ctx);
1109 return ASCIICHAT_OK;
1110}
1111
1112static asciichat_error_t handle_server_crypto_auth_response(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1113 if (!callbacks->on_crypto_auth_response) {
1114 return ASCIICHAT_OK;
1115 }
1116
1117 // Dispatch to application callback with packet type
1118 callbacks->on_crypto_auth_response(PACKET_TYPE_CRYPTO_AUTH_RESPONSE, payload, payload_len, client_ctx, callbacks->app_ctx);
1119 return ASCIICHAT_OK;
1120}
1121
1122static asciichat_error_t handle_server_crypto_no_encryption(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks) {
1123 if (!callbacks->on_crypto_no_encryption) {
1124 return ASCIICHAT_OK;
1125 }
1126
1127 // Dispatch to application callback with packet type
1128 callbacks->on_crypto_no_encryption(PACKET_TYPE_CRYPTO_NO_ENCRYPTION, payload, payload_len, client_ctx, callbacks->app_ctx);
1129 return ASCIICHAT_OK;
1130}
ascii-chat Discovery Service (ACDS) Protocol Message Formats
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U32(val)
Definition endian.h:85
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
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 short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
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
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
acip_session_joined_t
Definition acds.h:479
acip_webrtc_ice_t
Definition acds.h:655
acip_webrtc_sdp_t
Definition acds.h:609
#define US_PER_MS_INT
Definition time.h:176
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
#define MAX_ERROR_MESSAGE_LENGTH
Maximum error message length (512 bytes).
Definition packet.h:153
@ PACKET_TYPE_CRYPTO_CLIENT_HELLO
Client -> Server: Expected server key fingerprint for multi-key selection (UNENCRYPTED).
Definition packet.h:328
@ PACKET_TYPE_ACIP_WEBRTC_ICE
WebRTC ICE candidate (bidirectional).
Definition packet.h:466
@ PACKET_TYPE_AUDIO_OPUS_BATCH
Batched Opus-encoded audio frames.
Definition packet.h:412
@ PACKET_TYPE_ACIP_PARTICIPANT_JOINED
Participant joined notification (ACDS -> Existing Participants).
Definition packet.h:507
@ PACKET_TYPE_CLIENT_LEAVE
Clean disconnect notification.
Definition packet.h:427
@ PACKET_TYPE_ACIP_SESSION_INFO
Session info response (Discovery Server -> Client).
Definition packet.h:451
@ PACKET_TYPE_IMAGE_FRAME
Complete RGB image with dimensions.
Definition packet.h:399
@ PACKET_TYPE_CRYPTO_AUTH_RESPONSE
Client -> Server: {HMAC[32]} (UNENCRYPTED).
Definition packet.h:346
@ PACKET_TYPE_TEXT_MESSAGE
Text message.
Definition packet.h:386
@ PACKET_TYPE_AUDIO_MESSAGE
Audio message.
Definition packet.h:384
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_ACIP_SESSION_RECONNECT
Reconnect to session (Client -> Discovery Server).
Definition packet.h:461
@ PACKET_TYPE_CRYPTO_HANDSHAKE_COMPLETE
Server -> Client: "encryption ready" (UNENCRYPTED).
Definition packet.h:352
@ PACKET_TYPE_ACIP_PARTICIPANT_LIST
Participant list with ring order (ACDS -> Participants).
Definition packet.h:483
@ PACKET_TYPE_STREAM_START
Client requests to start sending video/audio.
Definition packet.h:429
@ PACKET_TYPE_ACIP_SETTINGS_SYNC
Settings sync (Initiator -> Host -> All Participants).
Definition packet.h:499
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_INIT
Server -> Client: {server_pubkey[32]} (UNENCRYPTED).
Definition packet.h:340
@ PACKET_TYPE_ACIP_ERROR
Generic error response (Discovery Server -> Client).
Definition packet.h:547
@ PACKET_TYPE_CRYPTO_KEY_EXCHANGE_RESP
Client -> Server: {client_pubkey[32]} (UNENCRYPTED).
Definition packet.h:342
@ PACKET_TYPE_CRYPTO_REKEY_COMPLETE
Initiator -> Responder: Empty (encrypted with NEW key, but still handshake).
Definition packet.h:375
@ PACKET_TYPE_ACIP_NETWORK_QUALITY
NETWORK_QUALITY exchange (unified packet for all quality metrics).
Definition packet.h:493
@ PACKET_TYPE_SERVER_STATE
Server sends current state to clients.
Definition packet.h:435
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
@ PACKET_TYPE_ACIP_BROADCAST_ACK
Broadcast acknowledgment for reliable delivery.
Definition packet.h:522
@ PACKET_TYPE_ACIP_HOST_DESIGNATED
Host designated (ACDS -> All Participants).
Definition packet.h:497
@ PACKET_TYPE_ACIP_STRING_RESERVE
Reserve session string (Client -> Discovery Server).
Definition packet.h:469
@ PACKET_TYPE_CRYPTO_AUTH_FAILED
Server -> Client: "authentication failed" (UNENCRYPTED).
Definition packet.h:348
@ PACKET_TYPE_ENCRYPTED
Encrypted packet (after handshake completion).
Definition packet.h:369
@ PACKET_TYPE_CRYPTO_REKEY_REQUEST
Initiator -> Responder: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:371
@ PACKET_TYPE_SIZE_MESSAGE
Terminal size message.
Definition packet.h:382
@ PACKET_TYPE_REMOTE_LOG
Bidirectional remote logging packet.
Definition packet.h:390
@ PACKET_TYPE_CRYPTO_SERVER_AUTH_RESP
Server -> Client: {HMAC[32]} server proves knowledge (UNENCRYPTED).
Definition packet.h:350
@ PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT
Host announcement (Participant -> ACDS, "I won negotiation").
Definition packet.h:495
@ PACKET_TYPE_PROTOCOL_VERSION
Protocol version and capabilities negotiation.
Definition packet.h:317
@ PACKET_TYPE_ACIP_SETTINGS_ACK
Settings acknowledgment (Participant -> Initiator).
Definition packet.h:501
@ PACKET_TYPE_ACIP_BANDWIDTH_TEST
Bandwidth test request (Client -> ACDS).
Definition packet.h:517
@ PACKET_TYPE_CLEAR_CONSOLE
Server tells client to clear console.
Definition packet.h:433
@ PACKET_TYPE_CRYPTO_NO_ENCRYPTION
Client -> Server: "I want to proceed without encryption" (UNENCRYPTED).
Definition packet.h:354
@ PACKET_TYPE_ACIP_SESSION_CREATE
Create new session (Client -> Discovery Server).
Definition packet.h:445
@ PACKET_TYPE_STATS_UPDATE
Statistics update during collection phase (Participant -> Next Participant).
Definition packet.h:534
@ PACKET_TYPE_ACIP_STRING_RESERVED
String reserved response (Discovery Server -> Client).
Definition packet.h:471
@ PACKET_TYPE_IMAGE_FRAME_H265
H.265-encoded frame from client (HEVC/H.265 codec).
Definition packet.h:401
@ PACKET_TYPE_ACIP_DISCOVERY_PING
Discovery server ping (keepalive).
Definition packet.h:545
@ PACKET_TYPE_CRYPTO_AUTH_CHALLENGE
Server -> Client: {nonce[32]} (UNENCRYPTED).
Definition packet.h:344
@ PACKET_TYPE_ASCII_FRAME
Complete ASCII frame with all metadata.
Definition packet.h:397
@ PACKET_TYPE_CRYPTO_PARAMETERS
Server -> Client: Chosen algorithms + data sizes (UNENCRYPTED).
Definition packet.h:338
@ PACKET_TYPE_ACIP_SESSION_LOOKUP
Lookup session by string (Client -> Discovery Server).
Definition packet.h:449
@ PACKET_TYPE_CRYPTO_CAPABILITIES
Client -> Server: Supported crypto algorithms (UNENCRYPTED).
Definition packet.h:336
@ PACKET_TYPE_RING_ELECTION_RESULT
Final election result (Quorum Leader -> All Participants).
Definition packet.h:536
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ PACKET_TYPE_ACIP_PARTICIPANT_LEFT
Participant left notification (ACDS -> Remaining Participants).
Definition packet.h:509
@ PACKET_TYPE_ACIP_WEBRTC_SDP
WebRTC SDP offer/answer (bidirectional).
Definition packet.h:464
@ PACKET_TYPE_ACIP_SESSION_JOIN
Join existing session (Client -> Discovery Server).
Definition packet.h:453
@ PACKET_TYPE_ACIP_SESSION_CREATED
Session created response (Discovery Server -> Client).
Definition packet.h:447
@ PACKET_TYPE_STATS_ACK
Acknowledgment of statistics update (Participant -> Sender).
Definition packet.h:538
@ PACKET_TYPE_ACIP_STRING_RELEASE
Release string reservation (Client -> Discovery Server).
Definition packet.h:475
@ PACKET_TYPE_CLIENT_JOIN
Client announces capability to send media.
Definition packet.h:425
@ PACKET_TYPE_CLIENT_CAPABILITIES
Client reports terminal capabilities.
Definition packet.h:419
@ PACKET_TYPE_ACIP_FUTURE_HOST_ELECTED
Future host elected announcement (Quorum Leader -> ACDS -> All Participants).
Definition packet.h:505
@ PACKET_TYPE_IMAGE_FRAME_H264
Definition packet.h:403
@ PACKET_TYPE_ACIP_BANDWIDTH_RESULT
Bandwidth test results (ACDS -> Client).
Definition packet.h:519
@ PACKET_TYPE_ACIP_STRING_RENEW
Renew string reservation (Client -> Discovery Server).
Definition packet.h:473
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
@ PACKET_TYPE_RING_MEMBERS
Ring member list announcement (ACDS -> All Participants).
Definition packet.h:530
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_AUDIO_BATCH
Batched audio packets for efficiency.
Definition packet.h:410
@ PACKET_TYPE_CRYPTO_REKEY_RESPONSE
Responder -> Initiator: {new_ephemeral_pk[32]} (UNENCRYPTED during rekey).
Definition packet.h:373
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
@ PACKET_TYPE_STATS_COLLECTION_START
Start statistics collection phase (Coordinator -> All Participants).
Definition packet.h:532
@ PACKET_TYPE_STREAM_STOP
Client stops sending media.
Definition packet.h:431
@ PACKET_TYPE_ACIP_RING_COLLECT
Ring collect request (Participant -> Next Participant).
Definition packet.h:485
@ PACKET_TYPE_ACIP_SESSION_END
End session (Host -> Discovery Server).
Definition packet.h:459
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
const char * acip_packet_type_name(uint16_t type)
Get human-readable name for packet type.
Definition handlers.c:579
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
#define NETWORK_ACIP_HANDLERS_HEX_BUFFER_SIZE
Definition handlers.c:15
#define NETWORK_ACIP_HANDLERS_MSG_BUFFER_SIZE
Definition handlers.c:14
asciichat_error_t acip_handle_client_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks)
Client-side packet handler callbacks.
Definition handlers.c:182
asciichat_error_t(* acip_client_handler_func_t)(const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks)
Definition handlers.c:34
#define HANDLER_HASH(type)
Definition handlers.c:58
asciichat_error_t(* acip_server_handler_func_t)(const void *payload, size_t payload_len, void *client_ctx, const acip_server_callbacks_t *callbacks)
Definition handlers.c:36
#define CLIENT_HANDLER_COUNT
Definition handlers.c:45
#define HANDLER_HASH_SIZE
Definition handlers.c:44
#define SERVER_HANDLER_COUNT
Definition handlers.c:46
ACIP protocol packet handlers (transport-agnostic).
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
#define log_debug_once(fmt,...)
Log DEBUG message exactly once.
Definition log/log.h:850
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:716
ACIP protocol message structures and helpers.
✅ Safe Integer Arithmetic and Overflow Detection
void stats_runtime_packet(stats_peer_t *peer, unsigned type, size_t payload_bytes, bool sent, bool success)
Definition runtime.c:205
🔤 String Manipulation and Shell Escaping Utilities
Client-side packet handler callbacks.
Definition handlers.h:55
void(* on_clear_console)(void *ctx)
Called when server requests console clear.
Definition handlers.h:87
void(* on_session_joined)(const acip_session_joined_t *joined, void *ctx)
Called when ACDS session join response received (Phase 3 WebRTC integration).
Definition handlers.h:96
void(* on_webrtc_sdp)(const acip_webrtc_sdp_t *sdp, size_t total_len, void *ctx)
Called when WebRTC SDP offer/answer received.
Definition handlers.h:90
void(* on_error)(const error_packet_t *header, const char *message, void *ctx)
Called when error message received.
Definition handlers.h:75
void(* on_crypto_parameters)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends CRYPTO_PARAMETERS (algorithm negotiation).
Definition handlers.h:99
void(* on_crypto_handshake_complete)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends HANDSHAKE_COMPLETE (crypto handshake success).
Definition handlers.h:114
void(* on_crypto_auth_challenge)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends AUTH_CHALLENGE (crypto handshake).
Definition handlers.h:105
void(* on_audio_opus_batch)(const void *batch_data, size_t batch_len, void *ctx)
Called when Opus batch received from server.
Definition handlers.h:69
void(* on_ping)(void *ctx)
Called when ping received (should send pong).
Definition handlers.h:81
void(* on_crypto_key_exchange_init)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends KEY_EXCHANGE_INIT (crypto handshake).
Definition handlers.h:102
void(* on_pong)(void *ctx)
Called when pong received.
Definition handlers.h:84
void(* on_audio_batch)(const audio_batch_packet_t *header, const float *samples, size_t num_samples, void *ctx)
Called when audio batch received from server.
Definition handlers.h:63
void(* on_webrtc_ice)(const acip_webrtc_ice_t *ice, size_t total_len, void *ctx)
Called when WebRTC ICE candidate received.
Definition handlers.h:93
void(* on_remote_log)(const remote_log_packet_t *header, const char *message, void *ctx)
Called when remote log received.
Definition handlers.h:78
void(* on_ascii_frame)(const ascii_frame_packet_t *header, const void *frame_data, size_t data_len, void *ctx)
Called when ASCII frame received from server.
Definition handlers.h:57
void(* on_crypto_server_auth_resp)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends SERVER_AUTH_RESP (crypto handshake mutual auth).
Definition handlers.h:108
void * app_ctx
Application context (passed to all callbacks).
Definition handlers.h:117
void(* on_server_state)(const server_state_packet_t *state, void *ctx)
Called when server state update received.
Definition handlers.h:72
void(* on_crypto_auth_failed)(packet_type_t type, const void *payload, size_t payload_len, void *ctx)
Called when server sends AUTH_FAILED (crypto handshake failure).
Definition handlers.h:111
Server-side packet handler callbacks.
Definition handlers.h:147
void(* on_image_frame)(const image_frame_packet_t *header, const void *pixel_data, size_t data_len, void *client_ctx, void *app_ctx)
Called when client sends image frame.
Definition handlers.h:152
void(* on_crypto_auth_response)(packet_type_t type, const void *payload, size_t payload_len, void *client_ctx, void *app_ctx)
Called when client sends AUTH_RESPONSE (crypto handshake).
Definition handlers.h:202
void(* on_capabilities)(const void *cap_data, size_t data_len, void *client_ctx, void *app_ctx)
Called when client sends capabilities.
Definition handlers.h:184
void(* on_pong)(void *client_ctx, void *app_ctx)
Called when pong received from client.
Definition handlers.h:190
void * app_ctx
Application context (passed to all callbacks).
Definition handlers.h:208
void(* on_image_frame_h265)(uint32_t width, uint32_t height, uint8_t flags, const void *h265_data, size_t data_len, void *client_ctx, void *app_ctx)
Called when client sends H.265-encoded image frame.
Definition handlers.h:157
void(* on_image_frame_h264)(uint32_t width, uint32_t height, uint8_t flags, const void *data, size_t data_len, void *client_ctx, void *app_ctx)
Called when client sends H.264-encoded image frame.
Definition handlers.h:155
void(* on_stream_start)(uint32_t stream_types, void *client_ctx, void *app_ctx)
Called when client starts streaming.
Definition handlers.h:178
void(* on_crypto_no_encryption)(packet_type_t type, const void *payload, size_t payload_len, void *client_ctx, void *app_ctx)
Called when client sends NO_ENCRYPTION (crypto handshake rejection).
Definition handlers.h:205
void(* on_ping)(void *client_ctx, void *app_ctx)
Called when ping received (should send pong).
Definition handlers.h:187
void(* on_stream_stop)(uint32_t stream_types, void *client_ctx, void *app_ctx)
Called when client stops streaming.
Definition handlers.h:181
void(* on_client_leave)(void *client_ctx, void *app_ctx)
Called when client leaves.
Definition handlers.h:175
void(* on_remote_log)(const remote_log_packet_t *header, const char *message, void *client_ctx, void *app_ctx)
Called when remote log received from client.
Definition handlers.h:196
void(* on_error)(const error_packet_t *header, const char *message, void *client_ctx, void *app_ctx)
Called when error message received from client.
Definition handlers.h:193
void(* on_client_join)(const void *join_data, size_t data_len, void *client_ctx, void *app_ctx)
Called when client joins.
Definition handlers.h:172
void(* on_audio_opus_batch)(const void *batch_data, size_t batch_len, void *client_ctx, void *app_ctx)
Called when client sends Opus batch.
Definition handlers.h:169
void(* on_audio_batch)(const audio_batch_packet_t *header, const float *samples, size_t num_samples, void *client_ctx, void *app_ctx)
Called when client sends audio batch.
Definition handlers.h:163
void(* on_protocol_version)(const protocol_version_packet_t *version, void *client_ctx, void *app_ctx)
Called when client sends protocol version.
Definition handlers.h:149
void(* on_crypto_key_exchange_resp)(packet_type_t type, const void *payload, size_t payload_len, void *client_ctx, void *app_ctx)
Called when client sends KEY_EXCHANGE_RESP (crypto handshake).
Definition handlers.h:199
stats_peer_t * stats_peer
Owned statistics handle, destroyed with transport.
The wire metadata for one rendered ASCII frame. width and height describe the terminal grid,...
Definition packet.h:920
The metadata prefix for a batch of encoded audio samples. batch_count, total_samples,...
Definition packet.h:983
uint32_t channels
Number of audio channels (1=mono, 2=stereo).
Definition packet.h:991
uint32_t batch_count
Number of audio chunks in this batch (usually AUDIO_BATCH_COUNT = 32).
Definition packet.h:985
uint32_t sample_rate
Sample rate in Hz (e.g., 44100, 48000).
Definition packet.h:989
uint32_t total_samples
Total audio samples across all chunks (typically 8192).
Definition packet.h:987
Error packet structure carrying error code and textual description.
Definition packet.h:778
Hash table entry for packet type to handler mapping.
Definition handlers.c:52
uint8_t handler_idx
Handler index (0-based).
Definition handlers.c:54
packet_type_t key
Packet type (0 = empty slot).
Definition handlers.c:53
Describes one compressed image sent through ACIP. width, height, and pixel_format tell the decoder ho...
Definition packet.h:952
uint32_t pixel_format
Pixel format enum (1=RGB24, 2=RGBA32, 3=BGR24, 4=BGRA32).
Definition packet.h:958
uint32_t height
Image height in pixels.
Definition packet.h:956
uint32_t width
Image width in pixels.
Definition packet.h:954
Protocol version negotiation packet structure (Packet Type 1).
Definition packet.h:871
Remote log packet structure carrying log level and message text.
Definition packet.h:792
Server state packet structure.
Definition packet.h:757