ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
source.h File Reference

🎬 Unified media source abstraction for webcam, files, and stdin More...

Go to the source code of this file.

Typedefs

typedef struct media_source_t media_source_t
 Opaque media source handle.

Enumerations

enum  media_source_type_t { MEDIA_SOURCE_WEBCAM , MEDIA_SOURCE_FILE , MEDIA_SOURCE_STDIN , MEDIA_SOURCE_TEST }
 Media source type enumeration. More...

Functions

media_source_t * media_source_create (media_source_type_t type, const char *path)
 Create a new media source.
void media_source_destroy (media_source_t *source)
 Destroy media source and free resources.
image_t * media_source_read_video (media_source_t *source)
 Read next video frame from media source.
bool media_source_has_video (media_source_t *source)
 Check if media source has video stream.
size_t media_source_read_audio (media_source_t *source, float *buffer, size_t num_samples)
 Read audio samples from media source.
bool media_source_has_audio (media_source_t *source)
 Check if media source has audio stream.
void media_source_set_loop (media_source_t *source, bool loop)
 Enable or disable looping.
void media_source_pause (media_source_t *source)
 Pause media playback.
void media_source_resume (media_source_t *source)
 Resume media playback after pause.
bool media_source_is_paused (media_source_t *source)
 Check if media source is paused.
void media_source_toggle_pause (media_source_t *source)
 Toggle pause state of media source.
bool media_source_at_end (media_source_t *source)
 Check if media source reached end of stream.
asciichat_error_t media_source_rewind (media_source_t *source)
 Rewind media source to beginning.
asciichat_error_t media_source_seek (media_source_t *source, double timestamp_sec)
 Seek media source to timestamp.
media_source_type_t media_source_get_type (media_source_t *source)
 Get media source type.
double media_source_get_duration (media_source_t *source)
 Get media duration in seconds.
double media_source_get_position (media_source_t *source)
 Get current playback position in seconds.
double media_source_get_video_fps (media_source_t *source)
 Get video frame rate in frames per second.
void media_source_set_audio_context (media_source_t *source, void *audio_ctx)
 Set audio context for playback buffer management.
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.
bool media_source_uses_webcam (media_source_t *source)
asciichat_error_t media_source_start_video (media_source_t *source)
media_source_t * media_source_create_interruptible (media_source_type_t type, const char *path, bool(*cancel)(void *), void *data)

Detailed Description

🎬 Unified media source abstraction for webcam, files, and stdin

Definition in file source.h.

Function Documentation

◆ media_source_create_interruptible()

media_source_t * media_source_create_interruptible ( media_source_type_t type,
const char * path,
bool(* cancel )(void *),
void * data )

Definition at line 248 of file source.c.

251 {
252 ASCII_OTEL_SCOPE(MEDIA_SOURCE_CREATE_INTERRUPTIBLE);
255 if (!source) {
256 SET_ERRNO(ERROR_MEMORY, "Failed to allocate media source");
257 return NULL;
258 }
259
260 memset(source, 0, sizeof(*source));
261 source->type = type;
262 source->loop_enabled = false;
263 atomic_store_bool(&source->is_paused, false);
264
265 // Initialize mutex for protecting shared decoder access (for YouTube URLs)
266 if (mutex_init(&source->decoder_mutex, "media_decoder") != 0) {
267 SET_ERRNO(ERROR_MEMORY, "Failed to initialize mutex");
269 return NULL;
270 }
271
272 switch (type) {
273 case MEDIA_SOURCE_WEBCAM: {
274 // Parse webcam index from path (if provided)
275 unsigned short int index = 0;
276 if (path) {
277 char *endptr;
278 errno = 0;
279 long parsed = strtol(path, &endptr, 10);
280 if (*endptr == '\0' && errno == 0 && parsed >= 0 && parsed <= USHRT_MAX) {
281 index = (unsigned short int)parsed;
282 } else if (*endptr != '\0' || errno != 0) {
283 log_error("Invalid webcam index: %s", path);
284 }
285 }
286
287 source->webcam_index = index;
288 if (GET_OPTION(waveform) || GET_OPTION(fft))
289 break;
290 asciichat_error_t webcam_error =
291 webcam_init_context(&source->webcam_ctx, index);
292 if (webcam_error != ASCIICHAT_OK) {
293 asciichat_error_context_t webcam_context;
294 bool has_webcam_context = HAS_ERRNO(&webcam_context);
295 // Webcam init failed - log and cleanup
296 NOTICE(WARNING, "CAMERA UNAVAILABLE",
297 "Failed to initialize webcam device %u: %s", index,
299 has_webcam_context ? webcam_context.context_message : NULL,
300 webcam_error));
301 // Destroy mutexes before freeing source
302 mutex_destroy(&source->decoder_mutex);
304
305 // Add media-level context while preserving the webcam failure as its
306 // cause.
307 if (webcam_error == ERROR_WEBCAM_IN_USE) {
308 SET_ERRNO(ERROR_WEBCAM_IN_USE, "Webcam device %u is in use", index);
309 } else {
310 SET_ERRNO(ERROR_WEBCAM, "Failed to initialize webcam device %u", index);
311 }
312 return NULL;
313 }
314
315 log_debug("Media source: Webcam device %u", index);
316 break;
317 }
318
319 case MEDIA_SOURCE_FILE: {
321 if (!path || path[0] == '\0') {
322 SET_ERRNO(ERROR_INVALID_PARAM, "File path is required for FILE source");
323 // Destroy mutexes before freeing source
324 mutex_destroy(&source->decoder_mutex);
326 return NULL;
327 }
328
329 // Resolve URL using smart FFmpeg/yt-dlp routing
330 const char *effective_path = path;
331 char resolved_url[MEDIA_STREAM_URL_SIZE] = {0};
332 char resolved_audio_url[MEDIA_STREAM_URL_SIZE] = {0};
333 yt_dlp_request_options_t video_request = {0}, audio_request = {0};
334 const char *yt_dlp_options = GET_OPTION(yt_dlp_options);
335
336 log_debug("Resolving URL: %s", path);
337 asciichat_error_t resolve_err = media_source_resolve_url(
338 path, yt_dlp_options, resolved_url, sizeof(resolved_url),
339 resolved_audio_url, sizeof(resolved_audio_url), &video_request,
340 &audio_request, cancel, data);
341 if (resolve_err != ASCIICHAT_OK) {
342 log_debug("Failed to resolve URL %s",
343 asciichat_error_format(NULL, resolve_err));
344 // Destroy mutexes before freeing source
345 mutex_destroy(&source->decoder_mutex);
347 return NULL;
348 }
349 if (cancel && cancel(data)) {
350 mutex_destroy(&source->decoder_mutex);
352 return NULL;
353 }
354 effective_path = resolved_url;
355 log_debug("Using resolved URL for playback");
356
357 // Store original URL for potential re-extraction if needed
358 source->original_youtube_url = platform_strdup(path);
359 if (!source->original_youtube_url) {
360 log_warn("Failed to cache original URL");
361 }
362
363 // Cache file path for potential reopen on loop
364 source->file_path = platform_strdup(effective_path);
365 if (!source->file_path) {
366 SET_ERRNO(ERROR_MEMORY, "Failed to duplicate file path");
367 SAFE_FREE(source->original_youtube_url);
368 // Destroy mutexes before freeing source
369 mutex_destroy(&source->decoder_mutex);
371 return NULL;
372 }
373
374 // Always use separate decoders for video and audio
375 // This allows independent read rates and avoids lock contention
378 effective_path, cancel, data, video_request.headers,
379 video_request.cookies,
380 video_request.proxy_specified ? video_request.proxy : NULL);
381 if (!source->video_decoder) {
382 SET_ERRNO(
384 "Media initialization failed: video decoder could not open input");
385 if (!cancel)
386 NOTICE(WARNING, "MEDIA COULD NOT BE OPENED",
387 "Failed to open media file for video: %s: %s", effective_path,
389 LOG_ERRNO_IF_SET("Media initialization failed");
390 SAFE_FREE(source->file_path);
391 SAFE_FREE(source->original_youtube_url);
392 // Destroy mutexes before freeing source
393 mutex_destroy(&source->decoder_mutex);
395 return NULL;
396 }
397
398 ASSERT_NO_ERRNO_SINCE(decoder_scope);
399
400 decoder_scope = errno_checkpoint();
401 const char *audio_path =
402 resolved_audio_url[0] ? resolved_audio_url : effective_path;
403 const yt_dlp_request_options_t *audio_settings =
404 resolved_audio_url[0] ? &audio_request : &video_request;
406 audio_path, cancel, data, audio_settings->headers,
407 audio_settings->cookies,
408 audio_settings->proxy_specified ? audio_settings->proxy : NULL);
409 if (!source->audio_decoder) {
410 SET_ERRNO(
412 "Media initialization failed: audio decoder could not open input");
413 LOG_ERRNO_IF_SET("Media initialization failed");
414 ffmpeg_decoder_destroy(source->video_decoder);
415 source->video_decoder = NULL;
416 SAFE_FREE(source->file_path);
417 SAFE_FREE(source->original_youtube_url);
418 // Destroy mutexes before freeing source
419 mutex_destroy(&source->decoder_mutex);
421 return NULL;
422 }
423 source->is_shared_decoder = false;
424
425 ASSERT_NO_ERRNO_SINCE(decoder_scope);
426 // yt-dlp emits selected formats in selector order, which may be audio
427 // first.
428 if (resolved_audio_url[0] &&
429 !ffmpeg_decoder_has_video(source->video_decoder) &&
430 ffmpeg_decoder_has_video(source->audio_decoder) &&
431 ffmpeg_decoder_has_audio(source->video_decoder)) {
432 ffmpeg_decoder_t *audio = source->video_decoder;
433 source->video_decoder = source->audio_decoder;
434 source->audio_decoder = audio;
435 }
436
437 // Start prefetch after choosing the decoder that actually contains video.
439 asciichat_error_t prefetch_err =
440 ffmpeg_decoder_has_video(source->video_decoder)
441 ? ffmpeg_decoder_start_prefetch(source->video_decoder)
442 : ASCIICHAT_OK;
443 if (prefetch_err != ASCIICHAT_OK) {
444 log_error("Failed to start video prefetch thread: %s",
445 asciichat_error_format(NULL, prefetch_err));
446 ffmpeg_decoder_destroy(source->video_decoder);
447 ffmpeg_decoder_destroy(source->audio_decoder);
448 SAFE_FREE(source->file_path);
449 SAFE_FREE(source->original_youtube_url);
450 mutex_destroy(&source->decoder_mutex);
452 return NULL;
453 }
454 ASSERT_NO_ERRNO_SINCE(prefetch_scope);
456 // Both decoders succeeded: failed extraction/prefetch attempts are
457 // resolved.
459 ASSERT_NO_ERRNO_SINCE(media_scope);
460 log_debug(
461 "Media source: URL resolved to stream (separate video/audio decoders)");
462 break;
463 }
464
465 case MEDIA_SOURCE_STDIN: {
466 // Create separate decoders for video and audio from stdin
467 source->video_decoder = ffmpeg_decoder_create_stdin();
468 if (!source->video_decoder) {
469 log_error("Failed to open stdin for video input");
470 // Destroy mutexes before freeing source
471 mutex_destroy(&source->decoder_mutex);
473 return NULL;
474 }
475
476 // Start prefetch thread for stdin video frames
478 asciichat_error_t prefetch_err =
479 ffmpeg_decoder_has_video(source->video_decoder)
480 ? ffmpeg_decoder_start_prefetch(source->video_decoder)
481 : ASCIICHAT_OK;
482 if (prefetch_err != ASCIICHAT_OK) {
483 log_error("Failed to start stdin video prefetch thread: %s",
484 asciichat_error_format(NULL, prefetch_err));
485 ffmpeg_decoder_destroy(source->video_decoder);
486 SAFE_FREE(source->file_path);
487 SAFE_FREE(source->original_youtube_url);
488 mutex_destroy(&source->decoder_mutex);
490 return NULL;
491 }
492
493 ASSERT_NO_ERRNO_SINCE(prefetch_scope);
495 source->audio_decoder = ffmpeg_decoder_create_stdin();
496 if (!source->audio_decoder) {
497 log_error("Failed to open stdin for audio input");
498 ffmpeg_decoder_destroy(source->video_decoder);
499 source->video_decoder = NULL;
500 // Destroy mutexes before freeing source
501 mutex_destroy(&source->decoder_mutex);
503 return NULL;
504 }
505
506 log_debug("Media source: stdin (separate video/audio decoders)");
507 break;
508 }
509
510 case MEDIA_SOURCE_TEST: {
511 // Test pattern state is encapsulated in media_source_t
512 source->webcam_index = 0;
513 source->webcam_ctx = NULL; // No context needed for test pattern
514 source->test_pattern = NULL;
515 source->test_start_ns = 0;
516
517 log_debug("Media source: Test pattern");
518 break;
519 }
520
521 default:
522 SET_ERRNO(ERROR_INVALID_PARAM, "Unknown media source type: %d", type);
523 // Destroy mutexes before freeing source
524 mutex_destroy(&source->decoder_mutex);
526 return NULL;
527 }
528
529 if ((type == MEDIA_SOURCE_FILE || type == MEDIA_SOURCE_STDIN) &&
530 !ffmpeg_decoder_has_video(source->video_decoder) &&
531 ffmpeg_decoder_has_audio(source->audio_decoder)) {
532 source->audio_only = true;
533 }
534
535 /* Register media source with named registry */
536 char media_type_str[MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE];
537 switch (type) {
539 snprintf(media_type_str, sizeof(media_type_str), "media_source:webcam");
540 break;
542 snprintf(media_type_str, sizeof(media_type_str), "media_source:file");
543 break;
545 snprintf(media_type_str, sizeof(media_type_str), "media_source:test");
546 break;
547 default:
548 snprintf(media_type_str, sizeof(media_type_str), "media_source:unknown");
549 break;
550 }
551 NAMED_REGISTER(source, media_type_str, "media_source_t", "0x%tx", NULL);
552
553 /* Register media source's sync primitives with hierarchical naming */
554 NAMED_REGISTER_MUTEX(&source->decoder_mutex, "decoder_mutex",
555 (uintptr_t)(const void *)(source));
556 NAMED_REGISTER_ATOMIC(&source->is_paused, "media_paused", source);
557
558 return source;
559}
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)
#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.
audio_visualization_source_t source
Definition fft.c:25
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#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_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:71
@ ERROR_WEBCAM
Definition error_codes.h:63
#define MEDIA_STREAM_URL_SIZE
#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_debug(...)
Log a DEBUG message.
Definition log/log.h:565
bool ffmpeg_decoder_has_video(ffmpeg_decoder_t *decoder)
Check if decoder has video stream.
bool ffmpeg_decoder_has_audio(ffmpeg_decoder_t *decoder)
Check if decoder has audio stream.
asciichat_error_t ffmpeg_decoder_start_prefetch(ffmpeg_decoder_t *decoder)
Start the background frame prefetching thread.
void ffmpeg_decoder_destroy(ffmpeg_decoder_t *decoder)
Destroy FFmpeg decoder and free resources.
ffmpeg_decoder_t * ffmpeg_decoder_create_stdin(void)
Create FFmpeg decoder from stdin.
@ 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 GET_OPTION(field)
Definition options.h:1339
asciichat_error_t webcam_init_context(webcam_context_t **ctx, unsigned short int device_index)
Initialize webcam context for advanced operations.
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)
#define NOTICE(severity, title,...)
Definition notice.h:86
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
static bool size_t index
Definition queries.h:10
#define MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE
Definition source.c:7
char * platform_strdup(const char *s)
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
FFmpeg decoder state for video and audio decoding.
Media source for video and audio capture.
Definition source.c:48
char headers[YT_DLP_HEADERS_CAPACITY]
Definition yt_dlp.h:24
char cookies[YT_DLP_COOKIES_CAPACITY]
Definition yt_dlp.h:25
char proxy[YT_DLP_PROXY_CAPACITY]
Definition yt_dlp.h:26

References ASCII_OTEL_SCOPE, ASCIICHAT_ERRNO_DISMISSED, ASCIICHAT_ERRNO_HANDLED, asciichat_error_format(), ASCIICHAT_OK, ASSERT_NO_ERRNO_SINCE, atomic_store_bool(), asciichat_error_context_t::context_message, yt_dlp_request_options_t::cookies, errno_checkpoint(), errno_scope_begin(), errno_scope_end(), ERROR_INVALID_PARAM, ERROR_MEDIA_OPEN, ERROR_MEMORY, ERROR_WEBCAM, ERROR_WEBCAM_IN_USE, ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), ffmpeg_decoder_destroy(), ffmpeg_decoder_has_audio(), ffmpeg_decoder_has_video(), ffmpeg_decoder_start_prefetch(), GET_OPTION, HAS_ERRNO, yt_dlp_request_options_t::headers, index, log_debug, LOG_ERRNO_IF_SET, log_error, log_warn, MEDIA_SOURCE_FILE, MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, MEDIA_STREAM_URL_SIZE, NAMED_REGISTER, NAMED_REGISTER_ATOMIC, NAMED_REGISTER_MUTEX, NOTICE, platform_strdup(), yt_dlp_request_options_t::proxy, yt_dlp_request_options_t::proxy_specified, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, source, and webcam_init_context().

Referenced by media_source_create(), and session_capture_create().

◆ media_source_start_video()

asciichat_error_t media_source_start_video ( media_source_t * source)

Definition at line 629 of file source.c.

629 {
630 ASCII_OTEL_SCOPE(MEDIA_SOURCE_START_VIDEO);
631 if (!source)
632 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing media source");
633 if ((!source->audio_only && source->type != MEDIA_SOURCE_WEBCAM) ||
634 source->webcam_ctx || GET_OPTION(test_pattern))
635 return ASCIICHAT_OK;
636 if (source->type != MEDIA_SOURCE_WEBCAM)
637 source->webcam_index = (unsigned short)GET_OPTION(webcam_index);
639 webcam_init_context(&source->webcam_ctx, source->webcam_index);
640 if (err != ASCIICHAT_OK)
641 return SET_ERRNO(err, "Audio-only media requires webcam %u",
642 source->webcam_index);
643 log_info("Audio-only media: using webcam %u for video", source->webcam_index);
644 return ASCIICHAT_OK;
645}
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ERROR_INVALID_PARAM, GET_OPTION, log_info, MEDIA_SOURCE_WEBCAM, SET_ERRNO, source, and webcam_init_context().

Referenced by media_source_read_video(), and session_capture_create().

◆ media_source_uses_webcam()

bool media_source_uses_webcam ( media_source_t * source)

Definition at line 647 of file source.c.

647 {
648 return source &&
650 (source->audio_only && !GET_OPTION(test_pattern)));
651}

References GET_OPTION, MEDIA_SOURCE_WEBCAM, and source.