ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
common/session/capture.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define SESSION_CAPTURE_LOAD_PATH_BUFFER_SIZE 8192
4#define SESSION_CAPTURE_LOAD_ERROR_BUFFER_SIZE 512
5#define SESSION_CAPTURE_WEBCAM_INDEX_BUFFER_SIZE 32
6#define SESSION_CAPTURE_ERROR_BUFFER_SIZE 512
7#define SESSION_CAPTURE_PATH_BUFFER_SIZE 8192
8#define SESSION_CAPTURE_FAILURE_BUFFER_SIZE 512
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define CAPTURE_TRACKER_NAME_BUFFER_SIZE 32
12
13#include <ascii-chat/otel.h>
16#include <libplatform/atomic.h>
28
29#include "session/capture.h"
31#include <ascii-chat/common.h>
33#include <ascii-chat/log/log.h>
35#include <options/options.h>
39#include <ascii-chat/util/fps.h>
42
43#include <stdio.h>
44#include <string.h>
45#include <time.h>
46#include <libplatform/thread.h>
47#include <libplatform/mutex.h>
54
55static bool playback_cancelled(void *data);
56
57/* ============================================================================
58 * Session Capture Constants
59 * ============================================================================ */
60
62#define SESSION_MAX_FRAME_WIDTH 320
63
65#define SESSION_MAX_FRAME_HEIGHT 180
66
67/* ============================================================================
68 * Session Capture Context Structure
69 * ============================================================================ */
70
90 platform_thread_t loader;
100
117
120
123
126
129
134
137
140
142 _Atomic bool audio_enabled;
143
146
149
152
155
158
161
164};
165
166/* ============================================================================
167 * Internal Helper Functions
168 * ============================================================================ */
169
183static void calculate_optimal_dimensions(ssize_t original_width, ssize_t original_height, ssize_t max_width, ssize_t max_height, ssize_t *result_width, ssize_t *result_height) {
184 // Calculate original aspect ratio
185 float img_aspect = (float)original_width / (float)original_height;
186
187 // Check if image needs resizing
188 if (original_width <= max_width && original_height <= max_height) {
189 // Image is already within bounds - use as-is
190 *result_width = original_width;
191 *result_height = original_height;
192 return;
193 }
194
195 // Determine scaling factor based on which dimension is the limiting factor
196 if ((float)max_width / (float)max_height > img_aspect) {
197 // Max box is wider than image aspect - scale by height
198 *result_height = max_height;
199 *result_width = (ssize_t)(max_height * img_aspect);
200 } else {
201 // Max box is taller than image aspect - scale by width
202 *result_width = max_width;
203 *result_height = (ssize_t)(max_width / img_aspect);
204 }
205}
206
207/* ============================================================================
208 * Session Capture Lifecycle Functions
209 * ============================================================================ */
210
211static void capture_sync_entries(session_capture_ctx_t *ctx, bool add) {
212 if (add)
213 NAMED_REGISTER_ATOMIC(&ctx->load_cancel, "capture.load_cancel", NULL);
214 else
216 if (add)
217 NAMED_REGISTER_ATOMIC(&ctx->playlist_skip, "capture.playlist_skip", NULL);
218 else
220 if (add)
221 NAMED_REGISTER_ATOMIC(&ctx->source_epoch, "capture.source_epoch", NULL);
222 else
224 if (add)
225 NAMED_REGISTER_ATOMIC(&ctx->frame_serial, "capture.frame_serial", NULL);
226 else
228 if (add)
229 NAMED_REGISTER_ATOMIC(&ctx->awaiting_presentation, "capture.awaiting_presentation", NULL);
230 else
232 if (add)
233 NAMED_REGISTER_ATOMIC(&ctx->toggle_media, "capture.toggle_media", NULL);
234 else
236 if (add)
237 NAMED_REGISTER_ATOMIC(&ctx->redraw_media, "capture.redraw_media", NULL);
238 else
240 if (add)
241 NAMED_REGISTER_ATOMIC(&ctx->non_media_active, "capture.non_media_active", NULL);
242 else
244}
245
247 // Mirror capture requires a config with media source info
248 if (!config) {
249 return SET_ERRNO(ERROR_INVALID_PARAM, "Mirror capture requires explicit config"), NULL;
250 }
251
252 // Delegate to the main implementation
253 return session_capture_create(config);
254}
255
257 // Network modes don't capture media - create minimal context for keyboard/audio only
259 if (!ctx) {
260 return NULL;
261 }
262
263 // Set FPS (use provided value or default to 60)
264 ctx->target_fps = target_fps > 0 ? target_fps : DEFAULT_MAX_FPS;
265 ctx->resize_for_network = false;
266
267 // Audio and keyboard will be set up separately by callers
268 ctx->audio_enabled = false;
269 ctx->source = NULL;
270
271 // Initialize minimal FPS tracker (won't be used but keep structure consistent)
272 char *tracker_name = SAFE_MALLOC(CAPTURE_TRACKER_NAME_BUFFER_SIZE, char *);
273 if (!tracker_name) {
274 SAFE_FREE(ctx);
275 return NULL;
276 }
277 safe_snprintf(tracker_name, CAPTURE_TRACKER_NAME_BUFFER_SIZE, "NETWORK_CAPTURE");
278 fps_init(&ctx->fps_tracker, 60, tracker_name);
279
280 ctx->start_time_ns = time_get_ns();
281 ctx->initialized = true;
282 capture_sync_entries(ctx, true);
283
284 log_debug("Created network capture context (no local media source)");
285 return ctx;
286}
287
289 ASCII_OTEL_SCOPE(SESSION_CAPTURE_CREATE);
290 // Auto-create config from command-line options if NULL
291 session_capture_config_t auto_config = {0};
292 if (!config) {
293 // Auto-initialization from GET_OPTION() only works when options have been parsed
294 // Verify by checking if we can access options (would SET_ERRNO if not)
295 const char *media_file = GET_OPTION(media_file);
296 bool media_from_stdin = GET_OPTION(media_from_stdin);
297
298 if (media_file[0] != '\0') {
299 // File or stdin streaming
300 auto_config.type = media_from_stdin ? MEDIA_SOURCE_STDIN : MEDIA_SOURCE_FILE;
301 auto_config.path = media_file;
302 auto_config.loop = GET_OPTION(media_loop) && !media_from_stdin;
303 } else if (GET_OPTION(test_pattern)) {
304 // Test pattern mode
305 auto_config.type = MEDIA_SOURCE_TEST;
306 auto_config.path = NULL;
307 } else {
308 // Webcam mode (default)
309 static char webcam_index_str[SESSION_CAPTURE_WEBCAM_INDEX_BUFFER_SIZE];
310 unsigned int idx = GET_OPTION(webcam_index);
311 safe_snprintf(webcam_index_str, sizeof(webcam_index_str), "%u", idx);
312 auto_config.type = MEDIA_SOURCE_WEBCAM;
313 auto_config.path = webcam_index_str;
314 log_debug("Webcam mode: using device index %u", idx);
315 }
316
317 // Default settings suitable for local display
318 auto_config.target_fps = DEFAULT_MAX_FPS;
319 auto_config.resize_for_network = false;
320 config = &auto_config;
321 }
322
323 // Check if we should exit before starting initialization
324 if (config->should_exit_callback && config->should_exit_callback(config->callback_data)) {
325 return NULL;
326 }
327
328 // Allocate context
330
331 if (!ctx)
332 return NULL;
333 if (mutex_init(&ctx->source_mutex, "capture_source") != 0) {
334 SAFE_FREE(ctx);
335 return NULL;
336 }
337 if (mutex_init(&ctx->load_mutex, "capture_load") != 0) {
338 mutex_destroy(&ctx->source_mutex);
339 SAFE_FREE(ctx);
340 return NULL;
341 }
342 ctx->media_locks_ready = true;
343 if (config->type == MEDIA_SOURCE_FILE && config->path) {
344 media_playlist_t configured = GET_OPTION(media_playlist);
345 if (configured.count && strcmp(configured.paths[0], config->path) == 0)
346 ctx->playlist = configured;
347 else if (media_playlist_append(&ctx->playlist, config->path, strstr(config->path, "://") != NULL) != ASCIICHAT_OK)
348 CLEAR_ERRNO();
349 }
350
351 // Store configuration
352 ctx->target_fps = config->target_fps > 0 ? config->target_fps : DEFAULT_MAX_FPS;
355 ctx->callback_data = config->callback_data;
356
357 // Store audio configuration
358 ctx->audio_enabled = config->enable_audio;
360 ctx->mic_audio_ctx = config->mic_audio_ctx;
361 ctx->using_file_audio = false;
362 ctx->file_has_audio = false;
363
364 // Create media source from config type and path
366 ctx->source = media_source_create_interruptible(config->type, config->path, playback_cancelled, ctx);
367
368 if (!ctx->source) {
369 // Preserve existing error if set, otherwise set generic error
371 asciichat_error_t existing_error = errno_peek_since(create_scope, &failure) ? failure.code : ASCIICHAT_OK;
372 if (existing_error == ASCIICHAT_OK) {
373 SET_ERRNO(ERROR_MEDIA_INIT, "Failed to create media source");
374 }
375 if (config->type == MEDIA_SOURCE_FILE && !playback_cancelled(ctx))
376 NOTICE(WARNING, "MEDIA COULD NOT BE OPENED", "Failed to open media: %s", config->path ? config->path : "");
377 if (ctx->media_locks_ready) {
378 mutex_destroy(&ctx->load_mutex);
379 mutex_destroy(&ctx->source_mutex);
380 }
381 SAFE_FREE(ctx);
382 return NULL;
383 }
384
387 if (ctx->media_locks_ready) {
388 mutex_destroy(&ctx->load_mutex);
389 mutex_destroy(&ctx->source_mutex);
390 }
391 SAFE_FREE(ctx);
392 return NULL;
393 }
394
395 if (config->type == MEDIA_SOURCE_WEBCAM && GET_OPTION(fps) == 0 && !GET_OPTION(waveform) && !GET_OPTION(fft)) {
396 double source_fps = media_source_get_video_fps(ctx->source);
397 if (source_fps >= 0.5 && source_fps <= 1000.0) {
398 ctx->target_fps = (uint32_t)(source_fps + 0.5);
399 log_info("Using negotiated webcam capture rate: %.3f FPS", source_fps);
400 } else {
401 log_warn("Webcam capture rate unavailable; using %u FPS", ctx->target_fps);
402 }
403 }
404
405 if (config->type == MEDIA_SOURCE_FILE) {
406 ctx->saved_matrix = GET_OPTION(matrix_rain);
407 ctx->saved_waveform = GET_OPTION(waveform);
408 ctx->saved_fft = GET_OPTION(fft);
409 // Explicit visualization flags also apply to the initial media source.
410 }
411
412 // Set up exit callback on media source for graceful shutdown during I/O
413 // This allows Ctrl+C to abort blocking FFmpeg calls like YouTube HTTP requests
414 media_source_set_exit_callback(ctx->source, playback_cancelled, ctx);
415
416 // Detect if media source has audio
417 if (ctx->audio_enabled && ctx->source) {
419 if (ctx->file_has_audio) {
420 ctx->using_file_audio = true;
421 log_info("Audio capture enabled: using file audio");
422 } else if (ctx->audio_fallback_enabled && ctx->mic_audio_ctx) {
423 ctx->using_file_audio = false;
424 log_info("Audio capture enabled: file has no audio, using microphone fallback");
425 } else {
426 ctx->audio_enabled = false;
427 log_debug("Audio capture disabled: no file audio and no fallback configured");
428 }
429 }
430
431 // Enable loop if requested (only for file sources)
432 if (config->loop && config->type == MEDIA_SOURCE_FILE && ctx->playlist.count <= 1) {
433 media_source_set_loop(ctx->source, true);
434 }
435
436 // Set initial pause state if requested (only for file sources)
437 // Note: We don't pause yet - we'll pause AFTER reading the first frame in the render loop
438 // This is because paused sources return NULL from read_video()
439 if (config->type == MEDIA_SOURCE_FILE && GET_OPTION(pause)) {
441 log_debug("Will pause after first frame (--pause flag)");
442 }
443
444 // Perform initial seek if requested
445 if (config->initial_seek_timestamp > 0.0) {
446 log_debug("Seeking to %.2f seconds", config->initial_seek_timestamp);
448 if (seek_err != ASCIICHAT_OK) {
449 log_warn("Failed to seek to %.2f seconds: %d", config->initial_seek_timestamp, seek_err);
450 // Continue anyway - seeking is best-effort
451 } else {
452 log_debug("Successfully seeked to %.2f seconds", config->initial_seek_timestamp);
453 // Codec buffers are flushed during seek, so next frame read will use correct position
454
455 // Reset timing state after seek to prevent FPS calculation confusion
456 // (frame_count and elapsed_time must match the new playback position)
457 ctx->frame_count = 0;
458 ctx->start_time_ns = time_get_ns();
459 }
460 }
461
462 // Initialize FPS tracker
463 // Note: Must allocate tracker_name on heap since fps_init stores a pointer to it
464 char *tracker_name = SAFE_MALLOC(CAPTURE_TRACKER_NAME_BUFFER_SIZE, char *);
465 if (!tracker_name) {
467 if (ctx->media_locks_ready) {
468 mutex_destroy(&ctx->load_mutex);
469 mutex_destroy(&ctx->source_mutex);
470 }
471 SAFE_FREE(ctx);
472 return NULL;
473 }
474 safe_snprintf(tracker_name, CAPTURE_TRACKER_NAME_BUFFER_SIZE, "CAPTURE_%u", ctx->target_fps);
475 fps_init(&ctx->fps_tracker, (int)ctx->target_fps, tracker_name);
476
477 // Record start time for FPS calculation (nanoseconds)
478 ctx->start_time_ns = time_get_ns();
479
480 ctx->initialized = true;
481 capture_sync_entries(ctx, true);
482 return ctx;
483}
484
486 if (!ctx) {
487 return;
488 }
489
490 if (ctx->loader_created) {
491 atomic_store_bool(&ctx->load_cancel, true);
492 ASCII_OTEL_SCOPE(MEDIA_TRANSITION_COMMIT);
493 if (thread_join(&ctx->loader, NULL) != 0) {
494 log_error("Cannot join media loader; retaining capture resources");
495 return;
496 }
498 }
499 if (ctx->loaded_frame)
501 if (ctx->initial_frame)
503 if (ctx->loaded_source) {
505 ctx->loaded_source = NULL;
506 }
507 if (ctx->media_locks_ready) {
508 mutex_destroy(&ctx->load_mutex);
509 mutex_destroy(&ctx->source_mutex);
510 }
511 if (ctx->webcam_source)
513 if (ctx->last_media_frame)
515 if (ctx->empty_frame)
518 ctx->face_follow = NULL;
519 // Destroy media source
520 if (ctx->source) {
522 ctx->source = NULL;
523 }
524
525 // Free FPS tracker name (allocated in session_capture_create)
526 if (ctx->fps_tracker.tracker_name) {
527 char *temp = (char *)ctx->fps_tracker.tracker_name;
528 SAFE_FREE(temp);
529 }
530
531 ctx->initialized = false;
532 capture_sync_entries(ctx, false);
533 SAFE_FREE(ctx);
534}
535
536/* ============================================================================
537 * Session Capture Operations
538 * ============================================================================ */
539
540static bool load_cancelled(void *data) {
541 session_capture_ctx_t *ctx = data;
542 return playback_cancelled(ctx) || atomic_load_bool(&ctx->load_cancel);
543}
544
545static bool playback_cancelled(void *data) {
546 session_capture_ctx_t *ctx = data;
548}
549
550static void *load_media_worker(void *data) {
551 ASCII_OTEL_SCOPE(MEDIA_TRANSITION_LOAD);
552 session_capture_ctx_t *ctx = data;
555 if (source) {
556 media_source_set_exit_callback(source, load_cancelled, ctx);
557 media_source_set_loop(source, GET_OPTION(media_loop) && ctx->load_playlist.count <= 1);
560 source = NULL;
561 }
562 }
563 image_t *first = NULL;
565 uint64_t deadline = time_get_ns() + 15 * NS_PER_SEC_INT;
566 while (!load_cancelled(ctx) && time_get_ns() < deadline) {
569 if (frame) {
570 first = image_new(frame->w, frame->h);
571 if (first)
572 memcpy(first->pixels, frame->pixels, (size_t)frame->w * frame->h * sizeof(rgb_pixel_t));
573 break;
574 }
575 asciichat_error_context_t read_failure;
576 if (errno_peek_since(read_scope, &read_failure) || media_source_at_end(source))
577 break;
578 platform_sleep_ms(1);
579 }
580 if (!first) {
582 source = NULL;
583 }
584 }
585 ASCII_OTEL_ATTR_STRING("media.transition.outcome", source ? "ready" : load_cancelled(ctx) ? "cancelled" : "failed");
586 if (!source && !load_cancelled(ctx))
587 ascii_otel_error("Media transition could not prepare source");
589 char error[SESSION_CAPTURE_ERROR_BUFFER_SIZE] = "Could not open media";
590 if (!source && errno_peek_since(scope, &failure))
591 snprintf(error, sizeof(error), "%.*s", (int)(sizeof(error) - 1), failure.context_message);
593 mutex_lock(&ctx->load_mutex);
594 ctx->loaded_source = source;
595 ctx->loaded_frame = first;
596 snprintf(ctx->load_error, sizeof(ctx->load_error), "%s", error);
597 ctx->loader_done = true;
598 mutex_unlock(&ctx->load_mutex);
599 return NULL;
600}
601
603 if (!ctx || !ctx->media_locks_ready)
604 return false;
605 mutex_lock(&ctx->load_mutex);
606 bool busy = ctx->loader_created;
607 if (busy)
608 atomic_store_bool(&ctx->load_cancel, true);
609 mutex_unlock(&ctx->load_mutex);
610 if (busy)
612 return busy;
613}
614
615static asciichat_error_t capture_load_playlist(session_capture_ctx_t *ctx, const media_playlist_t *list, size_t index, bool automatic) {
616 const char *path = list->paths[index];
617 if (!ctx || !ctx->media_locks_ready || !path || strlen(path) >= sizeof(ctx->load_path))
618 return SET_ERRNO(ERROR_INVALID_STATE, "Local capture is unavailable");
619 size_t limit = sizeof(((options_t *)0)->media_file);
620 if (strstr(path, "://"))
621 limit = sizeof(((options_t *)0)->media_url);
622 if (strlen(path) >= limit)
623 return SET_ERRNO(ERROR_INVALID_PARAM, "Media path or URL exceeds the configured source limit");
624 mutex_lock(&ctx->load_mutex);
625 if (ctx->loader_created || ctx->loaded_source) {
626 mutex_unlock(&ctx->load_mutex);
627 return SET_ERRNO(ERROR_INVALID_STATE, "Previous media load is still active; Escape cancels loading");
628 }
629 ctx->load_playlist = *list;
631 ctx->load_is_advance = automatic;
632 snprintf(ctx->load_path, sizeof(ctx->load_path), "%s", path);
633 ctx->loader_done = false;
635 atomic_store_bool(&ctx->load_cancel, false);
637 if (progress != ASCIICHAT_OK) {
638 mutex_unlock(&ctx->load_mutex);
639 return progress;
640 }
641 if (platform_thread_create(&ctx->loader, "media_open", load_media_worker, ctx) != 0) {
643 mutex_unlock(&ctx->load_mutex);
644 return SET_ERRNO(ERROR_THREAD, "Cannot start media loader");
645 }
646 ctx->loader_created = true;
647 mutex_unlock(&ctx->load_mutex);
648 return ASCIICHAT_OK;
649}
650
652 ASCII_OTEL_SCOPE(SESSION_CAPTURE_OPEN_MEDIA);
653 media_playlist_t list = {0};
654 asciichat_error_t result = media_playlist_append(&list, path, path && strstr(path, "://") != NULL);
655 return result == ASCIICHAT_OK ? capture_load_playlist(ctx, &list, 0, false) : result;
656}
658 ASCII_OTEL_SCOPE(SESSION_CAPTURE_OPEN_PLAYLIST);
659 media_playlist_t list = {0};
660 asciichat_error_t result = media_playlist_parse(text, &list);
661 return result == ASCIICHAT_OK ? capture_load_playlist(ctx, &list, 0, false) : result;
662}
664 ASCII_OTEL_SCOPE(SESSION_CAPTURE_SKIP_MEDIA);
665 if (ctx && (direction == -1 || direction == 1))
666 atomic_store_u64(&ctx->playlist_skip, direction > 0 ? 1 : 2);
667}
668
669/* Only the capture owner commits replacements, between frame reads. */
670static void capture_commit_media(session_capture_ctx_t *ctx) {
671 if (!ctx->media_locks_ready || !ctx->loader_created || !ctx->loader_done)
672 return;
673 mutex_lock(&ctx->load_mutex);
674 if (!ctx->loader_created || !ctx->loader_done) {
675 mutex_unlock(&ctx->load_mutex);
676 return;
677 }
678 // Media replacement must not inherit a discarded frame's sampling decision.
679 ASCII_OTEL_SCOPE_PARENT(MEDIA_TRANSITION_COMMIT, &(const gotel_context_t){0});
680 if (thread_join(&ctx->loader, NULL) != 0) {
681 mutex_unlock(&ctx->load_mutex);
682 log_error("Cannot join media loader; deferring replacement");
683 return;
684 }
686 snprintf(path, sizeof(path), "%s", ctx->load_path);
687 snprintf(failure, sizeof(failure), "%s", ctx->load_error);
688 ctx->loader_created = false;
689 media_source_t *replacement = ctx->loaded_source;
690 ctx->loaded_source = NULL;
691 image_t *first = ctx->loaded_frame;
692 ctx->loaded_frame = NULL;
693 media_playlist_t loaded_playlist = ctx->load_playlist;
694 bool cancelled = atomic_load_bool(&ctx->load_cancel);
695 bool automatic = ctx->load_is_advance;
696 ASCII_OTEL_ATTR_STRING("media.transition.kind", automatic ? "playlist_advance" : "user");
697 ASCII_OTEL_ATTR_STRING("media.transition.outcome", cancelled ? "cancelled" : "failed");
698 mutex_unlock(&ctx->load_mutex);
699 if (cancelled || !replacement) {
700 ascii_otel_ui_usage("media_input_prompt", cancelled ? "load_cancelled" : "load_failed", 0);
701 ctx->advance_failed |= automatic;
703 if (first)
704 image_destroy(first);
705 if (replacement)
706 media_source_destroy(replacement);
707 if (!cancelled)
708 NOTICE(WARNING, "MEDIA COULD NOT BE OPENED", "%s", failure);
709 CLEAR_ERRNO();
710 return;
711 }
713 if (audio && audio_stop_duplex(audio) != ASCIICHAT_OK) {
714 ascii_otel_ui_usage("media_input_prompt", "load_failed", 0);
715 ctx->advance_failed |= automatic;
717 if (first)
718 image_destroy(first);
719 media_source_destroy(replacement);
720 LOG_ERRNO_IF_SET("Cannot stop audio for media replacement");
721 CLEAR_ERRNO();
722 return;
723 }
724 bool has_audio = media_source_has_audio(replacement);
725 media_source_set_exit_callback(replacement, playback_cancelled, ctx);
726 if (audio) {
727 media_source_t *old_audio_source = audio->capture_media_source;
728 bool old_playback_only = audio->playback_only;
729 bool use_media = has_audio && GET_OPTION(audio_capture_source) != AUDIO_CAPTURE_SOURCE_MIC;
730 audio->capture_media_source = use_media ? replacement : NULL;
731 audio->playback_only = !audio_should_enable_microphone(GET_OPTION(audio_capture_source), has_audio);
732 media_source_set_audio_context(replacement, audio);
734 if (audio->capture_buffer)
736 if (audio_start_duplex(audio) != ASCIICHAT_OK) {
737 ascii_otel_ui_usage("media_input_prompt", "load_failed", 0);
738 ctx->advance_failed |= automatic;
740 LOG_ERRNO_IF_SET("Cannot start replacement audio; restoring previous source");
741 CLEAR_ERRNO();
742 if (first)
743 image_destroy(first);
744 if (audio_stop_duplex(audio) != ASCIICHAT_OK) {
745 /* A live worker may still borrow replacement; retain it until teardown. */
746 mutex_lock(&ctx->load_mutex);
747 ctx->loaded_source = replacement;
748 mutex_unlock(&ctx->load_mutex);
749 NOTICE(WARNING, "MEDIA AUDIO", "Could not stop replacement audio");
750 CLEAR_ERRNO();
751 return;
752 }
753 audio->capture_media_source = old_audio_source;
754 audio->playback_only = old_playback_only;
755 media_source_destroy(replacement);
756 if (audio_start_duplex(audio) != ASCIICHAT_OK) {
757 LOG_ERRNO_IF_SET("Cannot restore previous audio");
758 CLEAR_ERRNO();
759 }
760 NOTICE(WARNING, "MEDIA AUDIO", "Could not start replacement audio; previous video retained");
761 CLEAR_ERRNO();
762 return;
763 }
764 }
765 media_source_t *previous = ctx->source;
766 bool was_file = media_source_get_type(previous) == MEDIA_SOURCE_FILE;
767 if (!was_file && !ctx->webcam_source && media_source_uses_webcam(previous)) {
768 ctx->webcam_source = previous;
769 ctx->webcam_attempted = true;
770 previous = NULL;
771 }
772 ctx->source = replacement;
773 if (ctx->initial_frame)
775 ctx->initial_frame = first;
776 ctx->initial_frame_pending = first != NULL;
777 ctx->file_has_audio = has_audio;
779 ctx->audio_enabled = audio != NULL;
780 ctx->saved_audio_source = replacement;
781 ctx->non_media_requested = false;
784 if (!was_file) {
785 ctx->saved_matrix = GET_OPTION(matrix_rain);
786 ctx->saved_waveform = GET_OPTION(waveform);
787 ctx->saved_fft = GET_OPTION(fft);
788 }
789 options_set_bool("matrix_rain", false);
790 options_set_bool("waveform", false);
791 options_set_bool("fft", false);
792 ctx->retained_frame_shown = false;
793 if (ctx->last_media_frame)
795 ctx->last_media_frame = NULL;
797 ctx->face_follow = NULL;
798 ctx->face_media_valid = false;
799 ctx->next_frame_deadline_ns = 0;
800 ctx->frame_count = 0;
801 ctx->start_time_ns = time_get_ns();
802 if (GET_OPTION(fps) == 0) {
803 double fps = media_source_get_video_fps(replacement);
804 if (fps >= 0.5 && fps <= UINT32_MAX - 0.5) {
805 ctx->target_fps = (uint32_t)(fps + 0.5);
807 }
808 }
810 ctx->paused_after_first_frame = false;
811 if (audio) {
815 }
816 if (previous)
817 media_source_destroy(previous);
818 bool url = strstr(path, "://") != NULL;
819 options_set_bool("media_input", true);
820 options_set_string("media_url", url ? path : "");
821 options_set_string("media_file", url ? "" : path);
822 options_set_bool("media_from_stdin", false);
823 mutex_lock(&ctx->load_mutex);
824 ctx->playlist = loaded_playlist;
825 ctx->advance_failed = false;
828 mutex_unlock(&ctx->load_mutex);
829 ascii_otel_ui_usage("media_input_prompt", "load_succeeded", 0);
830 ASCII_OTEL_ATTR_STRING("media.transition.outcome", "committed");
831 log_info("Opened media: %s", path);
832 CLEAR_ERRNO();
833}
834
836 if (ctx && ctx->media_locks_ready)
837 mutex_lock(&ctx->source_mutex);
838}
840 if (ctx && ctx->media_locks_ready)
841 mutex_unlock(&ctx->source_mutex);
842}
843
844static image_t *capture_read_frame(session_capture_ctx_t *ctx) {
845 if (ctx->audio_update) {
847 void *audio_ctx = atomic_ptr_load(&ctx->audio_ctx);
848 ctx->audio_enabled = audio_ctx && ((audio_context_t *)audio_ctx)->running;
849 }
850 capture_commit_media(ctx);
851 bool loading = ctx->loader_created;
852 if (!loading) {
854 bool ended = ctx->source && media_source_get_type(ctx->source) == MEDIA_SOURCE_FILE && media_source_at_end(ctx->source);
855 size_t next;
856 bool adjacent = media_playlist_adjacent(&ctx->playlist, skip == 2 ? -1 : 1, &next);
857 if (!skip && ended && !adjacent && GET_OPTION(media_loop) && ctx->playlist.count > 1) {
858 next = 0;
859 adjacent = true;
860 }
861 if ((skip || (ended && !ctx->advance_failed)) && adjacent) {
862 if (capture_load_playlist(ctx, &ctx->playlist, next, !skip) != ASCIICHAT_OK) {
863 ctx->advance_failed |= !skip;
864 LOG_ERRNO_IF_SET("Cannot advance media playlist");
865 CLEAR_ERRNO();
866 }
867 }
868 }
869 if (!ctx || !ctx->initialized || !ctx->source) {
870 return NULL;
871 }
872
873 if (ctx->initial_frame && !ctx->initial_frame_pending) {
875 ctx->initial_frame = NULL;
876 }
877 static uint64_t last_frame_time_ns = 0;
878 uint64_t frame_request_time_ns = time_get_ns();
879
880 bool is_file = media_source_get_type(ctx->source) == MEDIA_SOURCE_FILE;
881 if (is_file && (atomic_exchange_u64(&ctx->toggle_media, 0) & 1)) {
882 bool leaving = !atomic_load_bool(&ctx->non_media_active);
883 if (leaving) {
886 }
888 if (audio && audio_stop_duplex(audio) == ASCIICHAT_OK) {
889 if (leaving) {
893 audio->capture_media_source = NULL;
894 audio->playback_only = !audio_should_enable_microphone(GET_OPTION(audio_capture_source), false);
895 audio->monitor_local_media = false;
896 } else {
900 }
901 if (audio->capture_buffer)
903 if (audio_start_duplex(audio) != ASCIICHAT_OK) {
904 LOG_ERRNO_IF_SET("Failed to switch audio input");
905 CLEAR_ERRNO();
906 }
907 }
908 if (!leaving && !ctx->media_was_paused)
910 atomic_store_bool(&ctx->non_media_active, leaving);
911 ctx->face_media_valid = false;
913 ctx->face_follow = NULL;
914 atomic_store_bool(&ctx->redraw_media, true);
915 ctx->next_frame_deadline_ns = 0;
916 log_info("Media playback %s at %.3fs (%s)", leaving ? "hidden" : "selected", media_source_get_position(ctx->source), ctx->media_was_paused ? "paused" : "playing");
917 }
918 bool alternate = atomic_load_bool(&ctx->non_media_active);
919 if (alternate && !ctx->webcam_attempted) {
920 ctx->webcam_attempted = true;
924 ctx->webcam_source = NULL;
925 }
926 if (!ctx->webcam_source) {
927 LOG_ERRNO_IF_SET("Webcam unavailable; animations remain available");
928 CLEAR_ERRNO();
929 ctx->empty_frame = image_new(320, 180);
930 if (ctx->empty_frame)
931 memset(ctx->empty_frame->pixels, 0, 320 * 180 * sizeof(rgb_pixel_t));
932 }
933 }
934 image_t *frame;
935 if (!alternate && ctx->initial_frame_pending) {
936 frame = ctx->initial_frame;
937 ctx->initial_frame_pending = false;
938 } else {
939 frame = alternate ? (ctx->webcam_source ? media_source_read_video(ctx->webcam_source) : ctx->empty_frame) : media_source_read_video(ctx->source);
940 }
941 if (frame && is_file && !alternate) {
942 double now = (double)time_get_ns() / 1e9;
943 double position = media_source_get_position(ctx->source);
944 if (ctx->face_media_valid && (position < ctx->face_media_position - 0.1 || position > ctx->face_media_position + (now - ctx->face_media_tick) + 0.75)) {
946 ctx->face_follow = NULL;
947 }
948 ctx->face_media_valid = true;
949 ctx->face_media_position = position;
950 ctx->face_media_tick = now;
951 }
952 bool recording = GET_OPTION(render_file)[0] != '\0';
953 if (is_file && !alternate && (!GET_OPTION(snapshot_mode) || recording)) {
954 if (frame) {
955 ctx->retained_frame_shown = false;
956 if (!ctx->last_media_frame || ctx->last_media_frame->w != frame->w || ctx->last_media_frame->h != frame->h) {
957 if (ctx->last_media_frame)
959 ctx->last_media_frame = image_new(frame->w, frame->h);
960 }
961 if (ctx->last_media_frame)
962 memcpy(ctx->last_media_frame->pixels, frame->pixels, (size_t)frame->w * frame->h * sizeof(rgb_pixel_t));
963 } else if ((!recording && media_source_at_end(ctx->source)) || media_source_is_paused(ctx->source)) {
964 if (!recording && media_source_at_end(ctx->source))
966 bool redraw = atomic_exchange_bool(&ctx->redraw_media, false);
967 // A paused recording still advances session time, including when stopped
968 // before playback resumes. Retained frames do not increment frame_serial.
969 if (!ctx->retained_frame_shown || redraw || recording) {
970 ctx->retained_frame_shown = true;
971 bool debug = false;
972#ifndef NDEBUG
973 debug = GET_OPTION(face_follow_debug);
974#endif
975 return face_follow_image_process(&ctx->face_follow, ctx->last_media_frame, (double)time_get_ns() / 1e9, GET_OPTION(face_follow), debug, ctx->resize_for_network ? SESSION_MAX_FRAME_WIDTH : 960,
977 }
978 return NULL;
979 }
980 }
981 stats_duration_record(stats_runtime_scope(), STATS_DURATION_CAPTURE, time_get_ns() - frame_request_time_ns);
982 if (frame) {
985 }
986
987 if (frame) {
988 uint64_t frame_available_time_ns = time_get_ns();
989
990 // Track frame for FPS reporting
991 fps_frame_ns(&ctx->fps_tracker, frame_available_time_ns, "frame captured");
992 ctx->frame_count++;
993 if (ctx->observed_rate_start_ns == 0)
994 ctx->observed_rate_start_ns = frame_available_time_ns;
996 if (ctx->source && media_source_uses_webcam(ctx->source) && GET_OPTION(fps) == 0 && frame_available_time_ns - ctx->observed_rate_start_ns >= NS_PER_SEC_INT) {
997 double elapsed = (double)(frame_available_time_ns - ctx->observed_rate_start_ns) / (double)NS_PER_SEC_INT;
998 unsigned int observed_fps = (unsigned int)(ctx->observed_rate_frames / elapsed + 0.5);
999 if (observed_fps > 0) {
1000 log_info("Webcam OS delivery: %.3f FPS over %.2f seconds (%llu frames)", (double)ctx->observed_rate_frames / elapsed, elapsed, (unsigned long long)ctx->observed_rate_frames);
1001 ui_controller_set_effective_fps(observed_fps);
1002 }
1003 ctx->observed_rate_start_ns = frame_available_time_ns;
1004 ctx->observed_rate_frames = 0;
1005 }
1007
1008 // Log frame-to-frame timing
1009 if (last_frame_time_ns > 0) {
1010 uint64_t time_since_last_frame_ns = time_elapsed_ns(last_frame_time_ns, frame_request_time_ns);
1011 uint64_t time_to_get_frame_ns = time_elapsed_ns(frame_request_time_ns, frame_available_time_ns);
1012 double since_last_ms = (double)time_since_last_frame_ns / NS_PER_MS;
1013 double to_get_ms = (double)time_to_get_frame_ns / NS_PER_MS;
1014
1015 if (ctx->frame_count % 30 == 0) {
1016 log_dev_every(3 * US_PER_SEC_INT, "FRAME_TIMING[%lu]: since_last=%.1f ms, to_get=%.1f ms", ctx->frame_count, since_last_ms, to_get_ms);
1017 }
1018 }
1019 last_frame_time_ns = frame_available_time_ns;
1020
1021 // Handle --pause flag: pause after first frame is read
1024 ctx->paused_after_first_frame = true;
1025 log_info("Paused (--pause flag)");
1026 }
1027 }
1028
1029 bool debug = false;
1030#ifndef NDEBUG
1031 debug = GET_OPTION(face_follow_debug);
1032#endif
1033 return face_follow_image_process(&ctx->face_follow, frame, (double)time_get_ns() / 1e9, GET_OPTION(face_follow), debug, ctx->resize_for_network ? SESSION_MAX_FRAME_WIDTH : 960,
1035}
1036
1038 ASCII_OTEL_SCOPE(SESSION_CAPTURE_READ_FRAME);
1039 if (!ctx)
1040 return NULL;
1042 image_t *frame = capture_read_frame(ctx);
1044 return frame;
1045}
1046
1048 ASCII_OTEL_SCOPE(SESSION_CAPTURE_PROCESS_FOR_TRANSMISSION_INTO);
1049 if (!ctx || !frame || !output)
1050 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing transmission frame or workspace");
1051 ssize_t width = frame->w, height = frame->h;
1052 if (ctx->resize_for_network)
1053 calculate_optimal_dimensions(frame->w, frame->h, SESSION_MAX_FRAME_WIDTH, SESSION_MAX_FRAME_HEIGHT, &width, &height);
1054 if (!*output || (*output)->w != width || (*output)->h != height) {
1055 image_t *replacement = image_new(width, height);
1056 if (!replacement)
1057 return SET_ERRNO(ERROR_MEMORY, "Cannot reserve transmission image workspace");
1058 image_destroy(*output);
1059 *output = replacement;
1060 }
1061 if (frame != *output) {
1062 if (frame->w == width && frame->h == height)
1063 memcpy((*output)->pixels, frame->pixels, (size_t)width * (size_t)height * sizeof(rgb_pixel_t));
1064 else
1065 image_resize(frame, *output);
1066 }
1067 return ASCIICHAT_OK;
1068}
1069
1071 image_t *output = NULL;
1073 return NULL;
1074 return output;
1075}
1076
1078 if (!ctx || !ctx->initialized || !ctx->source) {
1079 return;
1080 }
1081
1082 uint64_t frame_interval_ns = NS_PER_SEC_INT / ctx->target_fps;
1083 if (frame_interval_ns == 0) {
1084 return;
1085 }
1086
1087 uint64_t now_ns = time_get_ns();
1088 ctx->next_frame_deadline_ns = capture_pacing_deadline(ctx->next_frame_deadline_ns, now_ns, frame_interval_ns);
1089 if (ctx->next_frame_deadline_ns > now_ns)
1090 platform_sleep_ns(ctx->next_frame_deadline_ns - now_ns);
1091}
1092
1094 if (!ctx || !ctx->initialized || !ctx->source) {
1095 return true;
1096 }
1097
1098 bool pending = ctx->loader_created;
1099 size_t next;
1100 if (pending || (!ctx->advance_failed && (media_playlist_adjacent(&ctx->playlist, 1, &next) || (GET_OPTION(media_loop) && ctx->playlist.count > 1))))
1101 return false;
1102 if (media_source_get_type(ctx->source) == MEDIA_SOURCE_FILE && !GET_OPTION(snapshot_mode) && !GET_OPTION(render_file)[0])
1103 return false;
1104 return media_source_at_end(ctx->source);
1105}
1106
1108 return ctx != NULL && ctx->initialized && ctx->source != NULL;
1109}
1110
1112 if (!ctx || !ctx->initialized || ctx->frame_count == 0) {
1113 return 0.0;
1114 }
1115
1116 // Calculate elapsed time in nanoseconds then convert to seconds
1117 uint64_t elapsed_ns = time_elapsed_ns(ctx->start_time_ns, time_get_ns());
1118 double elapsed_sec = time_ns_to_s(elapsed_ns);
1119
1120 if (elapsed_sec <= 0.0) {
1121 return 0.0;
1122 }
1123
1124 return (double)ctx->frame_count / elapsed_sec;
1125}
1126
1128 if (!ctx) {
1129 return 0;
1130 }
1131 return ctx->target_fps;
1132}
1133
1135 if (!ctx || !ctx->initialized) {
1136 return false;
1137 }
1138 return ctx->audio_enabled;
1139}
1140
1141static size_t capture_read_audio(session_capture_ctx_t *ctx, float *buffer, size_t num_samples) {
1142 if (!ctx || !ctx->initialized || !buffer || num_samples == 0) {
1143 return 0;
1144 }
1145
1146 if (!ctx->audio_enabled) {
1147 return 0;
1148 }
1149
1150 // If using file audio, read from media source
1151 if (ctx->using_file_audio && ctx->source && !atomic_load_bool(&ctx->non_media_active)) {
1152 return media_source_read_audio(ctx->source, buffer, num_samples);
1153 }
1154
1155 // If using microphone fallback, read from mic context
1156 void *current_audio_ctx = atomic_ptr_load(&ctx->audio_ctx);
1157 if (ctx->mic_audio_ctx || (current_audio_ctx && atomic_load_bool(&ctx->non_media_active))) {
1158 audio_context_t *audio_ctx = ctx->mic_audio_ctx ? ctx->mic_audio_ctx : current_audio_ctx;
1159 if (audio_ctx && audio_ctx->capture_buffer) {
1160 return audio_ring_buffer_read(audio_ctx->capture_buffer, buffer, num_samples);
1161 }
1162 }
1163
1164 return 0;
1165}
1166
1167size_t session_capture_read_audio(session_capture_ctx_t *ctx, float *buffer, size_t num_samples) {
1168 ASCII_OTEL_SCOPE(SESSION_CAPTURE_READ_AUDIO);
1170 size_t count = capture_read_audio(ctx, buffer, num_samples);
1172 return count;
1173}
1174
1176 if (!ctx || !ctx->initialized) {
1177 return false;
1178 }
1179 return ctx->using_file_audio;
1180}
1181
1183 if (!ctx || !ctx->initialized || !ctx->source) {
1184 return NULL;
1185 }
1186 return (void *)ctx->source;
1187}
1188
1190 if (!ctx || !ctx->initialized) {
1191 return NULL;
1192 }
1193 return atomic_ptr_load(&ctx->audio_ctx);
1194}
1195
1197 if (ctx) {
1198 ctx->audio_update = update;
1199 ctx->audio_update_data = user_data;
1200 }
1201}
1202
1204 if (ctx) {
1206 atomic_ptr_store(&ctx->audio_ctx, audio_ctx);
1208 }
1209}
1210
1212 if (!ctx || !ctx->source || media_source_get_type(ctx->source) != MEDIA_SOURCE_FILE)
1213 return;
1214 // Swap UI preferences in input order so a following animation key applies to
1215 // the newly selected mode even before the capture thread switches devices.
1217 options_set_bool("media_input", !ctx->non_media_requested);
1218 if (ctx->non_media_requested) {
1219 options_set_bool("matrix_rain", ctx->saved_matrix);
1220 options_set_bool("waveform", ctx->saved_waveform);
1221 options_set_bool("fft", ctx->saved_fft);
1222 } else {
1223 ctx->saved_matrix = GET_OPTION(matrix_rain);
1224 ctx->saved_waveform = GET_OPTION(waveform);
1225 ctx->saved_fft = GET_OPTION(fft);
1226 options_set_bool("matrix_rain", false);
1227 options_set_bool("waveform", false);
1228 options_set_bool("fft", false);
1229 }
1231}
1232
1236
1238 if (ctx)
1239 atomic_store_bool(&ctx->redraw_media, true);
1240}
1241
1249 if (!ctx || !atomic_load_bool(&ctx->awaiting_presentation))
1250 return;
1251 mutex_lock(&ctx->load_mutex);
1254 mutex_unlock(&ctx->load_mutex);
1255}
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,...)
#define CLEAR_ERRNO()
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
uint64_t atomic_exchange_u64(atomic_t *a, uint64_t new_value)
Atomically exchange a uint64_t and return the old value.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
#define CAPTURE_TRACKER_NAME_BUFFER_SIZE
#define SESSION_CAPTURE_FAILURE_BUFFER_SIZE
void session_capture_lock_source(session_capture_ctx_t *ctx)
void session_capture_unlock_source(session_capture_ctx_t *ctx)
void session_capture_set_audio_context(session_capture_ctx_t *ctx, void *audio_ctx)
Set the audio context for playback control.
void session_capture_set_audio_updater(session_capture_ctx_t *ctx, session_capture_audio_update_fn update, void *user_data)
void session_capture_toggle_media(session_capture_ctx_t *ctx)
#define SESSION_CAPTURE_LOAD_ERROR_BUFFER_SIZE
#define SESSION_CAPTURE_ERROR_BUFFER_SIZE
void session_capture_skip_media(session_capture_ctx_t *ctx, int direction)
uint64_t session_capture_frame_serial(session_capture_ctx_t *ctx)
bool session_capture_media_active(session_capture_ctx_t *ctx)
void * session_capture_get_audio_context(session_capture_ctx_t *ctx)
Get the audio context for playback control.
#define SESSION_MAX_FRAME_WIDTH
Maximum frame width for network transmission (bandwidth optimization).
asciichat_error_t session_capture_open_playlist(session_capture_ctx_t *ctx, const char *text)
#define SESSION_CAPTURE_LOAD_PATH_BUFFER_SIZE
void session_capture_redraw_media(session_capture_ctx_t *ctx)
void session_capture_complete_open(session_capture_ctx_t *ctx, uint64_t epoch)
asciichat_error_t session_capture_open_media(session_capture_ctx_t *ctx, const char *path)
#define SESSION_CAPTURE_WEBCAM_INDEX_BUFFER_SIZE
#define SESSION_CAPTURE_PATH_BUFFER_SIZE
#define SESSION_MAX_FRAME_HEIGHT
Maximum frame height for network transmission (bandwidth optimization).
uint64_t session_capture_source_epoch(session_capture_ctx_t *ctx)
bool session_capture_cancel_open(session_capture_ctx_t *ctx)
asciichat_error_t session_capture_process_for_transmission_into(session_capture_ctx_t *ctx, image_t *frame, image_t **output)
📹 Unified media capture abstraction for session-based video sources
void *(* session_capture_audio_update_fn)(media_source_t *source, void *user_data)
Named object registry for debugging — log identifiable resource names.
image_t * face_follow_image_process(face_follow_image_t **context, image_t *source, double now, bool enabled, bool debug, int max_width, int max_height)
void face_follow_image_destroy(face_follow_image_t *context)
struct face_follow_image face_follow_image_t
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
⏱️ FPS tracking utility for monitoring frame throughput across all threads
Buffered terminal frame rendering.
bool audio_should_enable_microphone(audio_capture_source_t source, bool has_media_audio)
Determine if microphone should be enabled based on audio source setting and media state.
size_t audio_ring_buffer_read(audio_ring_buffer_t *rb, float *data, size_t samples)
Read audio samples from ring buffer.
asciichat_error_t audio_start_duplex(audio_context_t *ctx)
Start full-duplex audio (simultaneous capture and playback).
asciichat_error_t audio_stop_duplex(audio_context_t *ctx)
Stop full-duplex audio.
void audio_flush_playback_buffers(audio_context_t *ctx)
Flush all audio buffers to synchronize with seek operations.
void audio_ring_buffer_clear(audio_ring_buffer_t *rb)
Clear all audio samples from ring buffer.
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
void fps_frame_ns(fps_t *tracker, uint64_t current_time_ns, const char *context)
Track a frame and detect lag conditions (nanosecond version - PRIMARY).
Definition fps.c:58
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
void fps_init(fps_t *tracker, int expected_fps, const char *name)
Initialize FPS tracker.
Definition fps.c:37
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_MEDIA_INIT
Definition error_codes.h:70
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define DEFAULT_MAX_FPS
Default maximum frame rate (frames per second).
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
bool media_source_at_end(media_source_t *source)
Check if media source reached end of stream.
Definition source.c:922
bool media_source_is_paused(media_source_t *source)
Check if media source is paused.
Definition source.c:1190
bool media_source_has_video(media_source_t *source)
Check if media source has video stream.
Definition source.c:769
size_t media_source_read_audio(media_source_t *source, float *buffer, size_t num_samples)
Read audio samples from media source.
Definition source.c:795
bool media_source_has_audio(media_source_t *source)
Check if media source has audio stream.
Definition source.c:885
double media_source_get_position(media_source_t *source)
Get current playback position in seconds.
Definition source.c:1125
void media_source_destroy(media_source_t *source)
Destroy media source and free resources.
Definition source.c:561
void media_source_resume(media_source_t *source)
Resume media playback after pause.
Definition source.c:1183
double media_source_get_video_fps(media_source_t *source)
Get video frame rate in frames per second.
Definition source.c:1148
double media_source_get_duration(media_source_t *source)
Get media duration in seconds.
Definition source.c:1103
void media_source_pause(media_source_t *source)
Pause media playback.
Definition source.c:1176
image_t * media_source_read_video(media_source_t *source)
Read next video frame from media source.
Definition source.c:653
asciichat_error_t media_source_seek(media_source_t *source, double timestamp_sec)
Seek media source to timestamp.
Definition source.c:1006
void media_source_set_exit_callback(media_source_t *source, bool(*should_exit_callback)(void *), void *user_data)
Set exit signal callback for graceful shutdown during I/O.
Definition source.c:1212
media_source_type_t media_source_get_type(media_source_t *source)
Get media source type.
Definition source.c:1099
void media_source_set_audio_context(media_source_t *source, void *audio_ctx)
Set audio context for playback buffer management.
Definition source.c:1206
media_source_t * media_source_create(media_source_type_t type, const char *path)
Create a new media source.
Definition source.c:243
void media_source_set_loop(media_source_t *source, bool loop)
Enable or disable looping.
Definition source.c:910
@ MEDIA_SOURCE_STDIN
Piped or redirected input.
Definition source.h:105
@ MEDIA_SOURCE_WEBCAM
Hardware webcam device.
Definition source.h:103
@ MEDIA_SOURCE_FILE
Media file (video/audio).
Definition source.h:104
@ MEDIA_SOURCE_TEST
Test pattern generator.
Definition source.h:106
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS
Definition time.h:163
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1339
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
asciichat_error_t options_set_string(const char *name, const char *value)
Definition rcu.c:981
asciichat_error_t options_set_bool(const char *name, bool value)
Definition rcu.c:973
@ AUDIO_CAPTURE_SOURCE_MIC
Definition options.h:291
bool session_capture_has_audio(session_capture_ctx_t *ctx)
Check if capture source has audio available.
bool(* session_capture_should_exit_fn)(void *user_data)
Callback type to check if initialization should be cancelled.
image_t * session_capture_process_for_transmission(session_capture_ctx_t *ctx, image_t *frame)
Process a frame for network transmission (resize if needed).
session_capture_ctx_t * session_mirror_capture_create(const session_capture_config_t *config)
Create a new session capture context.
bool session_capture_at_end(session_capture_ctx_t *ctx)
Check if capture source has reached end of stream.
double session_capture_get_current_fps(session_capture_ctx_t *ctx)
Get the current FPS being achieved by the capture source.
size_t session_capture_read_audio(session_capture_ctx_t *ctx, float *buffer, size_t num_samples)
Read audio samples from capture source.
struct session_capture_ctx session_capture_ctx_t
session capture config keeps the values that move through the subsystem: type, path,...
image_t * session_capture_read_frame(session_capture_ctx_t *ctx)
Read the next video frame from the capture source.
bool session_capture_is_valid(session_capture_ctx_t *ctx)
Check if capture context is initialized and valid.
bool session_capture_using_file_audio(session_capture_ctx_t *ctx)
Check if currently using file audio vs microphone fallback.
uint32_t session_capture_get_target_fps(session_capture_ctx_t *ctx)
Get the target FPS configured for this capture 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.
session_capture_ctx_t * session_network_capture_create(uint32_t target_fps)
Create network mode capture context without media source.
void * session_capture_get_media_source(session_capture_ctx_t *ctx)
Get the underlying media source from capture context.
void session_capture_sleep_for_fps(session_capture_ctx_t *ctx)
Sleep to maintain target frame rate.
void session_capture_destroy(session_capture_ctx_t *ctx)
Destroy session capture context and free resources.
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
void image_resize(const image_t *s, image_t *d)
Resize image using nearest-neighbor interpolation.
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
📝 Logging API with multiple log levels and terminal output control
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:716
#define NOTICE(severity, title,...)
Definition notice.h:86
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_ui_usage(const char *screen, const char *event, uint64_t duration_ns)
Definition otel.c:506
void ascii_otel_error(const char *message)
Definition otel.c:965
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_SCOPE_PARENT(id, parent)
Definition otel.h:98
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
asciichat_error_t media_playlist_append(media_playlist_t *list, const char *path, bool url)
Definition playlist.c:7
asciichat_error_t media_playlist_parse(const char *text, media_playlist_t *list)
Definition playlist.c:40
bool media_playlist_adjacent(const media_playlist_t *list, int direction, size_t *index)
Definition playlist.c:128
asciichat_error_t ui_media_loading_present(void)
Definition prompt.c:382
static bool size_t index
Definition queries.h:10
void stats_runtime_media(unsigned width, unsigned height, double position, double duration)
Definition runtime.c:72
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
Shutdown check system for clean library/application separation.
media_source_t * media_source_create_interruptible(media_source_type_t type, const char *path, bool(*cancel)(void *), void *data)
Definition source.c:248
bool media_source_uses_webcam(media_source_t *source)
Definition source.c:647
asciichat_error_t media_source_start_video(media_source_t *source)
Definition source.c:629
🎬 Unified media source abstraction for webcam, files, and stdin
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:114
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
When code needs to work with audio device info, it keeps index, max_input_channels,...
bool monitor_local_media
Play local file audio in solo sessions.
audio_ring_buffer_t * capture_buffer
Counters and timestamps used to calculate and report frame rate.
Definition fps.h:59
const char * tracker_name
Definition fps.h:67
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).
char paths[64][256]
Definition playlist.h:14
Media source for video and audio capture.
Definition source.c:48
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).
uint32_t target_fps
Target frame rate in FPS (e.g., 60 for display, 144 for network).
double initial_seek_timestamp
Seek to this timestamp after opening media (0.0 = no seek).
session_capture_should_exit_fn should_exit_callback
Optional cancellation callback, also invoked by media loader threads. The callback and its data must ...
void * callback_data
Opaque data passed to should_exit_callback.
bool audio_fallback_to_mic
Fall back to microphone if file audio is not available.
bool resize_for_network
Resize frames to network-optimal dimensions (MAX_FRAME_WIDTH x MAX_FRAME_HEIGHT).
bool loop
Enable loop playback for file sources.
bool enable_audio
Enable audio capture from media source.
void * mic_audio_ctx
Microphone audio context for fallback (borrowed, not owned).
Runtime state for media loading, frame timing, and source switching.
fps_t fps_tracker
FPS tracker for monitoring capture rate.
media_source_t * saved_audio_source
session_capture_should_exit_fn should_exit_callback
void * mic_audio_ctx
Microphone audio context for fallback (borrowed, not owned).
bool file_has_audio
File has audio stream available.
media_playlist_t load_playlist
session_capture_audio_update_fn audio_update
bool using_file_audio
Using file audio (true) or microphone fallback (false).
bool paused_after_first_frame
Whether we've already paused after the first frame.
_Atomic bool audio_enabled
Audio is enabled for capture.
media_source_t * loaded_source
uint32_t target_fps
Target frames per second.
uint64_t start_time_ns
Start time for FPS calculation (nanoseconds).
bool initialized
Context has been successfully initialized.
bool should_pause_after_first_frame
Pause media source after first frame is read (–pause flag).
bool resize_for_network
Whether to resize frames for network transmission.
media_source_t * source
Underlying media source (webcam, file, stdin, test).
face_follow_image_t * face_follow
uint64_t next_frame_deadline_ns
Next capture deadline on the monotonic clock (nanoseconds).
atomic_ptr_t audio_ctx
Main audio context for playback (borrowed, not owned).
bool audio_fallback_enabled
Fall back to microphone if file has no audio.
uint64_t frame_count
Frame count for FPS calculation.
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_remove(ui_screen_t screen)
void ui_controller_set_effective_fps(unsigned int fps)
@ UI_SCREEN_RENDER_PROGRESS