ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
participant.c
Go to the documentation of this file.
1#define SESSION_PARTICIPANT_WEBCAM_INDEX_BUFFER_SIZE 32
4#include <sodium.h>
17
18#include "session/participant.h"
19#include "session/connection.h"
20#include <ascii-chat/common.h>
22#include <options/options.h>
25#include <libplatform/thread.h>
26#include <ascii-chat/log/log.h>
27#include "session/capture.h"
28#include "session/audio.h"
29#include "session/av_state.h"
39
40#include <string.h>
41#include <stdio.h>
42
43/* ============================================================================
44 * Session Participant Context Structure
45 * ============================================================================ */
46
142
143/* ============================================================================
144 * Session Participant Lifecycle Functions
145 * ============================================================================ */
146
147static void participant_interrupt(void *context);
148static asciichat_error_t participant_join(void *context);
149static void participant_release(void *context);
150
151static void participant_connection_init(session_participant_t *p) {
152 session_connection_init(&p->connection, (session_connection_ops_t){participant_interrupt, participant_join, participant_release}, p);
153}
154
156 log_info("config=%p", config);
157
158 if (!config) {
159 log_error("config is NULL");
160 SET_ERRNO(ERROR_INVALID_PARAM, "NULL config");
161 return NULL;
162 }
163
164 // Allocate participant
166 log_info("allocated p=%p", p);
167
168 // Copy configuration
169 if (config->address) {
170 SAFE_STRNCPY(p->address, config->address, sizeof(p->address));
171 } else {
172 SAFE_STRNCPY(p->address, "127.0.0.1", sizeof(p->address));
173 }
174
175 p->port = config->port > 0 ? config->port : OPT_PORT_INT_DEFAULT;
177
178 log_info("address=%s, port=%d", p->address, p->port);
179
180 if (config->password) {
181 SAFE_STRNCPY(p->password, config->password, sizeof(p->password));
182 }
183
184 if (config->server_key) {
185 SAFE_STRNCPY(p->server_key, config->server_key, sizeof(p->server_key));
186 }
187 if (config->tls_ca_file)
188 SAFE_STRNCPY(p->tls_ca_file, config->tls_ca_file, sizeof(p->tls_ca_file));
191
192 p->enable_audio = config->enable_audio;
193 p->enable_video = config->enable_video;
194 p->callbacks = config->callbacks;
195 p->user_data = config->user_data;
196
197 p->transport = NULL;
198 p->connected = false;
199 p->client_id = 0;
200
201 // Initialize settings
203 if (mutex_init(&p->settings_mutex, "participant_settings") != 0) {
204 SAFE_FREE(p);
205 return NULL;
206 }
207
208 participant_connection_init(p);
209 p->initialized = true;
210 log_info("returning p=%p (initialized=%d, connected=%d)", p, p->initialized, p->connected);
211 return p;
212}
213
215 if (!p) {
216 return;
217 }
218
220 // A failed join retains the participant and its resources for a safe retry.
222 return;
223
224 // Clear sensitive data
225 sodium_memzero(p->password, sizeof(p->password));
226 memset(p->server_key, 0, sizeof(p->server_key));
227
228 p->initialized = false;
229 mutex_destroy(&p->settings_mutex);
230 SAFE_FREE(p);
231}
232
233/* ============================================================================
234 * Session Participant Connection Functions
235 * ============================================================================ */
236
237static asciichat_error_t participant_prepare(network_connection_t *network, const connection_endpoint_t *endpoint, const char *password, void *context) {
238 (void)endpoint;
239 session_participant_t *p = context;
240 asciichat_error_t result = network_connection_prepare_security(network, false, password);
241 if (result == ASCIICHAT_OK && p->server_key[0]) {
243 ctx->verify_server_key = true;
245 }
246 return result;
247}
248
250 log_debug("p=%p", p);
251
252 if (!p || !p->initialized) {
253 log_debug("invalid param or not initialized");
254 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid participant");
255 }
256
257 log_debug("p->initialized=%d, p->connected=%d", p->initialized, p->connected);
258
259 if (p->connected) {
260 log_debug("already connected, returning OK");
261 return ASCIICHAT_OK; // Already connected
262 }
263 if (p->port > UINT16_MAX)
264 return SET_ERRNO(ERROR_INVALID_PARAM, "Participant port is outside the transport endpoint range");
265
267 if (result != ASCIICHAT_OK)
268 return result;
269 participant_connection_init(p);
270 char password[PASSWORD_BUFFER_SIZE] = {0};
271 SAFE_STRNCPY(password, p->password, sizeof(password));
272 network_connect_config_t quic_config = {
273 .timeout_ms = 10000, .tls_ca_file = p->tls_ca_file[0] ? p->tls_ca_file : NULL, .quic_audio_datagrams = p->quic_audio_datagrams, .quic_visual_datagrams = p->quic_visual_datagrams};
274 const network_connect_config_t *connect_config = strncmp(p->address, "quic://", 7) == 0 ? &quic_config : NULL;
275 result = session_connection_establish("participant", p->address, p->port, connect_config, &p->network, password, sizeof(password), participant_prepare, NULL, p);
276 sodium_memzero(password, sizeof(password));
279 if (result == ASCIICHAT_OK)
281 if (result != ASCIICHAT_OK) {
285 return result;
286 }
287 log_debug("session_participant_connect: setting p->connected=true");
288
289 mutex_lock(&p->settings_mutex);
290 p->settings_request = 0;
292 p->settings.version = 0;
293 mutex_unlock(&p->settings_mutex);
294 p->connected = true;
295 p->client_id = 0; // Will be assigned by server
296
297 log_info("Connected to server at %s:%d", p->address, p->port);
298
299 // Invoke callback
300 if (p->callbacks.on_connected) {
302 }
303
304 return ASCIICHAT_OK;
305}
306
308 if (!p || !p->initialized) {
309 return;
310 }
311
312 bool was_connected = p->connected;
314 return;
315
316 // Invoke callback
317 if (was_connected && p->callbacks.on_disconnected) {
319 }
320}
321
322static void participant_interrupt(void *context) {
323 session_participant_t *p = context;
327}
328
329static asciichat_error_t participant_join(void *context) {
330 session_participant_t *p = context;
334 return SET_ERRNO(ERROR_THREAD, "Participant workers still own connection resources");
335 return ASCIICHAT_OK;
336}
337
338static void participant_release(void *context) {
339 session_participant_t *p = context;
341 p->transport = NULL;
343 p->connected = false;
344 p->client_id = 0;
345}
346
348 if (!p || !p->initialized) {
349 return false;
350 }
351 return p->connected;
352}
353
355 if (!p || !p->initialized || !p->connected) {
356 return 0;
357 }
358 return p->client_id;
359}
360
361/* ============================================================================
362 * Session Participant Media Control Functions
363 * ============================================================================ */
364
368
372
373/* ============================================================================
374 * Session Participant Settings Functions
375 * ============================================================================ */
376
378 if (!p || !p->initialized || !settings) {
379 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
380 }
381
382 mutex_lock(&p->settings_mutex);
383 memcpy(settings, &p->settings, sizeof(session_settings_t));
384 mutex_unlock(&p->settings_mutex);
385 return ASCIICHAT_OK;
386}
387
389 if (!p || !p->initialized || !settings) {
390 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
391 }
392
393 if (!p->connected) {
394 return SET_ERRNO(ERROR_INVALID_STATE, "not connected");
395 }
396
397 options_t *values = SAFE_MALLOC(sizeof(*values), options_t *);
398 session_settings_to_options(settings, values);
399 if (values->fps == 0)
400 values->fps = DEFAULT_MAX_FPS;
401 if (values->color_mode == TERM_COLOR_AUTO) {
402 terminal_capabilities_t caps = detect_terminal_capabilities(options_terminal_settings());
403 values->color_mode = caps.detection_reliable ? caps.color_level : TERM_COLOR_NONE;
404 }
405 acip_render_settings_t prepared = {0};
406 asciichat_error_t result = acip_render_settings_prepare(&prepared, values);
407 if (result == ASCIICHAT_OK) {
408 mutex_lock(&p->settings_mutex);
409 uint32_t request = ++p->settings_request;
410 mutex_unlock(&p->settings_mutex);
411 result = acip_settings_send(p->transport, values, request, UINT32_MAX);
412 }
413 SAFE_FREE(values);
414 return result;
415}
416
417/* ============================================================================
418 * Session Participant Media Capture Threads
419 * ============================================================================ */
420
428static void *participant_video_capture_thread(void *arg) {
430 if (!p || !p->video_capture) {
431 SET_ERRNO(ERROR_INVALID_PARAM, "invalid participant or video_capture context");
432 return NULL;
433 }
434
435 log_info("Video capture thread started");
436
438 // Capture frame from media source (webcam, file, test pattern)
440 if (!raw_frame) {
441 APP_CALLBACK_VOID(platform_pump_events);
442 platform_sleep_ms(1);
443 continue;
444 }
445
446 // Process for network transmission (resize to bandwidth-optimal dimensions)
448 if (processed) {
449 // Send to host via IMAGE_FRAME packet
450 asciichat_error_t err = acip_send_image_frame(p->transport, processed->pixels, processed->w, processed->h, 0);
451 if (err != ASCIICHAT_OK) {
452 log_warn_every(5 * US_PER_SEC_INT, "Failed to send video frame: %d", err);
453 }
454 if (err == ASCIICHAT_OK)
456 image_destroy(processed);
457 }
458
459 // Sleep to maintain target frame rate (adaptive based on source)
461 }
462
463 log_info("Video capture thread stopped");
464 return NULL;
465}
466
474static void *participant_audio_capture_thread(void *arg) {
476 if (!p || !p->audio_capture || !p->opus_encoder) {
477 SET_ERRNO(ERROR_INVALID_PARAM, "invalid participant, audio_capture, or opus_encoder");
478 return NULL;
479 }
480
481 log_info("Audio capture thread started");
482
483 float sample_buffer[(OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)]; // 20ms @ 48kHz
485 size_t collected = 0;
486
488 // Read microphone samples (20ms chunk)
489 size_t samples_read = session_audio_read_captured(p->audio_capture, sample_buffer + collected, OPUS_FRAME_SAMPLES * AUDIO_CHANNELS - collected);
490 if (samples_read <= 0) {
491 APP_CALLBACK_VOID(platform_pump_events);
492 platform_sleep_ms(1);
493 continue;
494 }
495 collected += samples_read;
496 if (collected < OPUS_FRAME_SAMPLES * AUDIO_CHANNELS)
497 continue;
498
499 // Encode to Opus (lossy compression for bandwidth efficiency)
500 float mono[OPUS_FRAME_SAMPLES];
501 const float *pcm = sample_buffer;
502 int samples = (int)collected;
503 if (p->opus_encoder->channels == 1) {
504 (void)audio_convert_channels(sample_buffer, OPUS_FRAME_SAMPLES, AUDIO_CHANNELS, mono, 1);
505 pcm = mono;
506 samples = OPUS_FRAME_SAMPLES;
507 }
508 size_t opus_len = opus_codec_encode(p->opus_encoder, pcm, samples, opus_buffer, sizeof(opus_buffer));
509 collected = 0;
510 if (opus_len > 0) {
511 uint16_t frame_sizes[1] = {(uint16_t)opus_len};
513 if (err != ASCIICHAT_OK) {
514 log_warn_every(5 * US_PER_SEC_INT, "Failed to send audio packet: %d", err);
515 }
516 }
517 }
518
519 log_info("Audio capture thread stopped");
520 return NULL;
521}
522
523/* ============================================================================
524 * Session Participant Media Capture Public API
525 * ============================================================================ */
526
527static asciichat_error_t participant_startup_error(asciichat_errno_scope_t checkpoint, const char *message) {
529 asciichat_error_t code = errno_peek_since(checkpoint, &cause) ? cause.code : ERROR_INVALID_STATE;
530 return SET_ERRNO(code, "%s", message);
531}
532
534 if (!p || !p->initialized) {
535 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid participant");
536 }
537
538 if (!p->connected) {
539 return SET_ERRNO(ERROR_INVALID_STATE, "not connected");
540 }
541
542 if (!p->enable_video) {
543 return SET_ERRNO(ERROR_INVALID_STATE, "video not enabled");
544 }
545
547 return ASCIICHAT_OK;
548 uint32_t generation = session_av_state_begin(&p->video);
549 if (!generation)
550 return SET_ERRNO(ERROR_INVALID_STATE, "video is starting or stopping");
551
552 // Create video capture context if not already created
553 if (!p->video_capture) {
554 session_capture_config_t config = {
555 .type = MEDIA_SOURCE_WEBCAM,
556 .path = "0", // Default device
557 .target_fps = (uint32_t)GET_OPTION(fps),
558 .resize_for_network = true, // Optimize for bandwidth
559 };
560 const char *file = GET_OPTION(media_file);
561 const char *url = GET_OPTION(media_url);
563 safe_snprintf(webcam_index, sizeof(webcam_index), "%u", GET_OPTION(webcam_index));
564 config.path = webcam_index;
565 if (url && url[0]) {
566 config.type = MEDIA_SOURCE_FILE;
567 config.path = url;
568 } else if (file && file[0]) {
569 config.type = strcmp(file, "-") == 0 ? MEDIA_SOURCE_STDIN : MEDIA_SOURCE_FILE;
570 config.path = config.type == MEDIA_SOURCE_STDIN ? NULL : file;
571 }
572 config.loop = GET_OPTION(media_loop);
575 if (!p->video_capture) {
576 asciichat_error_t error = participant_startup_error(checkpoint, "Failed to create video capture context");
578 return error;
579 }
580 }
581
582 // Spawn video capture thread (media source is ready in ctx)
583 if (platform_thread_create(&p->video_capture_thread, "video_capture", participant_video_capture_thread, p) != 0) {
584 log_error("Failed to spawn video capture thread");
586 return SET_ERRNO(ERROR_THREAD, "Failed to spawn video capture thread");
587 }
588
589 p->video_thread_created = true;
590 session_av_state_complete(&p->video, generation);
591 log_info("Video capture started");
592 return ASCIICHAT_OK;
593}
594
596 if (!p || !p->initialized)
597 return;
598 if (p->audio_uses_video)
601 return;
603 if (p->video_thread_created) {
604 if (thread_join(&p->video_capture_thread, NULL) != 0) {
605 log_error("Failed to join video capture worker; retaining its resources");
606 return;
607 }
608 p->video_thread_created = false;
609 }
610 if (p->video_capture) {
612 p->video_capture = NULL;
613 }
615}
616
618 if (!p || !p->initialized) {
619 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid participant");
620 }
621
622 if (!p->connected) {
623 return SET_ERRNO(ERROR_INVALID_STATE, "not connected");
624 }
625
626 if (!p->enable_audio) {
627 return SET_ERRNO(ERROR_INVALID_STATE, "audio not enabled");
628 }
629
631 return ASCIICHAT_OK;
632 uint32_t generation = session_av_state_begin(&p->audio);
633 if (!generation)
634 return SET_ERRNO(ERROR_INVALID_STATE, "audio is starting or stopping");
635
636 // Create audio capture context if not already created
637 if (!p->audio_capture) {
639 p->audio_capture = session_audio_create(false); // false = participant mode (no mixing)
640 if (!p->audio_capture) {
641 asciichat_error_t error = participant_startup_error(checkpoint, "Failed to create audio capture context");
643 return error;
644 }
645 }
646
648 p->audio_uses_video = source != NULL;
651
652 // Start audio capture and playback
654 if (err != ASCIICHAT_OK) {
656 return SET_ERRNO(err, "Failed to start audio duplex");
657 }
658
659 // Create Opus encoder for audio compression (48kHz, VOIP mode, 24 kbps)
660 if (!p->opus_encoder) {
664 if (!p->opus_encoder) {
665 asciichat_error_t error = participant_startup_error(checkpoint, "Failed to create Opus encoder");
667 return error;
668 }
669 }
670
671 // Spawn audio capture thread
672 if (platform_thread_create(&p->audio_capture_thread, "audio_capture", participant_audio_capture_thread, p) != 0) {
673 log_error("Failed to spawn audio capture thread");
675 return SET_ERRNO(ERROR_THREAD, "Failed to spawn audio capture thread");
676 }
677
678 p->audio_thread_created = true;
679 session_av_state_complete(&p->audio, generation);
680 log_info("Audio capture started");
681 return ASCIICHAT_OK;
682}
683
685 if (!p || !p->initialized)
686 return;
688 if (p->audio_thread_created) {
689 if (thread_join(&p->audio_capture_thread, NULL) != 0) {
690 log_error("Failed to join audio capture worker; retaining its resources");
691 return;
692 }
693 p->audio_thread_created = false;
694 }
695 if (p->audio_capture) {
698 p->audio_capture = NULL;
699 }
700 if (p->opus_encoder) {
702 p->opus_encoder = NULL;
703 }
704 p->audio_uses_video = false;
706}
707
708/* ============================================================================
709 * Session Participant Transport Functions (WebRTC Integration)
710 * ============================================================================ */
711
713 if (!p || !p->initialized) {
714 return SET_ERRNO(ERROR_INVALID_PARAM, "Participant is NULL or not initialized");
715 }
716
718 return SET_ERRNO(ERROR_INVALID_STATE, "Stop media before replacing its transport");
719
720 log_info("Setting transport=%p (was=%p)", transport, p->transport);
721
722 if (ownership != ACIP_TRANSPORT_BORROWED && ownership != ACIP_TRANSPORT_OWNED)
723 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport ownership");
724 if (transport && transport == p->transport) {
725 if (ownership != p->transport_ownership)
726 return SET_ERRNO(ERROR_INVALID_STATE, "Detach before transferring transport ownership");
727 return ASCIICHAT_OK;
728 }
730 if (result != ASCIICHAT_OK)
731 return result;
732 participant_connection_init(p);
733 if (transport && ownership == ACIP_TRANSPORT_OWNED) {
734 result = network_connection_adopt(transport, &p->network);
735 if (result != ASCIICHAT_OK)
736 return result;
737 }
738 p->transport = transport;
739 mutex_lock(&p->settings_mutex);
740 p->settings_request = 0;
742 p->settings.version = 0;
743 mutex_unlock(&p->settings_mutex);
744 p->transport_ownership = transport ? ownership : ACIP_TRANSPORT_BORROWED;
745 if (transport) {
747 if (result != ASCIICHAT_OK)
748 return result;
749 }
750 p->connected = p->transport && acip_transport_is_connected(p->transport);
751
752 return ASCIICHAT_OK;
753}
754
756 if (!p || !p->initialized || !connection)
757 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing participant connection output");
759 return SET_ERRNO(ERROR_INVALID_STATE, "Stop media before transferring its connection");
760 if (!p->network)
761 return SET_ERRNO(ERROR_INVALID_STATE, "Participant does not own a connection");
762 *connection = p->network;
763 p->network = NULL;
764 p->transport = NULL;
766 p->connected = false;
767 return ASCIICHAT_OK;
768}
769
771 if (!owner || !*owner)
772 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing participant connection");
774 if (result != ASCIICHAT_OK)
775 return result;
776 p->network = *owner;
777 *owner = NULL;
781 p->connected = result == ASCIICHAT_OK && acip_transport_is_connected(p->transport);
782 return result;
783}
784
786 if (!p || !p->initialized) {
787 return NULL;
788 }
789
790 return p->transport;
791}
792
794 if (!p) {
795 return false;
796 }
797
798 return p->transport != NULL;
799}
800
804
806 if (!p || !p->initialized)
807 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid participant");
809 const char *json;
810 size_t json_length;
811 asciichat_error_t result = acip_settings_decode(payload, length, &header, &json, &json_length);
812 if (result != ASCIICHAT_OK)
813 return result;
814 mutex_lock(&p->settings_mutex);
815 if ((header.request && (header.request > p->settings_request || header.request < p->settings_applied_request)) || header.revision < p->settings.version) {
816 mutex_unlock(&p->settings_mutex);
817 return ASCIICHAT_OK;
818 }
819 options_t *current = SAFE_MALLOC(sizeof(*current), options_t *), *candidate = SAFE_MALLOC(sizeof(*candidate), options_t *);
821 result = options_prepare_json(current, json, json_length, candidate, true);
822 if (result == ASCIICHAT_OK) {
824 p->settings.version = header.revision;
825 if (header.request)
826 p->settings_applied_request = header.request;
827 }
828 session_settings_t effective = p->settings;
829 SAFE_FREE(current);
830 SAFE_FREE(candidate);
831 mutex_unlock(&p->settings_mutex);
832 if (result != ASCIICHAT_OK)
833 return result;
834 if (header.status && p->callbacks.on_error)
835 p->callbacks.on_error(p, (asciichat_error_t)header.status, "Remote rendering update rejected", p->user_data);
837 p->callbacks.on_settings_changed(p, &effective, p->user_data);
838 return ASCIICHAT_OK;
839}
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_checkpoint(void)
asciichat_errno_scope_t errno_scope_begin(void)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_HANDLED
int atomic_load_int(atomic_t *a)
Atomically load an int value.
asciichat_error_t audio_convert_channels(const float *input, size_t frames, unsigned input_channels, float *output, unsigned output_channels)
#define OPUS_FRAME_SAMPLES
#define CLIENT_AUDIO_PIPELINE_FRAME_MS
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:8
#define AUDIO_CHANNELS
Definition audio/limits.h:9
#define AUDIO_OPUS_SESSION_PACKET_CAPACITY
bool session_av_state_complete(session_av_state_t *state, uint32_t generation)
Definition av_state.c:34
uint32_t session_av_state_begin(session_av_state_t *state)
Definition av_state.c:22
void session_av_state_finish_stop(session_av_state_t *state)
Definition av_state.c:57
bool session_av_state_is_active(session_av_state_t *state)
Definition av_state.c:41
bool session_av_state_should_run(session_av_state_t *state)
Definition av_state.c:45
void session_av_state_begin_stop(session_av_state_t *state)
Definition av_state.c:52
Common buffer size definitions.
client_audio_pipeline_config_t client_audio_pipeline_config_for_source(bool has_media_audio)
Unified client-side audio processing pipeline.
void session_capture_set_audio_context(session_capture_ctx_t *ctx, void *audio_ctx)
Set the audio context for playback control.
void session_capture_complete_open(session_capture_ctx_t *ctx, uint64_t epoch)
uint64_t session_capture_source_epoch(session_capture_ctx_t *ctx)
📹 Unified media capture abstraction for session-based video sources
audio_visualization_source_t source
Definition fft.c:25
opus_application_t
State for one Opus encoding or decoding direction.
Definition opus.h:84
void opus_codec_destroy(opus_codec_t *codec)
Destroy an Opus codec instance.
Definition opus.c:271
size_t opus_codec_encode(opus_codec_t *codec, const float *samples, int num_samples, uint8_t *out_data, size_t out_size)
Encode audio frame with Opus.
Definition opus.c:132
opus_codec_t * opus_codec_create_encoder_channels(opus_application_t application, int sample_rate, int bitrate, int channels)
Definition opus.c:39
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second).
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
bool media_source_has_audio(media_source_t *source)
Check if media source has audio stream.
Definition source.c:774
@ MEDIA_SOURCE_STDIN
Piped or redirected input.
Definition source.h:104
@ MEDIA_SOURCE_WEBCAM
Hardware webcam device.
Definition source.h:102
@ MEDIA_SOURCE_FILE
Media file (video/audio).
Definition source.h:103
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1333
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPTIONS_BUFF_SIZE
Buffer size for option string values.
Definition options.h:305
#define options_terminal_settings()
Definition options.h:1287
#define OPT_PORT_INT_DEFAULT
Default TCP port for client/server communication (integer).
Definition options.h:562
void session_participant_stop_video(session_participant_t *p)
Stop and join video capture, then release its resources Also stops audio when it may borrow the video...
bool session_participant_is_audio_active(session_participant_t *p)
Check if audio is streaming.
struct session_audio_ctx session_audio_ctx_t
Opaque session audio context handle.
size_t session_audio_read_captured(session_audio_ctx_t *ctx, float *buffer, size_t num_samples)
Read captured audio samples.
struct session_participant session_participant_t
Client session state spanning connection, transport, media workers, and callbacks.
image_t * session_capture_process_for_transmission(session_capture_ctx_t *ctx, image_t *frame)
Process a frame for network transmission (resize if needed).
void session_audio_destroy(session_audio_ctx_t *ctx)
Destroy session audio context and free resources.
asciichat_error_t session_participant_connect(session_participant_t *p)
Connect to session server.
bool session_participant_is_video_active(session_participant_t *p)
Check if video is streaming.
void session_participant_stop_audio(session_participant_t *p)
Stop audio capture and streaming.
uint32_t session_participant_get_client_id(session_participant_t *p)
Get assigned client ID.
bool session_participant_has_transport(session_participant_t *p)
Check if participant has a selected transport.
acip_transport_t * session_participant_get_transport(session_participant_t *p)
Get the current transport for the participant.
asciichat_error_t session_participant_request_settings(session_participant_t *p, const session_settings_t *settings)
Request this participant's remote rendering update.
asciichat_error_t session_participant_start_video(session_participant_t *p)
Start video capture and streaming.
asciichat_error_t session_audio_start_duplex(session_audio_ctx_t *ctx)
Start full-duplex audio (simultaneous capture and playback).
struct session_capture_ctx session_capture_ctx_t
session capture config keeps the values that move through the subsystem: type, path,...
void session_participant_destroy(session_participant_t *p)
Destroy session participant and free resources.
asciichat_error_t session_participant_set_transport(session_participant_t *p, acip_transport_t *transport, acip_transport_ownership_t ownership)
Select a transport and its ownership mode for the participant.
image_t * session_capture_read_frame(session_capture_ctx_t *ctx)
Read the next video frame from the capture source.
session_participant_t * session_participant_create(const session_participant_config_t *config)
Server address, security, media, transport, and callback settings for a participant.
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
session_audio_ctx_t * session_audio_create(bool is_host)
Create a new session audio context.
session_capture_ctx_t * session_capture_create(const session_capture_config_t *config)
Legacy function - creates either mirror or network capture based on options.
void * session_capture_get_media_source(session_capture_ctx_t *ctx)
Get the underlying media source from capture context.
bool session_participant_is_connected(session_participant_t *p)
Check if participant is connected.
void session_capture_sleep_for_fps(session_capture_ctx_t *ctx)
Sleep to maintain target frame rate.
void session_participant_disconnect(session_participant_t *p)
Disconnect from session server.
void session_capture_destroy(session_capture_ctx_t *ctx)
Destroy session capture context and free resources.
asciichat_error_t session_participant_get_settings(session_participant_t *p, session_settings_t *settings)
Get current session settings.
asciichat_error_t session_participant_start_audio(session_participant_t *p)
Start audio capture and streaming.
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
⚙️ Common definitions, error codes, macros, and types shared throughout the application
ACIP client-side protocol API.
Transport abstraction layer for ACIP protocol.
struct network_connection network_connection_t
asciichat_error_t acip_send_image_frame(acip_transport_t *transport, const void *pixel_data, uint32_t width, uint32_t height, uint32_t pixel_format)
Send image frame to server (client → server).
asciichat_error_t acip_settings_send(acip_transport_t *transport, const options_t *values, uint32_t request, uint32_t expected_revision)
asciichat_error_t acip_render_settings_prepare(acip_render_settings_t *candidate, const options_t *values)
asciichat_error_t acip_settings_decode(const void *payload, size_t length, acip_settings_header_t *header, const char **json, size_t *json_length)
void network_connection_destroy(network_connection_t **owner)
asciichat_error_t network_connection_prepare_security(network_connection_t *c, bool server, const char *password)
crypto_handshake_context_t * network_connection_handshake(network_connection_t *c)
acip_transport_t * network_connection_transport(network_connection_t *c)
asciichat_error_t network_connection_adopt(acip_transport_t *transport, network_connection_t **out)
📝 Logging API with multiple log levels and terminal output control
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
Opus audio codec wrapper for real-time encoding/decoding.
#define SESSION_PARTICIPANT_WEBCAM_INDEX_BUFFER_SIZE
Definition participant.c:1
network_connection_t * session_participant_connection(session_participant_t *p)
asciichat_error_t session_participant_set_connection(session_participant_t *p, network_connection_t **owner)
Detach the selected transport and transfer its ownership responsibility.
asciichat_error_t session_participant_take_connection(session_participant_t *p, network_connection_t **connection)
asciichat_error_t session_participant_receive_settings(session_participant_t *p, const void *payload, size_t length)
👤 Client-side session participation abstraction
Password prompting utilities with secure input and formatting.
asciichat_error_t options_prepare_json(const options_t *current, const char *json, size_t length, options_t *candidate, bool remote_only)
Definition rcu.c:977
asciichat_error_t acip_send_audio_opus_batch(acip_transport_t *transport, const void *opus_data, size_t opus_len, const uint16_t *frame_sizes, uint32_t frame_count, uint32_t sample_rate, uint32_t frame_duration)
Send batched Opus-encoded audio frames.
Definition send.c:338
ACIP shared/bidirectional packet sending functions.
#define PASSWORD_BUFFER_SIZE
Password input buffer size (256 bytes).
Definition sizes.h:162
🎬 Unified media source abstraction for webcam, files, and stdin
void * session_audio_get_context(session_audio_ctx_t *ctx)
void session_audio_set_capture_source(session_audio_ctx_t *ctx, void *source)
🔊 Session-level audio coordination wrapper
asciichat_error_t session_connection_stop(session_connection_t *connection)
void session_connection_init(session_connection_t *connection, session_connection_ops_t ops, void *context)
asciichat_error_t session_connection_start(session_connection_t *connection)
void session_connection_interrupt_transport(acip_transport_t *transport)
asciichat_error_t session_connection_establish(const char *name, const char *address, uint16_t port, const network_connect_config_t *config, network_connection_t **owner, char *password, size_t capacity, network_connection_prepare_fn prepare, void(*detach)(void *), void *context)
void session_settings_to_options(const session_settings_t *settings, options_t *values)
void session_settings_from_values(const options_t *values, session_settings_t *settings)
void session_settings_init(session_settings_t *settings)
terminal_capabilities_t detect_terminal_capabilities(const terminal_options_t *options)
🔤 String Manipulation and Shell Escaping Utilities
acip render settings keeps the values that move through the subsystem: caps, width,...
acip settings header keeps the values that move through the subsystem: schema, request,...
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Pipeline configuration parameters.
int encoder_channels
Transmitted channels, independent of playback.
Cryptographic handshake context structure.
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
For network connect config, this is the live record that ties timeout_ms, callback_data,...
terminal_color_mode_t color_mode
Color mode (auto/none/16/256/truecolor).
Definition options.h:1084
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
State for one Opus encoding or decoding direction.
Definition opus.h:105
int channels
PCM channels (1 or 2); sample counts include all channels.
Definition opus.h:109
Generation-guarded lifecycle state for one session audio or video stream.
Definition av_state.h:25
Media-source and loader settings used to create a session capture context.
media_source_type_t type
Media source type (WEBCAM, FILE, STDIN, TEST).
const char * path
Device index (for webcam) or file path (for file sources).
bool loop
Enable loop playback for file sources.
Groups the callbacks and caller data for session connection ops. The owner invokes these function poi...
Client-side event hooks for connection, media, settings, and errors.
Definition participant.h:87
void(* on_disconnected)(session_participant_t *p, void *user_data)
Called when disconnected from session.
void(* on_settings_changed)(session_participant_t *p, const session_settings_t *settings, void *user_data)
Called when session settings change.
void(* on_connected)(session_participant_t *p, uint32_t client_id, void *user_data)
Called when successfully connected to session.
Definition participant.h:94
void(* on_error)(session_participant_t *p, asciichat_error_t error, const char *message, void *user_data)
Called when an error occurs.
Client-side event hooks for connection, media, settings, and errors.
session_participant_callbacks_t callbacks
Event callbacks.
const char * address
Server address to connect to.
bool enable_video
Enable video capture and streaming.
const char * password
Password for server authentication (optional).
bool encryption_enabled
Enable encryption (default: true).
void * user_data
User-provided context pointer passed to callbacks.
const char * server_key
Expected server key for verification (optional).
bool enable_audio
Enable audio streaming.
int port
Server port (default: 27224).
Client session state spanning connection, transport, media workers, and callbacks.
Definition participant.c:58
session_settings_t settings
Current session settings.
bool connected
Currently connected.
Definition participant.c:98
struct acip_transport * transport
Selected transport used by all media workers.
Definition participant.c:91
uint32_t settings_applied_request
session_av_state_t audio
Audio streaming active.
bool audio_thread_created
Audio worker handle requires joining.
opus_codec_t * opus_encoder
Opus encoder for audio compression.
network_connection_t * network
Definition participant.c:92
bool encryption_enabled
Encryption enabled.
Definition participant.c:67
char password[BUFFER_SIZE_SMALL]
Password (if any).
Definition participant.c:70
char tls_ca_file[OPTIONS_BUFF_SIZE]
Definition participant.c:75
int port
Server port.
Definition participant.c:64
bool enable_audio
Audio enabled.
Definition participant.c:79
session_connection_t connection
Definition participant.c:59
char address[BUFFER_SIZE_SMALL]
Server address.
Definition participant.c:61
platform_thread_t audio_capture_thread
Audio capture thread handle.
platform_thread_t video_capture_thread
Video capture thread handle.
char server_key[BUFFER_SIZE_MEDIUM]
Server key for verification (if any).
Definition participant.c:73
session_capture_ctx_t * video_capture
Video capture context (for webcam/file media).
acip_transport_ownership_t transport_ownership
Responsibility for releasing the selected transport.
Definition participant.c:95
bool initialized
Context is initialized.
bool enable_video
Video enabled.
Definition participant.c:82
session_participant_callbacks_t callbacks
Event callbacks.
Definition participant.c:85
void * user_data
User data for callbacks.
Definition participant.c:88
session_audio_ctx_t * audio_capture
Audio capture context (for microphone).
uint32_t client_id
Assigned client ID.
session_av_state_t video
Video streaming active.
bool video_thread_created
Video worker handle requires joining.
uint32_t settings_request
When code needs to work with session settings, it keeps version, width, height, color_mode here inste...
⏱️ High-precision timing utilities using sokol_time.h and uthash