ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
media/ffmpeg_decoder.c
Go to the documentation of this file.
1
5
6/* Storage capacities in elements; text buffers include the terminating NUL. */
7#define MEDIA_FFMPEG_DECODER_DECODER_NAME_BUFFER_SIZE 256
8
10#include <ascii-chat/common.h>
12#include <ascii-chat/log/io.h>
13#include <ascii-chat/log/log.h>
15#include <ascii-chat/otel.h>
17#include <ascii-chat/util/url.h>
19#include <libplatform/atomic.h>
20#include <libplatform/cond.h>
21#include <libplatform/mutex.h>
22#include <libplatform/system.h>
23#include <libplatform/thread.h>
24#include <options/options.h>
25#include <util/string.h>
26
27#include <inttypes.h>
28#include <libavcodec/avcodec.h>
29#include <libavformat/avformat.h>
30#include <libavutil/imgutils.h>
31#include <libavutil/log.h>
32#include <libavutil/opt.h>
33#include <libswresample/swresample.h>
34#include <libswscale/swscale.h>
35#include <string.h>
36
37/* ============================================================================
38 * FFmpeg Logging Suppression
39 * ============================================================================
40 */
41
54static void ffmpeg_silent_log_callback(void *avcl, int level, const char *fmt,
55 va_list vl) {
56 (void)avcl; // unused
57 (void)level; // unused
58 (void)fmt; // unused
59 (void)vl; // unused
60 // Do nothing - silently discard all FFmpeg logs
61}
62
63/* ============================================================================
64 * Constants
65 * ============================================================================
66 */
67
69#define TARGET_SAMPLE_RATE 48000
70
72#define TARGET_CHANNELS 2
73
75#define AVIO_BUFFER_SIZE (64 * 1024)
76
77/* ============================================================================
78 * FFmpeg Decoder Structure
79 * ============================================================================
80 */
81
89 // Format context
90 AVFormatContext *format_ctx;
91
92 // Video stream
93 AVCodecContext *video_codec_ctx;
95 struct SwsContext *sws_ctx;
96
97 // Audio stream
98 AVCodecContext *audio_codec_ctx;
100 struct SwrContext *swr_ctx;
101
102 // Frame and packet buffers
103 AVFrame *frame;
104 AVPacket *packet;
105
106 // Decoded image cache - double-buffered for prefetching
108
109 // Audio sample buffer (for partial frame handling)
113
114 // Background thread for frame prefetching (reduces YouTube HTTP blocking)
115 platform_thread_t prefetch_thread;
119 _Atomic bool
122 _Atomic bool prefetch_failed;
124 _Atomic bool prefetch_should_stop;
125 _Atomic bool
127 _Atomic uint64_t
133
134 // Track which buffer is being read by main thread
141
142 // State flags
144 bool is_stdin;
146
147 // Stdin I/O context
148 AVIOContext *avio_ctx;
149 unsigned char *avio_buffer;
150
151 // Position tracking
154
155 // Sample-based position tracking
158
159 // Exit signal callback (for graceful shutdown during blocking I/O)
162};
163
164/* ============================================================================
165 * Stdin I/O Callbacks
166 * ============================================================================
167 */
168
169/* ============================================================================
170 * Memory-based AVIO for stdin buffering
171 * ============================================================================
172 */
173
177typedef struct {
179 size_t size;
181
189
193static int memory_read_packet(void *opaque, uint8_t *buf, int buf_size) {
195
196 if (!reader || !reader->buffer || reader->pos >= reader->buffer->size)
197 return AVERROR_EOF;
198
199 int to_read = buf_size;
200 if (reader->pos + to_read > reader->buffer->size)
201 to_read = (int)(reader->buffer->size - reader->pos);
202
203 memcpy(buf, reader->buffer->data + reader->pos, to_read);
204 reader->pos += to_read;
205
206 return to_read;
207}
208
212static int64_t memory_seek_packet(void *opaque, int64_t offset, int whence) {
214
215 if (!reader || !reader->buffer)
216 return -1;
217
218 int64_t new_pos = 0;
219 if (whence == SEEK_SET) {
220 new_pos = offset;
221 } else if (whence == SEEK_CUR) {
222 new_pos = (int64_t)reader->pos + offset;
223 } else if (whence == SEEK_END) {
224 new_pos = (int64_t)reader->buffer->size + offset;
225 } else {
226 return -1;
227 }
228
229 if (new_pos < 0 || new_pos > (int64_t)reader->buffer->size)
230 return -1;
231
232 reader->pos = (size_t)new_pos;
233 return new_pos;
234}
235
240static stdin_buffer_t *stdin_buffer_read_all(void) {
242 if (!sb)
243 return NULL;
244
245 sb->data = NULL;
246 sb->size = 0;
247
248 // Read stdin in 64KB chunks
249 enum { chunk_size = 65536 };
250 uint8_t chunk_buffer[chunk_size];
251 size_t total_capacity = 0;
252 int chunk_count = 0;
253
254 while (1) {
255 size_t bytes_read = fread(chunk_buffer, 1, chunk_size, stdin);
256 if (bytes_read == 0)
257 break;
258 chunk_count++;
259
260 // Grow buffer if needed
261 if (sb->size + bytes_read > total_capacity) {
262 total_capacity = (sb->size + bytes_read) * 2; // Always double capacity
263 uint8_t *new_data = SAFE_MALLOC(total_capacity, uint8_t *);
264 if (!new_data) {
265 SAFE_FREE(sb->data);
266 SAFE_FREE(sb);
267 return NULL;
268 }
269 if (sb->data) {
270 memcpy(new_data, sb->data, sb->size);
271 SAFE_FREE(sb->data);
272 }
273 sb->data = new_data;
274 }
275
276 // Copy chunk to buffer
277 memcpy(sb->data + sb->size, chunk_buffer, bytes_read);
278 sb->size += bytes_read;
279 }
280
281 log_debug("Buffered stdin: %zu bytes in %d chunks (capacity: %zu)", sb->size,
282 chunk_count, total_capacity);
283 if (sb->size > 0) {
284 log_info(" First 16 bytes of stdin: %02x %02x %02x %02x %02x %02x %02x "
285 "%02x %02x %02x %02x %02x %02x %02x %02x %02x",
286 sb->data[0], sb->data[1], sb->data[2], sb->data[3], sb->data[4],
287 sb->data[5], sb->data[6], sb->data[7], sb->data[8], sb->data[9],
288 sb->data[10], sb->data[11], sb->data[12], sb->data[13],
289 sb->data[14], sb->data[15]);
290 }
291 return sb;
292}
293
297static stdin_buffer_t *g_stdin_buffer = NULL;
298
299/* ============================================================================
300 * Helper Functions
301 * ============================================================================
302 */
303
307static inline double av_q2d_safe(AVRational r) {
308 return (r.den != 0) ? ((double)r.num / (double)r.den) : 0.0;
309}
310
314static double get_frame_pts_seconds(AVFrame *frame, AVRational time_base) {
315 if (frame->pts == AV_NOPTS_VALUE) {
316 return -1.0;
317 }
318 return (double)frame->pts * av_q2d_safe(time_base);
319}
320
328static int ffmpeg_interrupt_callback(void *opaque) {
329 ffmpeg_decoder_t *decoder = (ffmpeg_decoder_t *)opaque;
330 if (!decoder) {
331 return 0;
332 }
333
334 // Interrupt traced_packet_read() if a seek is in progress
335 if (decoder->seeking_in_progress) {
336 return 1;
337 }
338
339 // Interrupt traced_packet_read() if application is shutting down
340 // This allows Ctrl+C to abort blocking I/O operations like YouTube HTTP
341 // requests
342 bool (*cancel)(void *) =
343 (bool (*)(void *))atomic_ptr_load(&decoder->should_exit_callback);
344 void *data = atomic_ptr_load(&decoder->exit_callback_user_data);
345 if (cancel && cancel(data)) {
346 return 1;
347 }
348
349 return 0;
350}
351
359
360static void ffmpeg_otel_result(int result, bool streaming) {
361 // EOF, buffering and application cancellation are expected control flow.
362 if (result < 0 && result != AVERROR_EXIT &&
363 !(streaming && (result == AVERROR_EOF || result == AVERROR(EAGAIN))))
364 gotel_current_error("ffmpeg.error", "FFmpeg operation failed");
365}
366
367static int traced_format_open(AVFormatContext **format, const char *path,
368 const AVInputFormat *input,
369 AVDictionary **options) {
370 ASCII_OTEL_SCOPE(FFMPEG_FORMAT_OPEN);
371 ASCII_OTEL_ATTR_STRING("media.source.kind", !path ? "stdin"
372 : strstr(path, "://") ? "network"
373 : "file");
374 int result = avformat_open_input(format, path, input, options);
375 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
376 ffmpeg_otel_result(result, false);
377 return result;
378}
379static int traced_format_probe(AVFormatContext *format,
380 AVDictionary **options) {
381 ASCII_OTEL_SCOPE(FFMPEG_PROBE);
382 int result = avformat_find_stream_info(format, options);
383 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
384 if (result >= 0 && format->iformat)
385 ASCII_OTEL_ATTR_STRING("media.container", format->iformat->name);
386 ffmpeg_otel_result(result, false);
387 return result;
388}
389static int traced_packet_read(AVFormatContext *format, AVPacket *packet) {
390 ASCII_OTEL_SCOPE(FFMPEG_PACKET_READ);
391 int result = av_read_frame(format, packet);
392 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
393 if (result >= 0)
394 ASCII_OTEL_ATTR_INT("media.packet.size", packet->size);
395 ffmpeg_otel_result(result, true);
396 return result;
397}
398static int traced_packet_send(AVCodecContext *codec, const AVPacket *packet) {
399 ASCII_OTEL_SCOPE(FFMPEG_PACKET_SEND);
400 ASCII_OTEL_ATTR_STRING("media.type", codec->codec_type == AVMEDIA_TYPE_AUDIO
401 ? "audio"
402 : "video");
403 ASCII_OTEL_ATTR_STRING("media.codec", avcodec_get_name(codec->codec_id));
404 ASCII_OTEL_ATTR_INT("media.decoder.draining", packet == NULL);
405 int result = avcodec_send_packet(codec, packet);
406 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
407 ffmpeg_otel_result(result, true);
408 return result;
409}
410static int traced_frame_receive(AVCodecContext *codec, AVFrame *frame) {
411 ASCII_OTEL_SCOPE(FFMPEG_FRAME_RECEIVE);
412 ASCII_OTEL_ATTR_STRING("media.type", codec->codec_type == AVMEDIA_TYPE_AUDIO
413 ? "audio"
414 : "video");
415 int result = avcodec_receive_frame(codec, frame);
416 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
417 ffmpeg_otel_result(result, true);
418 return result;
419}
420static int traced_video_scale(struct SwsContext *context,
421 const uint8_t *const data[], const int stride[],
422 int start, int height, uint8_t *const output[],
423 const int output_stride[]) {
424 ASCII_OTEL_SCOPE(FFMPEG_SCALE);
425 ASCII_OTEL_ATTR_INT("video.frame.height", height);
426 int result =
427 sws_scale(context, data, stride, start, height, output, output_stride);
428 ASCII_OTEL_ATTR_INT("ffmpeg.result", result);
429 ffmpeg_otel_result(result, false);
430 return result;
431}
432static int traced_audio_resample(struct SwrContext *context, uint8_t **output,
433 int capacity, const uint8_t **input,
434 int samples) {
435 ASCII_OTEL_SCOPE(FFMPEG_RESAMPLE);
436 ASCII_OTEL_ATTR_INT("audio.input.samples", samples);
437 int result = swr_convert(context, output, capacity, input, samples);
438 ASCII_OTEL_ATTR_INT("audio.output.samples", result > 0 ? result : 0);
439 ffmpeg_otel_result(result, false);
440 return result;
441}
442
443static void *ffmpeg_decoder_prefetch_thread_func(void *arg) {
444 ffmpeg_decoder_t *decoder = (ffmpeg_decoder_t *)arg;
445 if (!decoder || !decoder->prefetch_image_a || !decoder->prefetch_image_b) {
446 return NULL;
447 }
448
449 log_debug("Video prefetch thread started");
450 bool use_image_a = true; // Track which buffer we're using (critical for
451 // correct buffer swapping)
452
453 mutex_lock(&decoder->prefetch_mutex);
454 while (true) {
455
456 // The consumer releases the previous image and wakes us when taking the
457 // next frame. Seek completion and shutdown also signal this condition.
458 while (!decoder->prefetch_should_stop &&
459 (atomic_load_bool(&decoder->eof_reached) ||
460 decoder->seeking_in_progress || decoder->prefetch_frame_ready ||
461 (decoder->buffer_a_in_use && decoder->buffer_b_in_use)))
462 cond_wait(&decoder->prefetch_cond, &decoder->prefetch_mutex);
463 if (decoder->prefetch_should_stop) {
464 break;
465 }
466
467 use_image_a = !decoder->buffer_a_in_use;
468 uint64_t generation = decoder->seek_generation;
469 uint64_t read_start_ns = time_get_ns();
470 bool frame_decoded = false;
471 bool reached_eof = false;
472 bool packet_rejected = false;
474
475 // Release prefetch mutex but hold read_frame_mutex to prevent concurrent
476 // traced_packet_read() calls from audio thread
477 mutex_unlock(&decoder->prefetch_mutex);
478 mutex_lock(&decoder->read_frame_mutex);
479 if (generation != decoder->seek_generation ||
480 decoder->seeking_in_progress) {
481 mutex_unlock(&decoder->read_frame_mutex);
482 mutex_lock(&decoder->prefetch_mutex);
483 continue;
484 }
485 // Interrupted reads are expected. Publish a failure only after deciding
486 // whether this attempt was cancelled or superseded by a seek.
487 bool notifications_suppressed = errno_notifications_suppress(true);
488
489 ASCII_OTEL_SCOPE(FFMPEG_VIDEO_DECODE);
491 "media.codec", avcodec_get_name(decoder->video_codec_ctx->codec_id));
492 int decode_result = 0;
493 // Read packets until we get a video frame - read_frame_mutex HELD
494 while (true) {
495 int ret;
496 if (decoder->video_draining) {
497 ret = decode_result =
498 traced_frame_receive(decoder->video_codec_ctx, decoder->frame);
499 if (ret == AVERROR_EOF) {
500 atomic_store_bool(&decoder->eof_reached, true);
501 reached_eof = true;
502 break;
503 }
504 if (ret < 0) {
505 break;
506 }
507 } else {
508 ret = decode_result =
509 traced_packet_read(decoder->format_ctx, decoder->packet);
510 if (ret < 0) {
511 if (ret != AVERROR_EOF) {
512 break;
513 }
514
515 ret = decode_result =
516 traced_packet_send(decoder->video_codec_ctx, NULL);
517 decoder->video_draining = true;
518 if (ret < 0 && ret != AVERROR_EOF) {
519 break;
520 }
521
522 ret = decode_result =
523 traced_frame_receive(decoder->video_codec_ctx, decoder->frame);
524 if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
525 atomic_store_bool(&decoder->eof_reached, true);
526 reached_eof = true;
527 break;
528 }
529 if (ret < 0) {
530 break;
531 }
532 } else {
533 // Check if this is a video packet
534 if (decoder->packet->stream_index != decoder->video_stream_idx) {
535 av_packet_unref(decoder->packet);
536 continue;
537 }
538
539 // Send packet to decoder
540 ret = decode_result =
541 traced_packet_send(decoder->video_codec_ctx, decoder->packet);
542 av_packet_unref(decoder->packet);
543
544 if (ret == AVERROR(EAGAIN))
545 continue;
546 if (ret < 0) {
547 packet_rejected = true;
548 break;
549 }
550
551 // Receive decoded frame
552 ret = decode_result =
553 traced_frame_receive(decoder->video_codec_ctx, decoder->frame);
554 if (ret == AVERROR(EAGAIN)) {
555 continue; // Need more packets
556 } else if (ret < 0) {
557 break;
558 }
559 }
560 }
561
562 // Frame decoded - mutex still held
563 // Update position tracking
564 decoder->last_video_pts = get_frame_pts_seconds(
565 decoder->frame,
566 decoder->format_ctx->streams[decoder->video_stream_idx]->time_base);
567
568 // Convert frame to RGB24
569 int width = decoder->video_codec_ctx->width;
570 ASCII_OTEL_ATTR_INT("video.frame.width", width);
571 ASCII_OTEL_ATTR_INT("video.frame.height",
572 decoder->video_codec_ctx->height);
573 int height = decoder->video_codec_ctx->height;
574
575 // Get current decode buffer based on which one we're using
576 // (Buffer availability was already checked before entering the decode
577 // loop)
578 image_t *decode_buffer =
579 use_image_a ? decoder->prefetch_image_a : decoder->prefetch_image_b;
580
581 // Reallocate if needed (width/height changed)
582 if (decode_buffer->w != width || decode_buffer->h != height) {
583 image_t *replacement = image_new((size_t)width, (size_t)height);
584 if (!replacement) {
585 SET_ERRNO(ERROR_MEMORY, "Failed to allocate prefetch image buffer");
586 break;
587 }
588 image_destroy(decode_buffer);
589 decode_buffer = replacement;
590 // Update decoder's pointer to the reallocated buffer
591 if (use_image_a) {
592 decoder->prefetch_image_a = decode_buffer;
593 } else {
594 decoder->prefetch_image_b = decode_buffer;
595 }
596 }
597
598 // Convert pixel format (rgb_pixel_t is 3 bytes: r, g, b)
599 uint8_t *dst_data[1] = {(uint8_t *)decode_buffer->pixels};
600 int dst_linesize[1] = {width * 3};
601
602 static int decode_count = 0;
603 if (++decode_count <= 3) {
604 log_debug("[FRAME_DECODE] Frame %d: width=%d, height=%d, "
605 "codec_pix_fmt=%d, frame_pix_fmt=%d (is_stdin=%d)",
606 decode_count, width, height,
607 decoder->video_codec_ctx->pix_fmt, decoder->frame->format,
608 decoder->is_stdin);
609 }
610
611 // For fragmented MP4 from stdin, pixel format might not be set - default
612 // to YUV420p which is standard for H.264/H.265 video codecs
613 int pix_fmt_to_use = decoder->video_codec_ctx->pix_fmt;
614 if (pix_fmt_to_use == AV_PIX_FMT_NONE) {
615 if (decoder->frame->format != AV_PIX_FMT_NONE) {
616 pix_fmt_to_use = decoder->frame->format;
617 log_debug("[SWSCALE_FIX] Using frame->format=%d instead of codec "
618 "pix_fmt (was NONE)",
619 decoder->frame->format);
620 } else {
621 // Fragmented MP4: Default to YUV420p (standard for H.264/H.265)
622 pix_fmt_to_use = AV_PIX_FMT_YUV420P;
623 log_debug("[SWSCALE_FIX] Fragmented format: Using hardcoded YUV420p "
624 "(frame->format was also NONE)");
625 }
626 }
627
628 // Lazy initialize swscale context if not done at startup (happens with
629 // HTTP/stdin streams)
630 if (!decoder->sws_ctx) {
631 log_debug("Lazy init swscale: width=%d, height=%d, pix_fmt=%d", width,
632 height, pix_fmt_to_use);
633 if (width > 0 && height > 0 && pix_fmt_to_use != AV_PIX_FMT_NONE) {
634 LOG_IO("swscaler", {
635 decoder->sws_ctx = sws_getContext(width, height, pix_fmt_to_use,
636 width, height, AV_PIX_FMT_RGB24,
637 SWS_BILINEAR, NULL, NULL, NULL);
638 });
639 if (!decoder->sws_ctx) {
641 "Failed to create swscale context: pix_fmt=%d (might be "
642 "unsupported for conversion)",
643 pix_fmt_to_use);
644 break;
645 }
646
647 // Set proper colorspace for H.264 video (BT.709)
648 // sws_setColorspaceDetails(ctx, inv_table, srcRange, table, dstRange,
649 // brightness, contrast, saturation)
650 const int *inv_table = sws_getCoefficients(SWS_CS_ITU709);
651 const int *table = sws_getCoefficients(SWS_CS_ITU709);
652 int ret_cs = sws_setColorspaceDetails(decoder->sws_ctx, inv_table, 0,
653 table, 0, 0, 1 << 16, 1 << 16);
654 if (ret_cs < 0) {
655 log_warn("Failed to set BT.709 colorspace details (code=%d), "
656 "continuing with defaults",
657 ret_cs);
658 } else {
659 log_debug("Set BT.709 colorspace for H.264 YUV->RGB conversion");
660 }
661
662 log_debug(
663 "Lazy initialized swscale context with %dx%d from pix_fmt=%d",
664 width, height, pix_fmt_to_use);
665 } else {
667 "Cannot initialize swscale: width=%d, height=%d, "
668 "pix_fmt=%d (AV_PIX_FMT_NONE=%d)",
669 width, height, pix_fmt_to_use, AV_PIX_FMT_NONE);
670 break;
671 }
672 }
673
674 if (decode_count <= 3) {
675 // Log input YUV data
676 uint8_t *y_data = decoder->frame->data[0];
677 uint8_t *u_data = decoder->frame->data[1];
678 uint8_t *v_data = decoder->frame->data[2];
679 log_debug("[YUV_INPUT] Frame %d: Y[0]=%u, U[0]=%u, V[0]=%u "
680 "(linesize=%d,%d,%d)",
681 decode_count, y_data ? y_data[0] : 255,
682 u_data ? u_data[0] : 255, v_data ? v_data[0] : 255,
683 decoder->frame->linesize[0], decoder->frame->linesize[1],
684 decoder->frame->linesize[2]);
685 }
686
687 int ret_scale = traced_video_scale(
688 decoder->sws_ctx, (const uint8_t *const *)decoder->frame->data,
689 decoder->frame->linesize, 0, height, dst_data, dst_linesize);
690 if (ret_scale <= 0) {
691 SET_ERRNO(ERROR_MEDIA_DECODE, "Video conversion failed: %d", ret_scale);
692 break;
693 }
694 if (decode_count <= 3) {
695 log_debug("[SWS_SCALE] Frame %d: returned %d", decode_count, ret_scale);
696 rgb_pixel_t *test_px = (rgb_pixel_t *)decode_buffer->pixels;
697 log_debug("[SWS_RESULT] Frame %d: RGB[0]=(%u,%u,%u)", decode_count,
698 test_px[0].r, test_px[0].g, test_px[0].b);
699 }
700
701 frame_decoded = true;
702 break; // Exit while loop
703 }
704
705 // Release read_frame_mutex now that traced_packet_read() is done
706 mutex_unlock(&decoder->read_frame_mutex);
707
708 // Shutdown can race a buffered read without FFmpeg returning AVERROR_EXIT.
709 // The caller's cancellation request is authoritative for this operation.
710 bool (*cancel)(void *) =
711 (bool (*)(void *))atomic_ptr_load(&decoder->should_exit_callback);
712 bool cancelled =
713 cancel && cancel(atomic_ptr_load(&decoder->exit_callback_user_data));
714
715 if (frame_decoded) {
716 char read_time_str[TIME_DURATION_BUFFER_SIZE];
717 time_pretty(time_elapsed_ns(read_start_ns, time_get_ns()), -1,
718 read_time_str, sizeof(read_time_str));
719 log_dev_every(5 * US_PER_SEC_INT, "PREFETCH: decoded frame in %s",
720 read_time_str);
721 }
722
723 // Re-acquire mutex to update prefetch state
724 mutex_lock(&decoder->prefetch_mutex);
725
726 // Mutex now held - update prefetch state
727 bool obsolete = generation != decoder->seek_generation;
728 bool interrupted = decoder->prefetch_should_stop ||
729 decoder->seeking_in_progress || obsolete || cancelled;
730 errno_notifications_suppress(notifications_suppressed);
731 if (interrupted)
733 if (obsolete) {
734 frame_decoded = false;
735 reached_eof = false;
736 }
737 if (!frame_decoded && !reached_eof && !interrupted) {
738 if (!errno_peek_since(decode_scope, &decoder->prefetch_failure)) {
739 if (packet_rejected)
740 SET_ERRNO(ERROR_MEDIA_DECODE, "Video decoder rejected packet: %d",
741 decode_result);
742 else
744 "Background video decoding failed (FFmpeg result %d)",
745 decode_result);
746 if (!errno_peek_since(decode_scope, &decoder->prefetch_failure)) {
749 "Background video decoding failed",
750 sizeof(decoder->prefetch_failure.context_message));
751 }
752 }
753 }
754
755 if (!frame_decoded && !reached_eof && !interrupted)
756 atomic_store_explicit(&decoder->prefetch_failed, true,
757 memory_order_release);
758
759 if (frame_decoded) {
760 // Get current decode buffer
761 image_t *decode_buffer =
762 use_image_a ? decoder->prefetch_image_a : decoder->prefetch_image_b;
763
764 // Update the current prefetch image (main thread will pull from this)
765 decoder->current_prefetch_image = decode_buffer;
766 atomic_store_explicit(&decoder->prefetch_frame_ready, true,
767 memory_order_release);
768
769 } else if (cancelled || (!reached_eof && !interrupted)) {
770 // A decoder error terminates prefetch; EOF waits for rewind above.
771 break;
772 }
773 }
774
775 mutex_unlock(&decoder->prefetch_mutex);
776 log_debug("Video prefetch thread stopped");
777 return NULL;
778}
779
783static asciichat_error_t open_codec_context(AVFormatContext *fmt_ctx,
784 enum AVMediaType type,
785 int *stream_idx,
786 AVCodecContext **codec_ctx) {
787 ASCII_OTEL_SCOPE(FFMPEG_CODEC_OPEN);
788 ASCII_OTEL_ATTR_STRING("media.type",
789 type == AVMEDIA_TYPE_AUDIO ? "audio" : "video");
790 int ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
791 if (ret < 0) {
792 // Stream not found - not an error, just means no stream of this type
793 *stream_idx = -1;
794 *codec_ctx = NULL;
795 return ASCIICHAT_OK;
796 }
797
798 *stream_idx = ret;
799 AVStream *stream = fmt_ctx->streams[ret];
800
801 // Find decoder
802 const AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id);
803 if (!codec) {
804 return SET_ERRNO(ERROR_MEDIA_DECODE, "Codec not found for stream %d", ret);
805 }
806
807 ASCII_OTEL_ATTR_STRING("media.codec", codec->name);
808 // Allocate codec context
809 *codec_ctx = avcodec_alloc_context3(codec);
810 if (!*codec_ctx) {
811 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate codec context");
812 }
813
814 // Copy codec parameters
815 ret = avcodec_parameters_to_context(*codec_ctx, stream->codecpar);
816 if (ret < 0) {
817 avcodec_free_context(codec_ctx);
818 return SET_ERRNO(ret == AVERROR(ENOMEM) ? ERROR_MEMORY : ERROR_MEDIA_DECODE,
819 "Failed to copy codec parameters");
820 }
821
822 // Open codec
823 ret = avcodec_open2(*codec_ctx, codec, NULL);
824 if (ret < 0) {
825 avcodec_free_context(codec_ctx);
826 return SET_ERRNO(ret == AVERROR(ENOMEM) ? ERROR_MEMORY : ERROR_MEDIA_DECODE,
827 "Failed to open codec");
828 }
829
830 return ASCIICHAT_OK;
831}
832
833// A missing/unsupported stream can fall back to the other media type.
834// Allocation and other initialization failures still fail decoder creation with
835// their cause.
836static asciichat_error_t open_optional_codec_context(AVFormatContext *format,
837 enum AVMediaType type,
838 int *stream_index,
839 AVCodecContext **context) {
841 asciichat_error_t result =
842 open_codec_context(format, type, stream_index, context);
843 if (result == ERROR_MEDIA_DECODE &&
845 LOG_ERRNO_IF_SET("Optional media stream unavailable");
846 avcodec_free_context(context);
847 *stream_index = -1;
849 return ASCIICHAT_OK;
850 }
851 if (result != ASCIICHAT_OK)
852 return result;
855 return ASCIICHAT_OK;
856}
857
858/* ============================================================================
859 * Decoder Lifecycle
860 * ============================================================================
861 */
862
864 return ffmpeg_decoder_create_interruptible(path, NULL, NULL);
865}
866
868 bool (*cancel)(void *),
869 void *data) {
870 return ffmpeg_decoder_create_with_request_options(path, cancel, data, NULL,
871 NULL, NULL);
872}
873
875 const char *path, bool (*cancel)(void *), void *data, const char *headers,
876 const char *cookies, const char *proxy) {
877 ASCII_OTEL_SCOPE(FFMPEG_DECODER_CREATE_INTERRUPTIBLE);
878 if (!path) {
879 SET_ERRNO(ERROR_INVALID_PARAM, "Path is NULL");
880 return NULL;
881 }
882
883 // Suppress FFmpeg's verbose debug logging (H.264 codec warnings, etc.)
884 // Only set this once, it's a global setting
885 static bool ffmpeg_log_level_set = false;
886 if (!ffmpeg_log_level_set) {
887 av_log_set_level(AV_LOG_QUIET); // Suppress all FFmpeg logging
888 av_log_set_callback(ffmpeg_silent_log_callback); // Install silent callback
889 // to discard all output
890 ffmpeg_log_level_set = true;
891 }
892
893 ffmpeg_decoder_t *decoder =
895 if (!decoder) {
896 SET_ERRNO(ERROR_MEMORY, "Failed to allocate decoder");
897 return NULL;
898 }
899
900 memset(decoder, 0, sizeof(*decoder));
901 atomic_ptr_store(&decoder->should_exit_callback, (void *)cancel);
903 decoder->format_ctx = avformat_alloc_context();
904 if (!decoder->format_ctx) {
905 SAFE_FREE(decoder);
906 return NULL;
907 }
908 decoder->format_ctx->interrupt_callback.callback = ffmpeg_interrupt_callback;
909 decoder->format_ctx->interrupt_callback.opaque = decoder;
910 decoder->video_stream_idx = -1;
911 decoder->audio_stream_idx = -1;
912 decoder->last_video_pts = -1.0;
913 decoder->last_audio_pts = -1.0;
914
915 // Capture FFmpeg's probing output (FFmpeg may write directly to either
916 // stream)
917 int ret = 0;
918 LOG_IO("ffmpeg", {
919 // Configure FFmpeg options for HTTP streaming performance
920 AVDictionary *options = NULL;
921
922 // FFmpeg accepts HTTP authorities that the application URL validator
923 // rejects. Classify the protocol rather than validating the host for
924 // timeout settings.
925 bool is_http =
926 path &&
927 (platform_strncasecmp(path, "http://", sizeof("http://") - 1) == 0 ||
928 platform_strncasecmp(path, "https://", sizeof("https://") - 1) == 0);
930 bool is_url =
931 is_http || (path && strstr(path, "://") && url_is_valid(path));
933 if (is_url) {
934 if (headers && *headers)
935 av_dict_set(&options, "headers", headers, 0);
936 if (cookies && *cookies)
937 av_dict_set(&options, "cookies", cookies, 0);
938 if (proxy)
939 av_dict_set(&options, "http_proxy", proxy, 0);
940 // Limit probing to 32KB for faster format detection
941 av_dict_set(&options, "probesize", "32768", 0);
942 // Analyze for 100ms max to determine streams quickly
943 av_dict_set(&options, "analyzeduration", "100000", 0);
944 // Enable auto-reconnection for interrupted connections
945 av_dict_set(&options, "reconnect", "1", 0);
946 // Allow reconnection for streamed protocols
947 av_dict_set(&options, "reconnect_streamed", "1", 0);
948 // Set reasonable I/O timeout (10 seconds)
949 av_dict_set(&options, "rw_timeout", "10000000", 0);
950 // Enable HTTP persistent connection (keep-alive) for better performance
951 av_dict_set(&options, "http_persistent", "1", 0);
952 // Reduce connect timeout to fail faster if server is unreachable
953 av_dict_set(&options, "connect_timeout", "5000000", 0);
954 }
955
956 // Open input file
957 ret = traced_format_open(&decoder->format_ctx, path, NULL, &options);
958 av_dict_free(&options); // Free options dictionary
959
960 if (ret >= 0) {
961 // Find stream info
962 if (traced_format_probe(decoder->format_ctx, NULL) < 0) {
963 ret = -1;
964 }
965 }
966 });
967
968 if (ret < 0) {
969 if (ret == -1) {
970 SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to find stream info");
971 } else {
972 SET_ERRNO(ERROR_MEDIA_OPEN, "Failed to open media file: %s", path);
973 }
974 if (decoder->format_ctx) {
975 avformat_close_input(&decoder->format_ctx);
976 }
977 SAFE_FREE(decoder);
978 return NULL;
979 }
980
981 // Install interrupt callback to allow seeking to interrupt long
982 // traced_packet_read() calls Do this AFTER finding stream info to ensure
983 // format context is fully initialized
984 if (decoder->format_ctx) {
985 decoder->format_ctx->interrupt_callback.callback =
986 ffmpeg_interrupt_callback;
987 decoder->format_ctx->interrupt_callback.opaque = decoder;
988 }
989
990 // Open video codec
991 asciichat_error_t err = open_optional_codec_context(
992 decoder->format_ctx, AVMEDIA_TYPE_VIDEO, &decoder->video_stream_idx,
993 &decoder->video_codec_ctx);
994 if (err != ASCIICHAT_OK) {
995 ffmpeg_decoder_destroy(decoder);
996 return NULL;
997 }
998
999 // Open audio codec - audio is enabled by default (no option needed)
1000 // Always try to open audio codec, don't rely on GET_OPTION(audio_enabled)
1001 // which has a default issue
1002 err = open_optional_codec_context(decoder->format_ctx, AVMEDIA_TYPE_AUDIO,
1003 &decoder->audio_stream_idx,
1004 &decoder->audio_codec_ctx);
1005 if (err != ASCIICHAT_OK) {
1006 ffmpeg_decoder_destroy(decoder);
1007 return NULL;
1008 }
1009
1010 // Require at least one stream
1011 if (decoder->video_stream_idx < 0 && decoder->audio_stream_idx < 0) {
1012 SET_ERRNO(ERROR_MEDIA_DECODE, "No video or audio streams found");
1013 ffmpeg_decoder_destroy(decoder);
1014 return NULL;
1015 }
1016
1017 // Allocate frame and packet
1018 decoder->frame = av_frame_alloc();
1019 decoder->packet = av_packet_alloc();
1020 if (!decoder->frame || !decoder->packet) {
1021 SET_ERRNO(ERROR_MEMORY, "Failed to allocate frame/packet");
1022 ffmpeg_decoder_destroy(decoder);
1023 return NULL;
1024 }
1025
1026 // Initialize swscale context for video if present
1027 if (decoder->video_codec_ctx) {
1028 // Validate codec context has valid dimensions and pixel format
1029 // For HTTP streams, these might not be valid until first frame is read
1030 if (decoder->video_codec_ctx->width <= 0 ||
1031 decoder->video_codec_ctx->height <= 0) {
1032 log_warn("Video codec has invalid dimensions (%dx%d), will initialize "
1033 "swscale on first frame",
1034 decoder->video_codec_ctx->width,
1035 decoder->video_codec_ctx->height);
1036 // Don't create swscale context yet - will create it lazily on first frame
1037 // read
1038 } else if (decoder->video_codec_ctx->pix_fmt == AV_PIX_FMT_NONE) {
1039 log_warn("Video codec has invalid pixel format, will initialize swscale "
1040 "on first frame");
1041 // Don't create swscale context yet - will create it lazily on first frame
1042 // read
1043 } else {
1044 // Create swscale context with valid parameters
1045 LOG_IO("swscaler", {
1046 decoder->sws_ctx = sws_getContext(
1047 decoder->video_codec_ctx->width, decoder->video_codec_ctx->height,
1048 decoder->video_codec_ctx->pix_fmt, decoder->video_codec_ctx->width,
1049 decoder->video_codec_ctx->height, AV_PIX_FMT_RGB24, SWS_BILINEAR,
1050 NULL, NULL, NULL);
1051 });
1052 if (!decoder->sws_ctx) {
1053 SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to create swscale context");
1054 ffmpeg_decoder_destroy(decoder);
1055 return NULL;
1056 }
1057 }
1058 }
1059
1060 // Initialize swresample context for audio if present
1061 if (decoder->audio_codec_ctx) {
1062 // Store output sample rate for position tracking
1064
1065 // Allocate resampler context
1066 decoder->swr_ctx = swr_alloc();
1067 if (!decoder->swr_ctx) {
1068 SET_ERRNO(ERROR_MEMORY, "Failed to allocate swresample context");
1069 ffmpeg_decoder_destroy(decoder);
1070 return NULL;
1071 }
1072
1073 // Set options
1074 av_opt_set_chlayout(decoder->swr_ctx, "in_chlayout",
1075 &decoder->audio_codec_ctx->ch_layout, 0);
1076 av_opt_set_int(decoder->swr_ctx, "in_sample_rate",
1077 decoder->audio_codec_ctx->sample_rate, 0);
1078 av_opt_set_sample_fmt(decoder->swr_ctx, "in_sample_fmt",
1079 decoder->audio_codec_ctx->sample_fmt, 0);
1080
1081 AVChannelLayout out_ch_layout = AV_CHANNEL_LAYOUT_STEREO;
1082 av_opt_set_chlayout(decoder->swr_ctx, "out_chlayout", &out_ch_layout, 0);
1083 av_opt_set_int(decoder->swr_ctx, "out_sample_rate", TARGET_SAMPLE_RATE, 0);
1084 av_opt_set_sample_fmt(decoder->swr_ctx, "out_sample_fmt", AV_SAMPLE_FMT_FLT,
1085 0);
1086
1087 // A mono source stays centered at unity gain in the stereo pipeline.
1088 if (decoder->audio_codec_ctx->ch_layout.nb_channels == 1) {
1089 const double matrix[] = {1.0, 1.0};
1090 swr_set_matrix(decoder->swr_ctx, matrix, 1);
1091 }
1092 // Initialize
1093 if (swr_init(decoder->swr_ctx) < 0) {
1094 SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to initialize swresample context");
1095 ffmpeg_decoder_destroy(decoder);
1096 return NULL;
1097 }
1098
1099 // Allocate audio buffer (10 seconds worth)
1101 decoder->audio_buffer =
1102 SAFE_MALLOC(decoder->audio_buffer_size * sizeof(float), float *);
1103 if (!decoder->audio_buffer) {
1104 SET_ERRNO(ERROR_MEMORY, "Failed to allocate audio buffer");
1105 ffmpeg_decoder_destroy(decoder);
1106 return NULL;
1107 }
1108 }
1109
1110 // Initialize video frame prefetching system (for YouTube streaming)
1111 if (decoder->video_stream_idx >= 0) {
1112 int width = decoder->video_codec_ctx->width;
1113 int height = decoder->video_codec_ctx->height;
1114
1115 // Create two prefetch image buffers for double-buffering
1116 decoder->prefetch_image_a = image_new((size_t)width, (size_t)height);
1117 decoder->prefetch_image_b = image_new((size_t)width, (size_t)height);
1118 if (!decoder->prefetch_image_a || !decoder->prefetch_image_b) {
1119 SET_ERRNO(ERROR_MEMORY, "Failed to allocate prefetch image buffers");
1120 ffmpeg_decoder_destroy(decoder);
1121 return NULL;
1122 }
1123
1124 decoder->current_prefetch_image = decoder->prefetch_image_a;
1125 decoder->prefetch_frame_ready = false;
1126
1127 // Initialize prefetch mutex
1128 if (mutex_init(&decoder->prefetch_mutex, "ffmpeg_prefetch") != 0) {
1129 SET_ERRNO(ERROR_MEMORY, "Failed to initialize prefetch mutex");
1130 ffmpeg_decoder_destroy(decoder);
1131 return NULL;
1132 }
1133
1134 if (cond_init(&decoder->prefetch_cond, "ffmpeg_prefetch") != 0) {
1136 "Failed to initialize prefetch condition variable");
1137 mutex_destroy(&decoder->prefetch_mutex);
1138 ffmpeg_decoder_destroy(decoder);
1139 return NULL;
1140 }
1141
1142 if (mutex_init(&decoder->read_frame_mutex, "ffmpeg_read_frame") != 0) {
1143 SET_ERRNO(ERROR_MEMORY, "Failed to initialize read_frame mutex");
1144 mutex_destroy(&decoder->prefetch_mutex);
1145 cond_destroy(&decoder->prefetch_cond);
1146 ffmpeg_decoder_destroy(decoder);
1147 return NULL;
1148 }
1149
1150 decoder->prefetch_thread_running = false;
1151 decoder->prefetch_should_stop = false;
1152 }
1153
1154 log_debug("FFmpeg decoder opened: %s (video=%s, audio=%s)", path,
1155 decoder->video_stream_idx >= 0 ? "yes" : "no",
1156 decoder->audio_stream_idx >= 0 ? "yes" : "no");
1157
1159 snprintf(decoder_name, sizeof(decoder_name), "%s", path);
1160 NAMED_REGISTER_FFMPEG_DECODER(decoder, decoder_name, NULL);
1161 NAMED_REGISTER_ATOMIC(&decoder->eof_reached, "ffmpeg_eof", decoder);
1162
1163 return decoder;
1164}
1165
1167 ASCII_OTEL_SCOPE(FFMPEG_DECODER_CREATE_STDIN);
1168 // Buffer entire stdin on first call (shared between video and audio decoders)
1169 if (!g_stdin_buffer) {
1170 log_debug("Reading stdin into buffer...");
1171 g_stdin_buffer = stdin_buffer_read_all();
1172 if (!g_stdin_buffer) {
1173 SET_ERRNO(ERROR_MEDIA_OPEN, "Failed to read stdin into buffer");
1174 return NULL;
1175 }
1176 }
1177
1178 ffmpeg_decoder_t *decoder =
1180 if (!decoder) {
1181 SET_ERRNO(ERROR_MEMORY, "Failed to allocate decoder");
1182 return NULL;
1183 }
1184
1185 memset(decoder, 0, sizeof(*decoder));
1186 decoder->video_stream_idx = -1;
1187 decoder->audio_stream_idx = -1;
1188 decoder->is_stdin = true;
1189 decoder->last_video_pts = -1.0;
1190 decoder->last_audio_pts = -1.0;
1191
1192 // Create per-decoder reader (each decoder gets independent position tracking)
1193 stdin_buffer_reader_t *reader =
1195 if (!reader) {
1196 SET_ERRNO(ERROR_MEMORY, "Failed to allocate buffer reader");
1197 SAFE_FREE(decoder);
1198 return NULL;
1199 }
1200 reader->buffer = g_stdin_buffer;
1201 reader->pos = 0; // Each decoder starts from position 0
1202
1203 // AVIO takes ownership of this buffer and may resize or free it with
1204 // av_free().
1205 decoder->avio_buffer = av_malloc(AVIO_BUFFER_SIZE);
1206 if (!decoder->avio_buffer) {
1207 SET_ERRNO(ERROR_MEMORY, "Failed to allocate AVIO buffer");
1208 SAFE_FREE(reader);
1209 SAFE_FREE(decoder);
1210 return NULL;
1211 }
1212
1213 decoder->avio_ctx =
1214 avio_alloc_context(decoder->avio_buffer, // internal buffer for AVIO
1215 AVIO_BUFFER_SIZE, // buffer size
1216 0, // write_flag
1217 reader, // opaque (per-decoder reader)
1218 memory_read_packet,
1219 NULL, // write_packet
1220 memory_seek_packet // seek (memory is seekable)
1221 );
1222
1223 if (!decoder->avio_ctx) {
1224 SET_ERRNO(ERROR_MEMORY, "Failed to create AVIO context");
1225 av_free(decoder->avio_buffer);
1226 decoder->avio_buffer = NULL;
1227 SAFE_FREE(decoder);
1228 return NULL;
1229 }
1230
1231 // Mark AVIO context as seekable (memory buffer supports seeking)
1232 decoder->avio_ctx->seekable = AVIO_SEEKABLE_NORMAL;
1233
1234 // Allocate format context
1235 decoder->format_ctx = avformat_alloc_context();
1236 if (!decoder->format_ctx) {
1237 SET_ERRNO(ERROR_MEMORY, "Failed to allocate format context");
1238 av_freep(&decoder->avio_ctx->buffer);
1239 avio_context_free(&decoder->avio_ctx);
1240 SAFE_FREE(decoder);
1241 return NULL;
1242 }
1243
1244 decoder->format_ctx->pb = decoder->avio_ctx;
1245 decoder->format_ctx->flags |=
1246 AVFMT_FLAG_CUSTOM_IO; // Tell FFmpeg to use our custom AVIO context
1247
1248 // Capture FFmpeg's probing output
1249 int ret = 0;
1250 LOG_IO("ffmpeg", {
1251 // Open input from buffered stdin
1252 ret = traced_format_open(&decoder->format_ctx, NULL, NULL, NULL);
1253 if (ret >= 0) {
1254 // Find stream info
1255 if (traced_format_probe(decoder->format_ctx, NULL) < 0) {
1256 ret = -1;
1257 }
1258 }
1259 });
1260
1261 if (ret < 0) {
1262 if (ret == -1) {
1264 "Failed to find stream info from stdin buffer");
1265 } else {
1266 SET_ERRNO(ERROR_MEDIA_OPEN, "Failed to open stdin buffer");
1267 }
1268 av_freep(&decoder->avio_ctx->buffer);
1269 avio_context_free(&decoder->avio_ctx);
1270 if (decoder->format_ctx) {
1271 avformat_free_context(decoder->format_ctx);
1272 }
1273 SAFE_FREE(decoder);
1274 return NULL;
1275 }
1276
1277 // Open codecs (same as file-based decoder)
1278 asciichat_error_t err = open_optional_codec_context(
1279 decoder->format_ctx, AVMEDIA_TYPE_VIDEO, &decoder->video_stream_idx,
1280 &decoder->video_codec_ctx);
1281 if (err != ASCIICHAT_OK) {
1282 ffmpeg_decoder_destroy(decoder);
1283 return NULL;
1284 }
1285
1286 if (GET_OPTION(audio_enabled)) {
1287 err = open_optional_codec_context(decoder->format_ctx, AVMEDIA_TYPE_AUDIO,
1288 &decoder->audio_stream_idx,
1289 &decoder->audio_codec_ctx);
1290 if (err != ASCIICHAT_OK) {
1291 ffmpeg_decoder_destroy(decoder);
1292 return NULL;
1293 }
1294 } else {
1295 decoder->audio_stream_idx = -1;
1296 decoder->audio_codec_ctx = NULL;
1297 log_debug("Audio decoding disabled by user option");
1298 }
1299
1300 if (decoder->video_stream_idx < 0 && decoder->audio_stream_idx < 0) {
1301 SET_ERRNO(ERROR_MEDIA_DECODE, "No video or audio streams found in stdin");
1302 ffmpeg_decoder_destroy(decoder);
1303 return NULL;
1304 }
1305
1306 // Allocate frame and packet
1307 decoder->frame = av_frame_alloc();
1308 decoder->packet = av_packet_alloc();
1309 if (!decoder->frame || !decoder->packet) {
1310 SET_ERRNO(ERROR_MEMORY, "Failed to allocate frame/packet");
1311 ffmpeg_decoder_destroy(decoder);
1312 return NULL;
1313 }
1314
1315 // Initialize swscale/swresample (same as file-based)
1316 if (decoder->video_codec_ctx) {
1317 // Validate codec context has valid dimensions and pixel format
1318 // For stdin/HTTP streams, these might not be valid until first frame is
1319 // read
1320 if (decoder->video_codec_ctx->width <= 0 ||
1321 decoder->video_codec_ctx->height <= 0) {
1322 log_warn("Video codec has invalid dimensions (%dx%d), will initialize "
1323 "swscale on first frame",
1324 decoder->video_codec_ctx->width,
1325 decoder->video_codec_ctx->height);
1326 // Don't create swscale context yet - will create it lazily on first frame
1327 // read
1328 } else if (decoder->video_codec_ctx->pix_fmt == AV_PIX_FMT_NONE) {
1329 log_warn("Video codec has invalid pixel format, will initialize swscale "
1330 "on first frame");
1331 // Don't create swscale context yet - will create it lazily on first frame
1332 // read
1333 } else {
1334 // Create swscale context with valid parameters
1335 LOG_IO("swscaler", {
1336 decoder->sws_ctx = sws_getContext(
1337 decoder->video_codec_ctx->width, decoder->video_codec_ctx->height,
1338 decoder->video_codec_ctx->pix_fmt, decoder->video_codec_ctx->width,
1339 decoder->video_codec_ctx->height, AV_PIX_FMT_RGB24, SWS_BILINEAR,
1340 NULL, NULL, NULL);
1341 });
1342 if (!decoder->sws_ctx) {
1343 SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to create swscale context");
1344 ffmpeg_decoder_destroy(decoder);
1345 return NULL;
1346 }
1347 }
1348 }
1349
1350 if (decoder->audio_codec_ctx) {
1351 decoder->swr_ctx = swr_alloc();
1352 if (!decoder->swr_ctx) {
1353 SET_ERRNO(ERROR_MEMORY, "Failed to allocate swresample context");
1354 ffmpeg_decoder_destroy(decoder);
1355 return NULL;
1356 }
1357
1358 av_opt_set_chlayout(decoder->swr_ctx, "in_chlayout",
1359 &decoder->audio_codec_ctx->ch_layout, 0);
1360 av_opt_set_int(decoder->swr_ctx, "in_sample_rate",
1361 decoder->audio_codec_ctx->sample_rate, 0);
1362 av_opt_set_sample_fmt(decoder->swr_ctx, "in_sample_fmt",
1363 decoder->audio_codec_ctx->sample_fmt, 0);
1364
1365 AVChannelLayout out_ch_layout = AV_CHANNEL_LAYOUT_STEREO;
1366 av_opt_set_chlayout(decoder->swr_ctx, "out_chlayout", &out_ch_layout, 0);
1367 av_opt_set_int(decoder->swr_ctx, "out_sample_rate", TARGET_SAMPLE_RATE, 0);
1368 av_opt_set_sample_fmt(decoder->swr_ctx, "out_sample_fmt", AV_SAMPLE_FMT_FLT,
1369 0);
1370 if (decoder->audio_codec_ctx->ch_layout.nb_channels == 1) {
1371 const double matrix[] = {1.0, 1.0};
1372 swr_set_matrix(decoder->swr_ctx, matrix, 1);
1373 }
1374
1375 if (swr_init(decoder->swr_ctx) < 0) {
1376 SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to initialize swresample context");
1377 ffmpeg_decoder_destroy(decoder);
1378 return NULL;
1379 }
1380
1382 decoder->audio_buffer =
1383 SAFE_MALLOC(decoder->audio_buffer_size * sizeof(float), float *);
1384 if (!decoder->audio_buffer) {
1385 SET_ERRNO(ERROR_MEMORY, "Failed to allocate audio buffer");
1386 ffmpeg_decoder_destroy(decoder);
1387 return NULL;
1388 }
1389 }
1390
1391 // Initialize video frame prefetching system for stdin (same as file-based)
1392 if (decoder->video_stream_idx >= 0) {
1393 int width = decoder->video_codec_ctx->width;
1394 int height = decoder->video_codec_ctx->height;
1395
1396 // For stdin sources, dimensions might be invalid initially (0x0)
1397 // Use default dimensions for prefetch buffers; they'll be resized on first
1398 // frame
1399 if (width <= 0 || height <= 0) {
1400 width = 1920; // Default width for stdin
1401 height = 1080; // Default height for stdin
1402 log_debug("stdin: Using default prefetch dimensions %dx%d (will be "
1403 "resized on first frame)",
1404 width, height);
1405 }
1406
1407 // Create two prefetch image buffers for double-buffering
1408 decoder->prefetch_image_a = image_new((size_t)width, (size_t)height);
1409 decoder->prefetch_image_b = image_new((size_t)width, (size_t)height);
1410 if (!decoder->prefetch_image_a || !decoder->prefetch_image_b) {
1411 SET_ERRNO(ERROR_MEMORY, "Failed to allocate prefetch image buffers");
1412 ffmpeg_decoder_destroy(decoder);
1413 return NULL;
1414 }
1415
1416 decoder->current_prefetch_image = decoder->prefetch_image_a;
1417 decoder->prefetch_frame_ready = false;
1418
1419 // Initialize prefetch mutex
1420 if (mutex_init(&decoder->prefetch_mutex, "ffmpeg_prefetch") != 0) {
1421 SET_ERRNO(ERROR_MEMORY, "Failed to initialize prefetch mutex");
1422 ffmpeg_decoder_destroy(decoder);
1423 return NULL;
1424 }
1425
1426 if (cond_init(&decoder->prefetch_cond, "ffmpeg_prefetch") != 0) {
1428 "Failed to initialize prefetch condition variable");
1429 mutex_destroy(&decoder->prefetch_mutex);
1430 ffmpeg_decoder_destroy(decoder);
1431 return NULL;
1432 }
1433
1434 if (mutex_init(&decoder->read_frame_mutex, "ffmpeg_read_frame") != 0) {
1435 SET_ERRNO(ERROR_MEMORY, "Failed to initialize read_frame mutex");
1436 mutex_destroy(&decoder->prefetch_mutex);
1437 cond_destroy(&decoder->prefetch_cond);
1438 ffmpeg_decoder_destroy(decoder);
1439 return NULL;
1440 }
1441 }
1442
1443 log_debug("FFmpeg decoder opened from stdin (video=%s, audio=%s)",
1444 decoder->video_stream_idx >= 0 ? "yes" : "no",
1445 decoder->audio_stream_idx >= 0 ? "yes" : "no");
1446
1447 NAMED_REGISTER_FFMPEG_DECODER(decoder, "stdin", NULL);
1448 NAMED_REGISTER_ATOMIC(&decoder->eof_reached, "ffmpeg_eof", decoder);
1449
1450 return decoder;
1451}
1452
1454 ASCII_OTEL_SCOPE(FFMPEG_DECODER_DESTROY);
1455 if (!decoder) {
1456 return;
1457 }
1458
1459 NAMED_UNREGISTER(&decoder->eof_reached);
1460 NAMED_UNREGISTER(decoder);
1461
1462 // Stop prefetch thread (signal it to stop and wait for it to finish)
1463 if (decoder->prefetch_thread_running) {
1464 mutex_lock(&decoder->prefetch_mutex);
1465 decoder->prefetch_should_stop = true;
1466 cond_signal(&decoder->prefetch_cond);
1467 mutex_unlock(&decoder->prefetch_mutex);
1468
1469 // Wait for thread to finish
1470 thread_join(&decoder->prefetch_thread, NULL);
1471 decoder->prefetch_thread_running = false;
1472 }
1473
1474 // Clean up prefetch state
1475 cond_destroy(&decoder->prefetch_cond);
1476 mutex_destroy(&decoder->prefetch_mutex);
1477 mutex_destroy(&decoder->read_frame_mutex);
1478
1479 // Free prefetch image buffers
1480 if (decoder->prefetch_image_a) {
1482 decoder->prefetch_image_a = NULL;
1483 }
1484 if (decoder->prefetch_image_b) {
1486 decoder->prefetch_image_b = NULL;
1487 }
1488
1489 // Don't destroy current_image - it points to one of the prefetch buffers
1490 // which have already been destroyed above
1491 decoder->current_image = NULL;
1492
1493 // Free audio buffer
1494 SAFE_FREE(decoder->audio_buffer);
1495
1496 // Free swscale context
1497 if (decoder->sws_ctx) {
1498 sws_freeContext(decoder->sws_ctx);
1499 decoder->sws_ctx = NULL;
1500 }
1501
1502 // Free swresample context
1503 if (decoder->swr_ctx) {
1504 swr_free(&decoder->swr_ctx);
1505 }
1506
1507 // Free frame and packet
1508 if (decoder->frame) {
1509 av_frame_free(&decoder->frame);
1510 }
1511 if (decoder->packet) {
1512 av_packet_free(&decoder->packet);
1513 }
1514
1515 // Free codec contexts
1516 if (decoder->video_codec_ctx) {
1517 avcodec_free_context(&decoder->video_codec_ctx);
1518 }
1519 if (decoder->audio_codec_ctx) {
1520 avcodec_free_context(&decoder->audio_codec_ctx);
1521 }
1522
1523 // Free format context
1524 if (decoder->format_ctx) {
1525 avformat_close_input(&decoder->format_ctx);
1526 }
1527
1528 // Free AVIO context (stdin only)
1529 if (decoder->avio_ctx) {
1530 // Free the opaque reader for stdin
1531 if (decoder->is_stdin) {
1532 SAFE_FREE(decoder->avio_ctx->opaque);
1533 }
1534 av_freep(&decoder->avio_ctx->buffer);
1535 avio_context_free(&decoder->avio_ctx);
1536 }
1537
1538 SAFE_FREE(decoder);
1539}
1540
1541/* ============================================================================
1542 * Video Operations
1543 * ============================================================================
1544 */
1545
1548 asciichat_error_context_t *failure) {
1549 ASCII_OTEL_SCOPE(FFMPEG_DECODER_POLL_VIDEO);
1550 if (frame)
1551 *frame = NULL;
1552 if (failure)
1553 memset(failure, 0, sizeof(*failure));
1554 if (!decoder || !frame || !failure) {
1556 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid video poll outputs");
1557 if (failure && !errno_peek_since(scope, failure))
1558 failure->code = ERROR_INVALID_PARAM;
1559 return FFMPEG_FRAME_FAILED;
1560 }
1561 // Empty polls need no protected state. EOF and errors still confirm under
1562 // the mutex so a final pending frame takes precedence over termination.
1563 if (!atomic_load_explicit(&decoder->prefetch_frame_ready,
1564 memory_order_acquire) &&
1565 !atomic_load_explicit(&decoder->prefetch_failed, memory_order_acquire) &&
1566 !ffmpeg_decoder_at_end(decoder))
1567 return FFMPEG_FRAME_WAITING;
1568
1569 mutex_lock(&decoder->prefetch_mutex);
1570 if (decoder->prefetch_frame_ready && decoder->current_prefetch_image) {
1571 // Taking the next image releases the previous reader-owned buffer.
1572 if (decoder->current_read_buffer == decoder->prefetch_image_a)
1573 decoder->buffer_a_in_use = false;
1574 else if (decoder->current_read_buffer == decoder->prefetch_image_b)
1575 decoder->buffer_b_in_use = false;
1576 *frame = decoder->current_prefetch_image;
1577 decoder->prefetch_frame_ready = false;
1578 if (*frame == decoder->prefetch_image_a)
1579 decoder->buffer_a_in_use = true;
1580 else if (*frame == decoder->prefetch_image_b)
1581 decoder->buffer_b_in_use = true;
1582 decoder->current_read_buffer = *frame;
1583 decoder->current_image = *frame;
1584 cond_signal(&decoder->prefetch_cond);
1585 mutex_unlock(&decoder->prefetch_mutex);
1586 return FFMPEG_FRAME_READY;
1587 }
1588 *failure = decoder->prefetch_failure;
1589 bool eof = ffmpeg_decoder_at_end(decoder);
1590 mutex_unlock(&decoder->prefetch_mutex);
1591 if (failure->code != ASCIICHAT_OK)
1592 return FFMPEG_FRAME_FAILED;
1594}
1595
1597 ASCII_OTEL_SCOPE(FFMPEG_DECODER_READ_VIDEO_FRAME);
1598 image_t *frame = NULL;
1599 asciichat_error_context_t failure = {0};
1600 if (ffmpeg_decoder_poll_video(decoder, &frame, &failure) ==
1602 errno_import(&failure);
1603 return frame;
1604}
1605
1615 if (!decoder || decoder->video_stream_idx < 0) {
1617 "Decoder has no initialized video prefetch buffers");
1618 }
1619
1620 if (!decoder->prefetch_image_a || !decoder->prefetch_image_b) {
1622 "Decoder has no initialized video prefetch buffers");
1623 }
1624
1625 // Already running
1626 if (decoder->prefetch_thread_running) {
1627 return ASCIICHAT_OK;
1628 }
1629
1630 // Reset stop flag and create thread
1631 decoder->prefetch_should_stop = false;
1632 memset(&decoder->prefetch_failure, 0, sizeof(decoder->prefetch_failure));
1633 atomic_store(&decoder->prefetch_failed, false);
1634
1635 int thread_err =
1636 platform_thread_create(&decoder->prefetch_thread, "ffmpeg_prefetch",
1637 ffmpeg_decoder_prefetch_thread_func, decoder);
1638 if (thread_err != 0) {
1639 return SET_ERRNO(ERROR_THREAD, "Failed to create video prefetch thread");
1640 }
1641
1642 decoder->prefetch_thread_running = true;
1643 return ASCIICHAT_OK;
1644}
1645
1650 if (!decoder || !decoder->prefetch_thread_running) {
1651 return;
1652 }
1653
1654 mutex_lock(&decoder->prefetch_mutex);
1655 decoder->prefetch_should_stop = true;
1656 cond_signal(&decoder->prefetch_cond);
1657 mutex_unlock(&decoder->prefetch_mutex);
1658 // Wait up to 2 seconds for thread to stop
1659 // The interrupt callback should cause av_read_frame to abort quickly
1660 if (thread_join_timeout(&decoder->prefetch_thread, NULL,
1661 2000 * NS_PER_MS_INT) == ASCIICHAT_OK)
1662 decoder->prefetch_thread_running = false;
1663 // A timed-out worker remains owned and must be joined by decoder destruction.
1664 else
1665 log_warn("Video prefetch thread is still stopping");
1666}
1667
1669 bool (*should_exit_callback)(void *),
1670 void *user_data) {
1671 if (!decoder) {
1672 return;
1673 }
1674 atomic_ptr_store(&decoder->exit_callback_user_data, user_data);
1676 (void *)should_exit_callback);
1677}
1678
1680 if (!decoder) {
1681 return false;
1682 }
1683 return decoder->prefetch_thread_running;
1684}
1685
1687 return decoder && decoder->video_stream_idx >= 0;
1688}
1689
1691 int *width, int *height) {
1692 if (!decoder || decoder->video_stream_idx < 0) {
1693 return SET_ERRNO(ERROR_INVALID_PARAM, "Decoder has no video stream");
1694 }
1695
1696 if (width) {
1697 *width = decoder->video_codec_ctx->width;
1698 }
1699 if (height) {
1700 *height = decoder->video_codec_ctx->height;
1701 }
1702
1703 return ASCIICHAT_OK;
1704}
1705
1707 if (!decoder || decoder->video_stream_idx < 0) {
1708 return -1.0;
1709 }
1710
1711 AVStream *stream = decoder->format_ctx->streams[decoder->video_stream_idx];
1712
1713 // Try avg_frame_rate first (average frame rate from entire stream)
1714 double fps = av_q2d_safe(stream->avg_frame_rate);
1715
1716 // Fallback to r_frame_rate if avg_frame_rate is invalid or zero
1717 // r_frame_rate is the "real" frame rate based on codec parameters
1718 // This is more reliable for YouTube videos and some video codecs
1719 if (fps <= 0.0) {
1720 fps = av_q2d_safe(stream->r_frame_rate);
1721 }
1722
1723 return fps;
1724}
1725
1726/* ============================================================================
1727 * Audio Operations
1728 * ============================================================================
1729 */
1730
1732 float *buffer, size_t num_samples) {
1733 ASCII_OTEL_SCOPE(FFMPEG_DECODER_READ_AUDIO_SAMPLES);
1734 // Keep channels and the playback clock aligned even with odd caller capacity.
1735 num_samples -= num_samples % TARGET_CHANNELS;
1736 if (!decoder || decoder->audio_stream_idx < 0 || !buffer ||
1737 num_samples == 0) {
1738 return 0;
1739 }
1740
1741 mutex_lock(&decoder->read_frame_mutex);
1742 size_t samples_written = 0;
1743
1744 // First, drain any buffered samples
1745 if (decoder->audio_buffer_offset > 0) {
1746 size_t available = decoder->audio_buffer_offset;
1747 size_t to_copy = (available < num_samples) ? available : num_samples;
1748
1749 memcpy(buffer, decoder->audio_buffer, to_copy * sizeof(float));
1750 samples_written += to_copy;
1751
1752 // Shift buffer
1753 if (to_copy < available) {
1754 memmove(decoder->audio_buffer, decoder->audio_buffer + to_copy,
1755 (available - to_copy) * sizeof(float));
1756 }
1757 decoder->audio_buffer_offset -= to_copy;
1758
1759 if (samples_written >= num_samples) {
1760 decoder->audio_samples_read += samples_written / TARGET_CHANNELS;
1761 mutex_unlock(&decoder->read_frame_mutex);
1762 return samples_written;
1763 }
1764 }
1765
1766 // Read more packets to fill the request
1767 static uint64_t packet_count = 0;
1768
1769 while (samples_written < num_samples) {
1770 int ret = traced_packet_read(decoder->format_ctx, decoder->packet);
1771 if (ret < 0) {
1772 if (ret == AVERROR_EOF) {
1773 atomic_store_bool(&decoder->eof_reached, true);
1774 }
1775 break;
1776 }
1777
1778 // Check if this is an audio packet
1779 if (decoder->packet->stream_index != decoder->audio_stream_idx) {
1780 av_packet_unref(decoder->packet);
1781 continue;
1782 }
1783
1784 packet_count++;
1786 "Audio packet #%lu: pts=%ld dts=%ld duration=%d size=%d",
1787 packet_count, decoder->packet->pts, decoder->packet->dts,
1788 decoder->packet->duration, decoder->packet->size);
1789
1790 // Send packet to decoder
1791 ret = traced_packet_send(decoder->audio_codec_ctx, decoder->packet);
1792 av_packet_unref(decoder->packet);
1793
1794 if (ret < 0) {
1795 char error_message[AV_ERROR_MAX_STRING_SIZE];
1796 av_strerror(ret, error_message, sizeof(error_message));
1798 "Error sending audio packet to decoder: %s",
1799 error_message);
1800 continue;
1801 }
1802
1803 // Receive all decoded frames from this packet
1804 // Important: a single packet can produce multiple frames. Must drain all
1805 // before next packet.
1806 while (1) {
1807 ret = traced_frame_receive(decoder->audio_codec_ctx, decoder->frame);
1808 if (ret == AVERROR(EAGAIN)) {
1809 break; // No more frames from this packet, get next packet
1810 } else if (ret < 0) {
1812 "Error receiving audio frame from decoder");
1813 goto audio_read_done;
1814 }
1815
1816 // Update position tracking
1817 decoder->last_audio_pts = get_frame_pts_seconds(
1818 decoder->frame,
1819 decoder->format_ctx->streams[decoder->audio_stream_idx]->time_base);
1820
1821 // Resample the complete frame and retain output beyond this callback's
1822 // requested block. Flushing the resampler between packets would insert
1823 // padding into inputs whose sample rate differs from the output rate.
1824 uint8_t *out_ptr = (uint8_t *)decoder->audio_buffer;
1825 int converted = traced_audio_resample(
1826 decoder->swr_ctx, &out_ptr,
1827 (int)(decoder->audio_buffer_size / TARGET_CHANNELS),
1828 (const uint8_t **)decoder->frame->data, decoder->frame->nb_samples);
1829
1830 if (converted > 0) {
1831 size_t available = (size_t)converted * TARGET_CHANNELS;
1832 size_t remaining = num_samples - samples_written;
1833 size_t to_copy = available < remaining ? available : remaining;
1834 memcpy(buffer + samples_written, decoder->audio_buffer,
1835 to_copy * sizeof(float));
1836 samples_written += to_copy;
1837 decoder->audio_buffer_offset = available - to_copy;
1838 if (decoder->audio_buffer_offset > 0)
1839 memmove(decoder->audio_buffer, decoder->audio_buffer + to_copy,
1840 decoder->audio_buffer_offset * sizeof(float));
1841 }
1842
1843 if (samples_written >= num_samples) {
1844 goto audio_read_done;
1845 }
1846 }
1847 }
1848
1849audio_read_done:
1850 // Flush resampler buffer if we haven't filled the full request
1851 // The resampler may have buffered samples that need to be output
1852 if (samples_written < num_samples &&
1853 atomic_load_bool(&decoder->eof_reached)) {
1854 int remaining_space =
1855 (int)((num_samples - samples_written) / TARGET_CHANNELS);
1856 uint8_t *out_ptr = (uint8_t *)(buffer + samples_written);
1857 int flushed = traced_audio_resample(decoder->swr_ctx, &out_ptr,
1858 remaining_space, NULL, 0);
1859 if (flushed > 0) {
1860 samples_written += (size_t)flushed * TARGET_CHANNELS;
1861 }
1862 }
1863
1864 // Update sample-based position tracking
1865 decoder->audio_samples_read += samples_written / TARGET_CHANNELS;
1866 mutex_unlock(&decoder->read_frame_mutex);
1867
1868 return samples_written;
1869}
1870
1872 return decoder && decoder->audio_stream_idx >= 0;
1873}
1874
1875/* ============================================================================
1876 * Playback Control
1877 * ============================================================================
1878 */
1879
1883
1885 double timestamp_sec) {
1886 ASCII_OTEL_SCOPE(FFMPEG_DECODER_SEEK_TO_TIMESTAMP);
1887 if (!decoder) {
1888 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing decoder for seek");
1889 }
1890
1891 if (decoder->is_stdin) {
1892 return ERROR_NOT_SUPPORTED; // Cannot seek stdin
1893 }
1894
1895 // Hold mutex during entire seek operation to prevent race with prefetch
1896 // thread
1897 mutex_lock(&decoder->prefetch_mutex);
1898
1899 // Set flag to pause prefetch thread via condition variable
1900 decoder->seeking_in_progress = true;
1901 ++decoder->seek_generation;
1902 // Serialize codec and partial-audio state with the existing packet reader.
1903 mutex_lock(&decoder->read_frame_mutex);
1904 // The old reader has stopped. Holding both guards prevents another read;
1905 // the seek must not cancel its own I/O through the interrupt callback.
1906 decoder->seeking_in_progress = false;
1907 if (decoder->format_ctx->pb && decoder->format_ctx->pb->error == AVERROR_EXIT)
1908 decoder->format_ctx->pb->error = 0;
1909
1910 // Convert seconds to FFmpeg time base units (AV_TIME_BASE = 1,000,000)
1911 int64_t target_ts = (int64_t)(timestamp_sec * AV_TIME_BASE);
1912
1913 // For HTTP streams, use simple keyframe seeking (faster than frame-accurate
1914 // seeking) HTTP seeking is expensive and can break stream state, so prefer
1915 // speed over precision
1916 int seek_ret =
1917 av_seek_frame(decoder->format_ctx, -1, target_ts, AVSEEK_FLAG_BACKWARD);
1918 if (seek_ret < 0) {
1919 // Fallback: try without backward flag
1920 seek_ret = av_seek_frame(decoder->format_ctx, -1, target_ts, 0);
1921 }
1922
1923 if (seek_ret < 0) {
1924 decoder->seeking_in_progress = false;
1925 mutex_unlock(&decoder->read_frame_mutex);
1926 cond_signal(&decoder->prefetch_cond);
1927 mutex_unlock(&decoder->prefetch_mutex);
1929 "Failed to seek to timestamp %.2f seconds", timestamp_sec);
1930 }
1931
1932 // Flush codec buffers AFTER seeking
1933 if (decoder->video_codec_ctx) {
1934 avcodec_flush_buffers(decoder->video_codec_ctx);
1935 }
1936 if (decoder->audio_codec_ctx) {
1937 avcodec_flush_buffers(decoder->audio_codec_ctx);
1938 }
1939
1940 // Reset state
1941 atomic_store_bool(&decoder->eof_reached, false);
1942 decoder->video_draining = false;
1943 decoder->audio_buffer_offset = 0;
1944 // Clear any stale audio data in buffer
1945 if (decoder->audio_buffer) {
1946 memset(decoder->audio_buffer, 0,
1947 decoder->audio_buffer_size * sizeof(float));
1948 }
1949 decoder->last_video_pts = -1.0;
1950 decoder->last_audio_pts = -1.0;
1951 decoder->prefetch_frame_ready = false;
1952 // Set audio_samples_read to match the seek target so position tracking works
1953 // correctly
1954 decoder->audio_samples_read =
1955 (uint64_t)(timestamp_sec * decoder->audio_sample_rate);
1956
1957 // The consumer retains its image across seeks until it takes a replacement.
1958
1959 // Resume prefetch thread
1960 decoder->seeking_in_progress = false;
1961 mutex_unlock(&decoder->read_frame_mutex);
1962 cond_signal(&decoder->prefetch_cond);
1963
1964 // Release mutex - prefetch thread can resume
1965 mutex_unlock(&decoder->prefetch_mutex);
1966
1967 return ASCIICHAT_OK;
1968}
1969
1971 return decoder && atomic_load_bool(&decoder->eof_reached);
1972}
1973
1975 if (!decoder || !decoder->format_ctx) {
1976 return -1.0;
1977 }
1978
1979 if (decoder->format_ctx->duration == AV_NOPTS_VALUE) {
1980 return -1.0;
1981 }
1982
1983 return (double)decoder->format_ctx->duration / AV_TIME_BASE;
1984}
1985
1987 if (!decoder) {
1988 return -1.0;
1989 }
1990
1991 // Prefer sample-based position tracking (continuous, works before frames are
1992 // decoded)
1993 if (decoder->audio_sample_rate > 0) {
1994 return (double)decoder->audio_samples_read /
1995 (double)decoder->audio_sample_rate;
1996 }
1997
1998 // Fallback to frame-based position if available
1999 if (decoder->last_video_pts >= 0.0) {
2000 return decoder->last_video_pts;
2001 } else if (decoder->last_audio_pts >= 0.0) {
2002 return decoder->last_audio_pts;
2003 }
2004
2005 return -1.0;
2006}
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)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_checkpoint(void)
asciichat_errno_scope_t errno_scope_begin(void)
asciichat_error_t errno_import(const asciichat_error_context_t *cause)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
#define HAS_ERRNO_CODE_SINCE(scope, code)
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.
Named object registry for debugging — log identifiable resource names.
🎞️ FFmpeg-based media decoder for video and audio streams
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
#define NAMED_REGISTER_FFMPEG_DECODER(decoder, name, parent_ptr)
Register an FFmpeg decoder with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEDIA_SEEK
Definition error_codes.h:73
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_MEDIA_DECODE
Definition error_codes.h:72
@ ERROR_INVALID_PARAM
@ ERROR_MEDIA_OPEN
Definition error_codes.h:71
@ ERROR_THREAD
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:74
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#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 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.
void ffmpeg_decoder_stop_prefetch(ffmpeg_decoder_t *decoder)
Stop the background frame prefetching thread.
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.
asciichat_error_t ffmpeg_decoder_rewind(ffmpeg_decoder_t *decoder)
Seek to beginning of media.
asciichat_error_t ffmpeg_decoder_get_video_dimensions(ffmpeg_decoder_t *decoder, int *width, int *height)
Get video dimensions.
ffmpeg_frame_status_t
Decode next video frame.
bool ffmpeg_decoder_has_audio(ffmpeg_decoder_t *decoder)
Check if decoder has audio stream.
bool ffmpeg_decoder_is_prefetch_running(ffmpeg_decoder_t *decoder)
Check if background frame prefetching thread is running.
asciichat_error_t ffmpeg_decoder_start_prefetch(ffmpeg_decoder_t *decoder)
Start the background frame prefetching thread.
asciichat_error_t ffmpeg_decoder_seek_to_timestamp(ffmpeg_decoder_t *decoder, double timestamp_sec)
Seek to specific timestamp in media.
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.
ffmpeg_decoder_t * ffmpeg_decoder_create(const char *path)
Create FFmpeg decoder from file path.
size_t ffmpeg_decoder_read_audio_samples(ffmpeg_decoder_t *decoder, float *buffer, size_t num_samples)
Decode audio samples.
ffmpeg_frame_status_t ffmpeg_decoder_poll_video(ffmpeg_decoder_t *decoder, image_t **frame, asciichat_error_context_t *failure)
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.
@ FFMPEG_FRAME_READY
@ FFMPEG_FRAME_WAITING
@ FFMPEG_FRAME_FAILED
@ FFMPEG_FRAME_EOF
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:406
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define NS_PER_MS_INT
Definition time.h:172
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
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:181
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.
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:106
📝 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:719
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:716
ffmpeg_decoder_t * ffmpeg_decoder_create_interruptible(const char *path, bool(*cancel)(void *), void *data)
#define MEDIA_FFMPEG_DECODER_DECODER_NAME_BUFFER_SIZE
#define TARGET_CHANNELS
#define AVIO_BUFFER_SIZE
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 TARGET_SAMPLE_RATE
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
int platform_strncasecmp(const char *s1, const char *s2, size_t n)
🔤 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
FFmpeg decoder state for video and audio decoding.
mutex_t prefetch_mutex
Protect prefetch state and FFmpeg decoder access.
uint64_t audio_samples_read
Total audio samples decoded and output.
AVCodecContext * video_codec_ctx
Video codec context.
image_t * prefetch_image_a
First prefetch buffer.
AVFormatContext * format_ctx
FFmpeg format/container context.
_Atomic bool seeking_in_progress
Signal to pause prefetch thread during seek.
platform_thread_t prefetch_thread
Prefetch thread handle.
atomic_t eof_reached
Whether end of file was reached.
atomic_ptr_t exit_callback_user_data
User data for exit callback.
bool prefetch_thread_running
Whether prefetch thread is active.
size_t audio_buffer_offset
Current offset in audio buffer.
image_t * prefetch_image_b
Second prefetch buffer.
atomic_ptr_t should_exit_callback
Callback to check if app should exit.
cond_t prefetch_cond
Condition variable for pausing during seek.
AVIOContext * avio_ctx
Custom I/O context for stdin.
bool video_draining
Whether EOF was sent to the video decoder.
struct SwrContext * swr_ctx
Software resampler for format conversion.
AVPacket * packet
Reusable packet for reading.
int video_stream_idx
Video stream index (-1 if none).
_Atomic bool prefetch_should_stop
Signal to stop prefetch thread.
unsigned char * avio_buffer
Buffer for custom I/O.
double last_audio_pts
Last audio presentation timestamp.
AVCodecContext * audio_codec_ctx
Audio codec context.
bool is_stdin
Whether reading from stdin.
int audio_sample_rate
Audio sample rate (Hz).
size_t audio_buffer_size
Total size of audio buffer.
image_t * current_prefetch_image
Currently available prefetched frame.
float * audio_buffer
Buffer for partial audio frames.
double last_video_pts
Last video presentation timestamp.
_Atomic bool prefetch_frame_ready
Whether current_prefetch_image has valid data.
asciichat_error_context_t prefetch_failure
_Atomic uint64_t seek_generation
Detect seeks before and after packet reads.
int audio_stream_idx
Audio stream index (-1 if none).
AVFrame * frame
Reusable frame for decoding.
image_t * current_image
Working buffer for decoding.
struct SwsContext * sws_ctx
Software scaler for format conversion.
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).
size_t pos
Current read position (per-decoder).
stdin_buffer_t * buffer
Pointer to shared buffer.
uint8_t * data
Buffered data (shared between decoders).
size_t size
Total size of buffered data.
⏱️ High-precision timing utilities using sokol_time.h and uthash
🌐 Production-Grade URL Validation and Parsing