ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
source.c
Go to the documentation of this file.
1
5
6/* Storage capacities in elements; text buffers include the terminating NUL. */
7#define MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE 64
8
9#include <ascii-chat/otel.h>
11
19#include <options/options.h>
21#include <ascii-chat/log/log.h>
23#include <libplatform/compiler.h>
24#include <libplatform/system.h>
25#include <util/string.h>
26#include <libplatform/terminal.h>
31#include <stdlib.h>
32#include <string.h>
33#include <errno.h>
34#include <limits.h>
35
36/* ============================================================================
37 * Media Source Structure
38 * ============================================================================ */
39
52
53 // Webcam context (for WEBCAM and TEST types)
55 unsigned short int webcam_index;
56
57 // FFmpeg decoders (for FILE and STDIN types)
61
62 // Thread synchronization
63 mutex_t decoder_mutex;
64
65 // Cached paths
66 char *file_path;
68
69 // Audio integration
70 void *audio_ctx;
71
72 // Test pattern state (for MEDIA_SOURCE_TEST)
75};
76
77/* ============================================================================
78 * Stream Type Detection
79 * ============================================================================ */
80
84static bool url_has_ffmpeg_native_extension(const char *url) {
85 if (!url)
86 return false;
87
88 // Extract extension from URL (ignore query params)
89 const char *question = strchr(url, '?');
90 size_t url_len = question ? (size_t)(question - url) : strlen(url);
91
92 // Find last dot
93 const char *dot = NULL;
94 for (const char *p = url + url_len - 1; p >= url; p--) {
95 if (*p == '.') {
96 dot = p;
97 break;
98 }
99 if (*p == '/')
100 break;
101 }
102
103 if (!dot)
104 return false;
105
106 const char *ext = dot + 1;
107
108 // Video containers
109 if (strcasecmp(ext, "mp4") == 0 || strcasecmp(ext, "mkv") == 0 || strcasecmp(ext, "webm") == 0 || strcasecmp(ext, "mov") == 0 || strcasecmp(ext, "avi") == 0 || strcasecmp(ext, "flv") == 0 ||
110 strcasecmp(ext, "ogv") == 0 || strcasecmp(ext, "ts") == 0 || strcasecmp(ext, "m2ts") == 0 || strcasecmp(ext, "mts") == 0 || strcasecmp(ext, "3gp") == 0 || strcasecmp(ext, "3g2") == 0 ||
111 strcasecmp(ext, "f4v") == 0 || strcasecmp(ext, "asf") == 0 || strcasecmp(ext, "wmv") == 0) {
112 return true;
113 }
114
115 // Audio containers
116 if (strcasecmp(ext, "ogg") == 0 || strcasecmp(ext, "oga") == 0 || strcasecmp(ext, "wma") == 0 || strcasecmp(ext, "wav") == 0 || strcasecmp(ext, "flac") == 0 || strcasecmp(ext, "aac") == 0 ||
117 strcasecmp(ext, "m4a") == 0 || strcasecmp(ext, "m4b") == 0 || strcasecmp(ext, "mp3") == 0 || strcasecmp(ext, "aiff") == 0 || strcasecmp(ext, "au") == 0) {
118 return true;
119 }
120
121 // Still and animated image formats handled directly by FFmpeg
122 if (strcasecmp(ext, "png") == 0 || strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0 || strcasecmp(ext, "gif") == 0 || strcasecmp(ext, "bmp") == 0 || strcasecmp(ext, "webp") == 0 ||
123 strcasecmp(ext, "tif") == 0 || strcasecmp(ext, "tiff") == 0) {
124 return true;
125 }
126
127 // Streaming
128 if (strcasecmp(ext, "m3u8") == 0 || strcasecmp(ext, "mpd") == 0) {
129 return true;
130 }
131
132 return false;
133}
134
138static bool url_is_direct_stream(const char *url) {
139 if (!url)
140 return false;
141
142 // RTSP, RTMP, and TCP are streaming protocols, always direct
143 if (strncmp(url, "rtsp://", 7) == 0 || strncmp(url, "rtmp://", 7) == 0 || strncmp(url, "tcp://", 6) == 0) {
144 return true;
145 }
146
147 // Check for FFmpeg-native file extension
148 return url_has_ffmpeg_native_extension(url);
149}
150
154static asciichat_error_t media_source_resolve_url(const char *url, const char *yt_dlp_options, char *output_url, size_t output_size, char *audio_url, size_t audio_size,
155 yt_dlp_request_options_t *video_request, yt_dlp_request_options_t *audio_request, bool (*cancel)(void *), void *data) {
156 ASCII_OTEL_SCOPE(MEDIA_SOURCE_RESOLVE_URL);
157 if (!url || !output_url || output_size < 256 || !audio_url || audio_size < 256) {
158 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for URL resolution");
159 return ERROR_INVALID_PARAM;
160 }
161 audio_url[0] = '\0';
162 memset(video_request, 0, sizeof(*video_request));
163 memset(audio_request, 0, sizeof(*audio_request));
164
165 // Local paths and native FFmpeg protocols never need site extraction.
166 bool is_site = platform_strncasecmp(url, "http://", sizeof("http://") - 1) == 0 || platform_strncasecmp(url, "https://", sizeof("https://") - 1) == 0 ||
167 (platform_strncasecmp(url, "ytsearch", sizeof("ytsearch") - 1) == 0 && strchr(url, ':'));
168 bool is_direct = !is_site || url_is_direct_stream(url);
169 ASCII_OTEL_ATTR_STRING("media.resolver", is_direct ? "ffmpeg" : "yt-dlp");
170
171 if (is_direct) {
172 log_debug("URL is direct stream, passing to FFmpeg directly: %s", url);
173 SAFE_STRNCPY(output_url, url, output_size - 1);
174 output_url[output_size - 1] = '\0';
175 return ASCIICHAT_OK;
176 }
177
178 log_debug("URL is complex site, attempting yt-dlp extraction: %s", url);
179
180 // Try yt-dlp extraction (for complex sites like YouTube, Twitch, etc.)
181 asciichat_errno_scope_t extraction_scope = errno_scope_begin();
182 asciichat_error_t yt_dlp_result = yt_dlp_extract_with_options(url, yt_dlp_options, output_url, output_size, audio_url, audio_size, video_request, audio_request, cancel, data);
183 errno_scope_end(extraction_scope, ASCIICHAT_ERRNO_HANDLED);
184 if (yt_dlp_result == ASCIICHAT_OK) {
185 log_debug("yt-dlp successfully extracted stream URL");
186 return ASCIICHAT_OK;
187 }
188 if (yt_dlp_result == ERROR_NOT_SUPPORTED)
189 return SET_ERRNO(ERROR_NOT_SUPPORTED, "The selected yt-dlp proxy cannot be used for media requests");
190 if (yt_dlp_result == ERROR_INVALID_PARAM)
191 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid yt-dlp options");
192 audio_url[0] = '\0';
193 video_request->headers[0] = video_request->cookies[0] = '\0';
194 audio_request->headers[0] = audio_request->cookies[0] = '\0';
195
196 ASCII_OTEL_ATTR_STRING("media.resolver", "ffmpeg");
197 log_debug("URL extraction failed; trying the native decoder");
198
199 // For complex sites, try FFmpeg as last resort
200 log_debug("yt-dlp failed, trying FFmpeg as fallback for: %s", url);
201 SAFE_STRNCPY(output_url, url, output_size - 1);
202 output_url[output_size - 1] = '\0';
203 log_info("FFmpeg will attempt to handle URL (yt-dlp extraction failed)");
204 return ASCIICHAT_OK; // Let FFmpeg try - if it fails, that's ok too
205}
206
207/* ============================================================================
208 * Media Source Lifecycle
209 * ============================================================================ */
210
212 return media_source_create_interruptible(type, path, NULL, NULL);
213}
214
215media_source_t *media_source_create_interruptible(media_source_type_t type, const char *path, bool (*cancel)(void *), void *data) {
216 ASCII_OTEL_SCOPE(MEDIA_SOURCE_CREATE_INTERRUPTIBLE);
218 if (!source) {
219 SET_ERRNO(ERROR_MEMORY, "Failed to allocate media source");
220 return NULL;
221 }
222
223 memset(source, 0, sizeof(*source));
224 source->type = type;
225 source->loop_enabled = false;
226 atomic_store_bool(&source->is_paused, false);
227
228 // Initialize mutex for protecting shared decoder access (for YouTube URLs)
229 if (mutex_init(&source->decoder_mutex, "media_decoder") != 0) {
230 SET_ERRNO(ERROR_MEMORY, "Failed to initialize mutex");
232 return NULL;
233 }
234
235 switch (type) {
236 case MEDIA_SOURCE_WEBCAM: {
237 // Parse webcam index from path (if provided)
238 unsigned short int index = 0;
239 if (path) {
240 char *endptr;
241 errno = 0;
242 long parsed = strtol(path, &endptr, 10);
243 if (*endptr == '\0' && errno == 0 && parsed >= 0 && parsed <= USHRT_MAX) {
244 index = (unsigned short int)parsed;
245 } else if (*endptr != '\0' || errno != 0) {
246 log_error("Invalid webcam index: %s", path);
247 }
248 }
249
250 source->webcam_index = index;
251 if (GET_OPTION(waveform) || GET_OPTION(fft))
252 break;
253 asciichat_error_t webcam_error = webcam_init_context(&source->webcam_ctx, index);
254 if (webcam_error != ASCIICHAT_OK) {
255 asciichat_error_context_t webcam_context;
256 bool has_webcam_context = HAS_ERRNO(&webcam_context);
257 // Webcam init failed - log and cleanup
258 NOTICE(WARNING, "CAMERA UNAVAILABLE", "Failed to initialize webcam device %u: %s", index, asciichat_error_format(has_webcam_context ? webcam_context.context_message : NULL, webcam_error));
259 // Destroy mutexes before freeing source
260 mutex_destroy(&source->decoder_mutex);
262
263 // Add media-level context while preserving the webcam failure as its cause.
264 if (webcam_error == ERROR_WEBCAM_IN_USE) {
265 SET_ERRNO(ERROR_WEBCAM_IN_USE, "Webcam device %u is in use", index);
266 } else {
267 SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam device %u", index);
268 }
269 return NULL;
270 }
271
272 log_debug("Media source: Webcam device %u", index);
273 break;
274 }
275
276 case MEDIA_SOURCE_FILE: {
278 if (!path || path[0] == '\0') {
279 SET_ERRNO(ERROR_INVALID_PARAM, "File path is required for FILE source");
280 // Destroy mutexes before freeing source
281 mutex_destroy(&source->decoder_mutex);
283 return NULL;
284 }
285
286 // Resolve URL using smart FFmpeg/yt-dlp routing
287 const char *effective_path = path;
288 char resolved_url[MEDIA_STREAM_URL_SIZE] = {0};
289 char resolved_audio_url[MEDIA_STREAM_URL_SIZE] = {0};
290 yt_dlp_request_options_t video_request = {0}, audio_request = {0};
291 const char *yt_dlp_options = GET_OPTION(yt_dlp_options);
292
293 log_debug("Resolving URL: %s", path);
294 asciichat_error_t resolve_err =
295 media_source_resolve_url(path, yt_dlp_options, resolved_url, sizeof(resolved_url), resolved_audio_url, sizeof(resolved_audio_url), &video_request, &audio_request, cancel, data);
296 if (resolve_err != ASCIICHAT_OK) {
297 log_debug("Failed to resolve URL %s", asciichat_error_format(NULL, resolve_err));
298 // Destroy mutexes before freeing source
299 mutex_destroy(&source->decoder_mutex);
301 return NULL;
302 }
303 if (cancel && cancel(data)) {
304 mutex_destroy(&source->decoder_mutex);
306 return NULL;
307 }
308 effective_path = resolved_url;
309 log_debug("Using resolved URL for playback");
310
311 // Store original URL for potential re-extraction if needed
312 source->original_youtube_url = platform_strdup(path);
313 if (!source->original_youtube_url) {
314 log_warn("Failed to cache original URL");
315 }
316
317 // Cache file path for potential reopen on loop
318 source->file_path = platform_strdup(effective_path);
319 if (!source->file_path) {
320 SET_ERRNO(ERROR_MEMORY, "Failed to duplicate file path");
321 SAFE_FREE(source->original_youtube_url);
322 // Destroy mutexes before freeing source
323 mutex_destroy(&source->decoder_mutex);
325 return NULL;
326 }
327
328 // Always use separate decoders for video and audio
329 // This allows independent read rates and avoids lock contention
331 source->video_decoder =
332 ffmpeg_decoder_create_with_request_options(effective_path, cancel, data, video_request.headers, video_request.cookies, video_request.proxy_specified ? video_request.proxy : NULL);
333 if (!source->video_decoder) {
334 SET_ERRNO(ERROR_MEDIA_OPEN, "Media initialization failed: video decoder could not open input");
335 if (!cancel)
336 NOTICE(WARNING, "MEDIA COULD NOT BE OPENED", "Failed to open media file for video: %s: %s", effective_path, asciichat_error_format(NULL, ERROR_MEDIA_OPEN));
337 LOG_ERRNO_IF_SET("Media initialization failed");
338 SAFE_FREE(source->file_path);
339 SAFE_FREE(source->original_youtube_url);
340 // Destroy mutexes before freeing source
341 mutex_destroy(&source->decoder_mutex);
343 return NULL;
344 }
345
346 ASSERT_NO_ERRNO_SINCE(decoder_scope);
347
348 decoder_scope = errno_checkpoint();
349 const char *audio_path = resolved_audio_url[0] ? resolved_audio_url : effective_path;
350 const yt_dlp_request_options_t *audio_settings = resolved_audio_url[0] ? &audio_request : &video_request;
351 source->audio_decoder =
352 ffmpeg_decoder_create_with_request_options(audio_path, cancel, data, audio_settings->headers, audio_settings->cookies, audio_settings->proxy_specified ? audio_settings->proxy : NULL);
353 if (!source->audio_decoder) {
354 SET_ERRNO(ERROR_MEDIA_OPEN, "Media initialization failed: audio decoder could not open input");
355 LOG_ERRNO_IF_SET("Media initialization failed");
356 ffmpeg_decoder_destroy(source->video_decoder);
357 source->video_decoder = NULL;
358 SAFE_FREE(source->file_path);
359 SAFE_FREE(source->original_youtube_url);
360 // Destroy mutexes before freeing source
361 mutex_destroy(&source->decoder_mutex);
363 return NULL;
364 }
365 source->is_shared_decoder = false;
366
367 ASSERT_NO_ERRNO_SINCE(decoder_scope);
368 // yt-dlp emits selected formats in selector order, which may be audio first.
369 if (resolved_audio_url[0] && !ffmpeg_decoder_has_video(source->video_decoder) && ffmpeg_decoder_has_video(source->audio_decoder) && ffmpeg_decoder_has_audio(source->video_decoder)) {
370 ffmpeg_decoder_t *audio = source->video_decoder;
371 source->video_decoder = source->audio_decoder;
372 source->audio_decoder = audio;
373 }
374
375 // Start prefetch after choosing the decoder that actually contains video.
378 if (prefetch_err != ASCIICHAT_OK) {
379 log_error("Failed to start video prefetch thread: %s", asciichat_error_format(NULL, prefetch_err));
380 ffmpeg_decoder_destroy(source->video_decoder);
381 ffmpeg_decoder_destroy(source->audio_decoder);
382 SAFE_FREE(source->file_path);
383 SAFE_FREE(source->original_youtube_url);
384 mutex_destroy(&source->decoder_mutex);
386 return NULL;
387 }
388 ASSERT_NO_ERRNO_SINCE(prefetch_scope);
390 // Both decoders succeeded: failed extraction/prefetch attempts are resolved.
392 ASSERT_NO_ERRNO_SINCE(media_scope);
393 log_debug("Media source: URL resolved to stream (separate video/audio decoders)");
394 break;
395 }
396
397 case MEDIA_SOURCE_STDIN: {
398 // Create separate decoders for video and audio from stdin
399 source->video_decoder = ffmpeg_decoder_create_stdin();
400 if (!source->video_decoder) {
401 log_error("Failed to open stdin for video input");
402 // Destroy mutexes before freeing source
403 mutex_destroy(&source->decoder_mutex);
405 return NULL;
406 }
407
408 // Start prefetch thread for stdin video frames
411 if (prefetch_err != ASCIICHAT_OK) {
412 log_error("Failed to start stdin video prefetch thread: %s", asciichat_error_format(NULL, prefetch_err));
413 ffmpeg_decoder_destroy(source->video_decoder);
414 SAFE_FREE(source->file_path);
415 SAFE_FREE(source->original_youtube_url);
416 mutex_destroy(&source->decoder_mutex);
418 return NULL;
419 }
420
421 ASSERT_NO_ERRNO_SINCE(prefetch_scope);
423 source->audio_decoder = ffmpeg_decoder_create_stdin();
424 if (!source->audio_decoder) {
425 log_error("Failed to open stdin for audio input");
426 ffmpeg_decoder_destroy(source->video_decoder);
427 source->video_decoder = NULL;
428 // Destroy mutexes before freeing source
429 mutex_destroy(&source->decoder_mutex);
431 return NULL;
432 }
433
434 log_debug("Media source: stdin (separate video/audio decoders)");
435 break;
436 }
437
438 case MEDIA_SOURCE_TEST: {
439 // Test pattern state is encapsulated in media_source_t
440 source->webcam_index = 0;
441 source->webcam_ctx = NULL; // No context needed for test pattern
442 source->test_pattern = NULL;
443 source->test_start_ns = 0;
444
445 log_debug("Media source: Test pattern");
446 break;
447 }
448
449 default:
450 SET_ERRNO(ERROR_INVALID_PARAM, "Unknown media source type: %d", type);
451 // Destroy mutexes before freeing source
452 mutex_destroy(&source->decoder_mutex);
454 return NULL;
455 }
456
457 if ((type == MEDIA_SOURCE_FILE || type == MEDIA_SOURCE_STDIN) && !ffmpeg_decoder_has_video(source->video_decoder) && ffmpeg_decoder_has_audio(source->audio_decoder)) {
458 source->audio_only = true;
459 }
460
461 /* Register media source with named registry */
462 char media_type_str[MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE];
463 switch (type) {
465 snprintf(media_type_str, sizeof(media_type_str), "media_source:webcam");
466 break;
468 snprintf(media_type_str, sizeof(media_type_str), "media_source:file");
469 break;
471 snprintf(media_type_str, sizeof(media_type_str), "media_source:test");
472 break;
473 default:
474 snprintf(media_type_str, sizeof(media_type_str), "media_source:unknown");
475 break;
476 }
477 NAMED_REGISTER(source, media_type_str, "media_source_t", "0x%tx", NULL);
478
479 /* Register media source's sync primitives with hierarchical naming */
480 NAMED_REGISTER_MUTEX(&source->decoder_mutex, "decoder_mutex", (uintptr_t)(const void *)(source));
481 NAMED_REGISTER_ATOMIC(&source->is_paused, "media_paused", source);
482
483 return source;
484}
485
487 ASCII_OTEL_SCOPE(MEDIA_SOURCE_DESTROY);
488 if (!source) {
489 return;
490 }
491
492 // Cleanup based on type
493 if (source->webcam_ctx) {
494 webcam_cleanup_context(source->webcam_ctx);
495 source->webcam_ctx = NULL;
496 }
497
498 // For YouTube (shared decoder), only destroy once
499 // For local files (separate decoders), destroy both
500 if (source->video_decoder) {
501 ffmpeg_decoder_destroy(source->video_decoder);
502 source->video_decoder = NULL;
503 }
504
505 if (source->audio_decoder) {
506 // Don't double-free if audio and video share the same decoder
507 if (!source->is_shared_decoder) {
508 ffmpeg_decoder_destroy(source->audio_decoder);
509 }
510 source->audio_decoder = NULL;
511 }
512
513 SAFE_FREE(source->file_path);
514 SAFE_FREE(source->original_youtube_url);
515
516 // Clean up test pattern frame
517 test_pattern_destroy(source->test_pattern);
518 source->test_pattern = NULL;
519
520 NAMED_UNREGISTER(&source->is_paused);
521
522 // Destroy mutexes
523 mutex_destroy(&source->decoder_mutex);
524
526}
527
528/* ============================================================================
529 * Video Operations
530 * ============================================================================ */
531
532static image_t *read_test_pattern(media_source_t *source) {
534 // Preserve a useful source resolution when terminal dimensions are automatic.
535 width = width > 0 ? width : 320;
536 height = height > 0 ? height * 2 : 240;
537 if (!source->test_pattern) {
538 if (test_pattern_create(width, height, &source->test_pattern) != ASCIICHAT_OK)
539 return NULL;
540 source->test_start_ns = time_get_ns();
541 } else if (test_pattern_resize(source->test_pattern, width, height) != ASCIICHAT_OK)
542 return NULL;
543 double elapsed = (double)time_elapsed_ns(source->test_start_ns, time_get_ns()) / 1000000.0;
544 if (test_pattern_render(source->test_pattern, GET_OPTION(test_pattern_index), elapsed, true) != ASCIICHAT_OK)
545 return NULL;
546 return test_pattern_image(source->test_pattern);
547}
548
550 ASCII_OTEL_SCOPE(MEDIA_SOURCE_START_VIDEO);
551 if (!source)
552 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing media source");
553 if ((!source->audio_only && source->type != MEDIA_SOURCE_WEBCAM) || source->webcam_ctx || GET_OPTION(test_pattern))
554 return ASCIICHAT_OK;
555 if (source->type != MEDIA_SOURCE_WEBCAM)
556 source->webcam_index = GET_OPTION(webcam_index);
557 asciichat_error_t err = webcam_init_context(&source->webcam_ctx, source->webcam_index);
558 if (err != ASCIICHAT_OK)
559 return SET_ERRNO(err, "Audio-only media requires webcam %u", source->webcam_index);
560 log_info("Audio-only media: using webcam %u for video", source->webcam_index);
561 return ASCIICHAT_OK;
562}
563
567
569 ASCII_OTEL_SCOPE(MEDIA_SOURCE_READ_VIDEO);
570 if (!source) {
571 return NULL;
572 }
573
574 // Check pause state (thread-safe)
575 bool is_paused = atomic_load_bool(&source->is_paused);
576
577 // Return NULL immediately if paused (maintaining position)
578 if (is_paused) {
579 return NULL;
580 }
581
582 if (source->audio_only && media_source_at_end(source))
583 return NULL;
584 // Audio visualizations replace the image at display time and need only a frame clock.
585 if ((source->audio_only && GET_OPTION(test_pattern)) || ((source->audio_only || source->type == MEDIA_SOURCE_WEBCAM) && (GET_OPTION(waveform) || GET_OPTION(fft))))
586 return read_test_pattern(source);
587 if ((source->audio_only || source->type == MEDIA_SOURCE_WEBCAM) && !source->webcam_ctx) {
589 return NULL;
590 }
591 if (source->webcam_ctx)
592 return webcam_read_context(source->webcam_ctx);
593
594 switch (source->type) {
596 // Read from webcam
597 if (source->webcam_ctx) {
598 return webcam_read_context(source->webcam_ctx);
599 }
600 return NULL;
601
602 case MEDIA_SOURCE_TEST: {
603 return read_test_pattern(source);
604 }
605
607 case MEDIA_SOURCE_STDIN: {
608 if (!source->video_decoder) {
609 return NULL;
610 }
611
612 // Lock shared decoder if YouTube URL (protect against concurrent audio thread access)
613 if (source->is_shared_decoder) {
614 mutex_lock(&source->decoder_mutex);
615 }
616
617 uint64_t frame_read_start_ns = time_get_ns();
618 image_t *frame = ffmpeg_decoder_read_video_frame(source->video_decoder);
619 uint64_t frame_read_ns = time_elapsed_ns(frame_read_start_ns, time_get_ns());
620
621 // Track frame reading statistics for FPS diagnosis
622 static uint64_t total_attempts = 0;
623 static uint64_t successful_frames = 0;
624 static uint64_t null_frame_count = 0;
625 static uint64_t total_read_time_ns = 0;
626 static uint64_t max_read_time_ns = 0;
627
628 total_attempts++;
629 if (frame) {
630 successful_frames++;
631 total_read_time_ns += frame_read_ns;
632 if (frame_read_ns > max_read_time_ns) {
633 max_read_time_ns = frame_read_ns;
634 }
635
636 // Log statistics every 30 successful frames
637 if (successful_frames % 30 == 0) {
638 double avg_read_ms = (double)total_read_time_ns / (double)successful_frames / NS_PER_MS;
639 double max_read_ms = (double)max_read_time_ns / NS_PER_MS;
640 double null_rate = (double)null_frame_count * 100.0 / (double)total_attempts;
642 "FRAME_STATS[%lu]: avg_read=%.2f ms, max_read=%.2f ms, null_rate=%.1f%% "
643 "(%lu null/%lu attempts)",
644 successful_frames, avg_read_ms, max_read_ms, null_rate, null_frame_count, total_attempts);
645 }
646 } else {
647 null_frame_count++;
648 }
649
650 // Handle EOF with loop
651 if (!frame && ffmpeg_decoder_at_end(source->video_decoder)) {
652 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
653 log_debug("End of file reached, rewinding for loop");
655 // Try reading again after rewind
656 frame = ffmpeg_decoder_read_video_frame(source->video_decoder);
657 }
658 }
659 }
660
661 // Unlock shared decoder
662 if (source->is_shared_decoder) {
663 mutex_unlock(&source->decoder_mutex);
664 }
665
666 return frame;
667 }
668
669 default:
670 return NULL;
671 }
672}
673
675 if (!source) {
676 return false;
677 }
678
679 switch (source->type) {
682 return true; // Webcam/test always has video
683
686 return source->audio_only || (source->video_decoder && ffmpeg_decoder_has_video(source->video_decoder));
687
688 default:
689 return false;
690 }
691}
692
693/* ============================================================================
694 * Audio Operations
695 * ============================================================================ */
696
697size_t media_source_read_audio(media_source_t *source, float *buffer, size_t num_samples) {
698 ASCII_OTEL_SCOPE(MEDIA_SOURCE_READ_AUDIO);
699 if (!source || !buffer || num_samples == 0) {
700 return 0;
701 }
702
703 static uint64_t call_count = 0;
704 call_count++;
705 if (call_count <= 5 || call_count % 1000 == 0) {
706 log_debug("#%lu: source_type=%d num_samples=%zu", call_count, source->type, num_samples);
707 }
708
709 // Check pause state (thread-safe)
710 bool is_paused = atomic_load_bool(&source->is_paused);
711
712 // Return silence immediately if paused (maintaining position)
713 if (is_paused) {
714 memset(buffer, 0, num_samples * sizeof(float));
715 return num_samples;
716 }
717
718 switch (source->type) {
721 // Webcam/test pattern don't provide audio
722 return 0;
723
725 case MEDIA_SOURCE_STDIN: {
726 if (!source->audio_decoder) {
727 log_warn_every(US_PER_SEC_INT, "audio_decoder is NULL!");
728 return 0;
729 }
730
731 // Lock shared decoder if YouTube URL (protect against concurrent video thread access)
732 if (source->is_shared_decoder) {
733 mutex_lock(&source->decoder_mutex);
734 }
735
736 double audio_pos_before_read = ffmpeg_decoder_get_position(source->audio_decoder);
737 size_t samples_read = ffmpeg_decoder_read_audio_samples(source->audio_decoder, buffer, num_samples);
738 double audio_pos_after_read = ffmpeg_decoder_get_position(source->audio_decoder);
739
740 static double last_audio_pos = 0;
741 if (audio_pos_after_read >= 0 && last_audio_pos >= 0 && audio_pos_after_read < last_audio_pos) {
742 log_debug_every(US_PER_SEC_INT, "Audio position moved backward: %.2f → %.2f (LOOPING!)", last_audio_pos, audio_pos_after_read);
743 }
744 if (audio_pos_after_read >= 0) {
745 last_audio_pos = audio_pos_after_read;
746 }
747
748 log_debug_every(US_PER_SEC_INT, "Audio: read %zu samples, pos %.2f → %.2f", samples_read, audio_pos_before_read, audio_pos_after_read);
749
750 // Handle EOF with loop
751 if (samples_read == 0 && ffmpeg_decoder_at_end(source->audio_decoder)) {
752 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
753 log_debug("End of file reached (audio), rewinding for loop");
755 // Try reading again after rewind
756 samples_read = ffmpeg_decoder_read_audio_samples(source->audio_decoder, buffer, num_samples);
757 }
758 }
759 }
760
761 // Unlock shared decoder
762 if (source->is_shared_decoder) {
763 mutex_unlock(&source->decoder_mutex);
764 }
765
766 return samples_read;
767 }
768
769 default:
770 return 0;
771 }
772}
773
775 if (!source) {
776 return false;
777 }
778
779 switch (source->type) {
782 return false; // Webcam/test don't have audio
783
786 return source->audio_decoder && ffmpeg_decoder_has_audio(source->audio_decoder);
787
788 default:
789 return false;
790 }
791}
792
793/* ============================================================================
794 * Playback Control
795 * ============================================================================ */
796
798 if (!source) {
799 return;
800 }
801
802 source->loop_enabled = loop;
803
804 if (loop && source->type == MEDIA_SOURCE_STDIN) {
805 log_warn("Loop mode not supported for stdin input (cannot seek)");
806 }
807}
808
810 if (!source) {
811 return true;
812 }
813
814 switch (source->type) {
817 return false; // Webcam never ends
818
821 if (!source->video_decoder) {
822 return true;
823 }
824 // If loop is enabled, we never truly reach end
825 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
826 return false;
827 }
828 if (source->audio_only)
829 return source->audio_decoder && ffmpeg_decoder_at_end(source->audio_decoder);
830 return ffmpeg_decoder_at_end(source->video_decoder);
831
832 default:
833 return true;
834 }
835}
836
838 ASCII_OTEL_SCOPE(MEDIA_SOURCE_REWIND);
839 if (!source) {
840 return ERROR_INVALID_PARAM;
841 }
842
843 switch (source->type) {
846 return ASCIICHAT_OK; // No-op for webcam
847
849 if (!source->video_decoder && !source->audio_decoder) {
850 return ERROR_INVALID_PARAM;
851 }
852
853 // Lock shared decoder if YouTube URL (protect against concurrent thread access)
854 if (source->is_shared_decoder) {
855 mutex_lock(&source->decoder_mutex);
856 }
857
858 // Rewind video decoder
859 asciichat_error_t video_result = source->video_decoder ? ffmpeg_decoder_rewind(source->video_decoder) : ASCIICHAT_OK;
860 if (video_result != ASCIICHAT_OK) {
861 if (source->is_shared_decoder) {
862 mutex_unlock(&source->decoder_mutex);
863 }
864 return video_result;
865 }
866
867 // For YouTube (shared decoder), don't rewind audio separately
868 // For local files (separate decoders), rewind audio too
870 if (!source->is_shared_decoder && source->audio_decoder) {
871 result = ffmpeg_decoder_rewind(source->audio_decoder);
872 }
873
874 // Unlock shared decoder
875 if (source->is_shared_decoder) {
876 mutex_unlock(&source->decoder_mutex);
877 }
878
879 return result;
880
882 return ERROR_NOT_SUPPORTED; // Cannot seek stdin
883
884 default:
885 return ERROR_INVALID_PARAM;
886 }
887}
888
890 ASCII_OTEL_SCOPE(MEDIA_SOURCE_SEEK);
891 if (!source) {
892 SET_ERRNO(ERROR_INVALID_PARAM, "Media source is NULL");
893 return ERROR_INVALID_PARAM;
894 }
895
896 if (timestamp_sec < 0.0) {
897 SET_ERRNO(ERROR_INVALID_PARAM, "Timestamp must be >= 0.0");
898 return ERROR_INVALID_PARAM;
899 }
900
901 // WEBCAM and TEST sources: no-op (always return OK)
902 if (source->type == MEDIA_SOURCE_WEBCAM || source->type == MEDIA_SOURCE_TEST) {
903 return ASCIICHAT_OK;
904 }
905
906 // STDIN: not supported
907 if (source->type == MEDIA_SOURCE_STDIN) {
908 SET_ERRNO(ERROR_NOT_SUPPORTED, "Cannot seek stdin");
909 return ERROR_NOT_SUPPORTED;
910 }
911
913
914 // Clear audio playback buffer BEFORE seeking to prevent old audio from being queued
915 // This ensures fresh audio starts playing immediately after seek completes
916 if (source->audio_ctx) {
917 audio_context_t *audio_ctx = (audio_context_t *)source->audio_ctx;
918 if (audio_ctx->playback_buffer) {
920 }
921 }
922
923 // The seeking_in_progress flag in decoders blocks prefetch thread
924 // seeking_in_progress coordinates with audio callback via condition variable
925
926 uint64_t seek_start_ns = time_get_ns();
927 if (source->video_decoder) {
928 double video_pos_before = ffmpeg_decoder_get_position(source->video_decoder);
929 asciichat_error_t video_err = ffmpeg_decoder_seek_to_timestamp(source->video_decoder, timestamp_sec);
930 double video_pos_after = ffmpeg_decoder_get_position(source->video_decoder);
931 uint64_t video_seek_ns = time_elapsed_ns(seek_start_ns, time_get_ns());
932 char video_seek_str[TIME_DURATION_BUFFER_SIZE];
933 time_pretty(video_seek_ns, -1, video_seek_str, sizeof(video_seek_str));
934 if (video_err != ASCIICHAT_OK) {
935 log_warn("Video seek to %.2f failed %s (took %s)", timestamp_sec, asciichat_error_format(NULL, video_err), video_seek_str);
936 result = video_err;
937 } else {
938 log_debug("Video SEEK: %.2f → %.2f sec (target %.2f, took %s)", video_pos_before, video_pos_after, timestamp_sec, video_seek_str);
939 }
940 }
941
942 // Seek audio decoder (if separate from video)
943 if (source->audio_decoder && !source->is_shared_decoder) {
944 log_debug("=== Starting audio seek to %.2f sec ===", timestamp_sec);
945 uint64_t audio_seek_start_ns = time_get_ns();
946 double audio_pos_before = ffmpeg_decoder_get_position(source->audio_decoder);
947 log_debug("Audio position before seek: %.2f", audio_pos_before);
948 asciichat_error_t audio_err = ffmpeg_decoder_seek_to_timestamp(source->audio_decoder, timestamp_sec);
949 double audio_pos_after = ffmpeg_decoder_get_position(source->audio_decoder);
950 uint64_t audio_seek_ns = time_elapsed_ns(audio_seek_start_ns, time_get_ns());
951 log_debug("Audio position after seek: %.2f", audio_pos_after);
952 char audio_seek_str[TIME_DURATION_BUFFER_SIZE];
953 time_pretty(audio_seek_ns, -1, audio_seek_str, sizeof(audio_seek_str));
954 if (audio_err != ASCIICHAT_OK) {
955 log_warn("Audio seek to %.2f failed %s (took %s)", timestamp_sec, asciichat_error_format(NULL, audio_err), audio_seek_str);
956 result = audio_err;
957 } else {
958 log_debug("Audio SEEK COMPLETE: %.2f → %.2f sec (target %.2f, took %s)", audio_pos_before, audio_pos_after, timestamp_sec, audio_seek_str);
959 }
960 }
961
962 // Prefetch thread automatically resumes when seeking_in_progress is cleared and signaled
963
964 return result;
965}
966
970
972 if (!source) {
973 return -1.0;
974 }
975
976 switch (source->type) {
979 return -1.0; // Infinite
980
983 if (!source->video_decoder) {
984 return -1.0;
985 }
986 return ffmpeg_decoder_get_duration(source->video_decoder);
987
988 default:
989 return -1.0;
990 }
991}
992
994 if (!source) {
995 return -1.0;
996 }
997
998 switch (source->type) {
1000 case MEDIA_SOURCE_TEST:
1001 return -1.0; // No position concept
1002
1003 case MEDIA_SOURCE_FILE:
1004 case MEDIA_SOURCE_STDIN:
1005 if (!source->video_decoder) {
1006 return -1.0;
1007 }
1008 return ffmpeg_decoder_get_position(source->audio_only ? source->audio_decoder : source->video_decoder);
1009
1010 default:
1011 return -1.0;
1012 }
1013}
1014
1016 if (!source) {
1017 return 0.0;
1018 }
1019
1020 switch (source->type) {
1022 return source->webcam_ctx ? webcam_get_fps(source->webcam_ctx) : 0.0;
1023 case MEDIA_SOURCE_TEST:
1024 return 0.0;
1025
1026 case MEDIA_SOURCE_FILE:
1027 case MEDIA_SOURCE_STDIN:
1028 if (!source->video_decoder) {
1029 return 0.0;
1030 }
1031 return ffmpeg_decoder_get_video_fps(source->video_decoder);
1032
1033 default:
1034 return 0.0;
1035 }
1036}
1037
1038/* ============================================================================
1039 * Pause/Resume Control
1040 * ============================================================================ */
1041
1043 if (!source) {
1044 return;
1045 }
1046 atomic_store_bool(&source->is_paused, true);
1047}
1048
1050 if (!source) {
1051 return;
1052 }
1053 atomic_store_bool(&source->is_paused, false);
1054}
1055
1057 if (!source) {
1058 return false;
1059 }
1060 return atomic_load_bool(&source->is_paused);
1061}
1062
1064 if (!source) {
1065 return;
1066 }
1067 bool paused = atomic_load_bool(&source->is_paused);
1068 while (!atomic_cas_bool(&source->is_paused, &paused, !paused)) {
1069 }
1070}
1071
1073 if (source) {
1074 source->audio_ctx = audio_ctx;
1075 }
1076}
1077
1078void media_source_set_exit_callback(media_source_t *source, bool (*should_exit_callback)(void *), void *user_data) {
1079 if (!source) {
1080 return;
1081 }
1082
1083 // Set exit callback on video decoder if present
1084 if (source->video_decoder) {
1085 ffmpeg_decoder_set_exit_callback(source->video_decoder, should_exit_callback, user_data);
1086 }
1087
1088 // Set exit callback on audio decoder if present (only if different from video decoder)
1089 if (source->audio_decoder && source->audio_decoder != source->video_decoder) {
1090 ffmpeg_decoder_set_exit_callback(source->audio_decoder, should_exit_callback, user_data);
1091 }
1092}
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)
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,...)
#define HAS_ERRNO(context)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.
Common buffer size definitions.
Application limits and constraints.
Named object registry for debugging — log identifiable resource names.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
🎞️ FFmpeg-based media decoder for video and audio streams
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
void audio_ring_buffer_clear(audio_ring_buffer_t *rb)
Clear all audio samples from ring buffer.
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_WEBCAM_IN_USE
Definition error_codes.h:64
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_MEDIA_OPEN
Definition error_codes.h:70
@ ERROR_WEBCAM
Definition error_codes.h:63
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73
#define MEDIA_STREAM_URL_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#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 ffmpeg_decoder_at_end(ffmpeg_decoder_t *decoder)
Check if decoder reached end of stream.
double ffmpeg_decoder_get_position(ffmpeg_decoder_t *decoder)
Get current playback position in seconds.
bool media_source_at_end(media_source_t *source)
Check if media source reached end of stream.
Definition source.c:809
image_t * ffmpeg_decoder_read_video_frame(ffmpeg_decoder_t *decoder)
bool ffmpeg_decoder_has_video(ffmpeg_decoder_t *decoder)
Check if decoder has video stream.
double ffmpeg_decoder_get_video_fps(ffmpeg_decoder_t *decoder)
Get video frame rate.
bool media_source_is_paused(media_source_t *source)
Check if media source is paused.
Definition source.c:1056
asciichat_error_t ffmpeg_decoder_rewind(ffmpeg_decoder_t *decoder)
Seek to beginning of media.
bool media_source_has_video(media_source_t *source)
Check if media source has video stream.
Definition source.c:674
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:697
media_source_type_t
Media source type enumeration.
Definition source.h:101
bool media_source_has_audio(media_source_t *source)
Check if media source has audio stream.
Definition source.c:774
double media_source_get_position(media_source_t *source)
Get current playback position in seconds.
Definition source.c:993
void media_source_destroy(media_source_t *source)
Destroy media source and free resources.
Definition source.c:486
void media_source_resume(media_source_t *source)
Resume media playback after pause.
Definition source.c:1049
double media_source_get_video_fps(media_source_t *source)
Get video frame rate in frames per second.
Definition source.c:1015
double media_source_get_duration(media_source_t *source)
Get media duration in seconds.
Definition source.c:971
bool ffmpeg_decoder_has_audio(ffmpeg_decoder_t *decoder)
Check if decoder has audio stream.
void media_source_pause(media_source_t *source)
Pause media playback.
Definition source.c:1042
image_t * media_source_read_video(media_source_t *source)
Read next video frame from media source.
Definition source.c:568
asciichat_error_t media_source_seek(media_source_t *source, double timestamp_sec)
Seek media source to timestamp.
Definition source.c:889
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:1078
media_source_type_t media_source_get_type(media_source_t *source)
Get media source type.
Definition source.c:967
asciichat_error_t ffmpeg_decoder_start_prefetch(ffmpeg_decoder_t *decoder)
Start the background frame prefetching thread.
void media_source_set_audio_context(media_source_t *source, void *audio_ctx)
Set audio context for playback buffer management.
Definition source.c:1072
asciichat_error_t ffmpeg_decoder_seek_to_timestamp(ffmpeg_decoder_t *decoder, double timestamp_sec)
Seek to specific timestamp in media.
media_source_t * media_source_create(media_source_type_t type, const char *path)
Create a new media source.
Definition source.c:211
void ffmpeg_decoder_set_exit_callback(ffmpeg_decoder_t *decoder, bool(*should_exit_callback)(void *), void *user_data)
Set exit signal callback for graceful shutdown during I/O.
void ffmpeg_decoder_destroy(ffmpeg_decoder_t *decoder)
Destroy FFmpeg decoder and free resources.
void media_source_toggle_pause(media_source_t *source)
Toggle pause state of media source.
Definition source.c:1063
asciichat_error_t media_source_rewind(media_source_t *source)
Rewind media source to beginning.
Definition source.c:837
size_t ffmpeg_decoder_read_audio_samples(ffmpeg_decoder_t *decoder, float *buffer, size_t num_samples)
Decode audio samples.
ffmpeg_decoder_t * ffmpeg_decoder_create_stdin(void)
Create FFmpeg decoder from stdin.
double ffmpeg_decoder_get_duration(ffmpeg_decoder_t *decoder)
Get media duration in seconds.
void media_source_set_loop(media_source_t *source, bool loop)
Enable or disable looping.
Definition source.c:797
@ 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
@ MEDIA_SOURCE_TEST
Test pattern generator.
Definition source.h:105
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#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:117
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1333
asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index)
Initialize webcam context for advanced operations.
struct webcam_context_t webcam_context_t
Opaque webcam context structure.
Definition webcam.h:157
image_t * webcam_read_context(webcam_context_t *ctx)
Capture a frame from webcam context.
void webcam_cleanup_context(webcam_context_t *ctx)
Clean up webcam context and release resources.
🔊 Audio Capture and Playback Interface for ascii-chat
ffmpeg_decoder_t * ffmpeg_decoder_create_with_request_options(const char *path, bool(*cancel)(void *), void *data, const char *headers, const char *cookies, const char *proxy)
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:749
#define NOTICE(severity, title,...)
Definition notice.h:56
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
static bool size_t index
Definition queries.h:8
#define MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE
Definition source.c:7
media_source_t * media_source_create_interruptible(media_source_type_t type, const char *path, bool(*cancel)(void *), void *data)
Definition source.c:215
bool media_source_uses_webcam(media_source_t *source)
Definition source.c:564
asciichat_error_t media_source_start_video(media_source_t *source)
Definition source.c:549
🎬 Unified media source abstraction for webcam, files, and stdin
int platform_strncasecmp(const char *s1, const char *s2, size_t n)
char * platform_strdup(const char *s)
🔤 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:76
When code needs to work with audio device info, it keeps index, max_input_channels,...
audio_ring_buffer_t * playback_buffer
OLD: Network → Worker (will become network_playback_rb).
FFmpeg decoder state for video and audio decoding.
Media source for video and audio capture.
Definition source.c:47
uint64_t test_start_ns
Monotonic animation origin.
Definition source.c:74
atomic_t is_paused
Independently published playback pause flag.
Definition source.c:51
bool audio_only
File audio uses the selected webcam for video.
Definition source.c:50
webcam_context_t * webcam_ctx
Webcam context (NULL for non-webcam types).
Definition source.c:54
bool is_shared_decoder
True if both streams share same decoder (YouTube URLs).
Definition source.c:60
char * file_path
File path (for FILE type).
Definition source.c:66
void * audio_ctx
Audio context for clearing buffers on seek (opaque).
Definition source.c:70
char * original_youtube_url
Original YouTube URL for re-extraction.
Definition source.c:67
media_source_type_t type
Type of media source (webcam, file, stdin, test).
Definition source.c:48
mutex_t decoder_mutex
Protects shared decoder access (YouTube URLs).
Definition source.c:63
unsigned short int webcam_index
Webcam device index.
Definition source.c:55
ffmpeg_decoder_t * audio_decoder
Audio decoder (separate or shared with video).
Definition source.c:59
test_pattern_t * test_pattern
Independent reusable synthetic renderer.
Definition source.c:73
ffmpeg_decoder_t * video_decoder
Video decoder (separate or shared with audio).
Definition source.c:58
bool loop_enabled
Whether to loop playback (for files).
Definition source.c:49
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...
char headers[YT_DLP_HEADERS_CAPACITY]
Definition yt_dlp.h:20
char cookies[YT_DLP_COOKIES_CAPACITY]
Definition yt_dlp.h:21
char proxy[YT_DLP_PROXY_CAPACITY]
Definition yt_dlp.h:22
⏱️ High-precision timing utilities using sokol_time.h and uthash
image_t * test_pattern_image(test_pattern_t *p)
asciichat_error_t test_pattern_render(test_pattern_t *p, int index, double time_ms, bool cadence)
asciichat_error_t test_pattern_create(int width, int height, test_pattern_t **out)
void test_pattern_destroy(test_pattern_t *p)
asciichat_error_t test_pattern_resize(test_pattern_t *p, int width, int height)
struct test_pattern test_pattern_t
double webcam_get_fps(webcam_context_t *ctx)
asciichat_error_t yt_dlp_extract_with_options(const char *url, const char *yt_dlp_options, char *output_url, size_t output_size, char *audio_url, size_t audio_size, yt_dlp_request_options_t *video_request, yt_dlp_request_options_t *audio_request, bool(*cancel)(void *), void *data)
Definition yt_dlp.c:361
yt-dlp stream URL extraction