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 File Reference

Unified media source implementation. More...

Go to the source code of this file.

Data Structures

struct  media_source_t
 Media source for video and audio capture. More...

Macros

#define MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE   64

Functions

media_source_t * media_source_create (media_source_type_t type, const char *path)
 Create a new media source.
media_source_t * media_source_create_interruptible (media_source_type_t type, const char *path, bool(*cancel)(void *), void *data)
void media_source_destroy (media_source_t *source)
 Destroy media source and free resources.
asciichat_error_t media_source_start_video (media_source_t *source)
bool media_source_uses_webcam (media_source_t *source)
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.
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_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.
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.

Detailed Description

Unified media source implementation.

Definition in file source.c.

Macro Definition Documentation

◆ MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE

#define MEDIA_SOURCE_MEDIA_TYPE_BUFFER_SIZE   64

Definition at line 7 of file source.c.

Referenced by media_source_create_interruptible().

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 215 of file source.c.

215 {
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}
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:70
@ ERROR_WEBCAM
Definition error_codes.h:63
#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_debug(...)
Log a DEBUG message.
Definition log/log.h:589
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: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
#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.
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:56
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
static bool size_t index
Definition queries.h:8
#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:47
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

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 549 of file source.c.

549 {
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}
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
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 564 of file source.c.

564 {
565 return source && ((source->type == MEDIA_SOURCE_WEBCAM && !GET_OPTION(test_pattern)) || (source->audio_only && !GET_OPTION(test_pattern)));
566}

References GET_OPTION, MEDIA_SOURCE_WEBCAM, and source.