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

🎞️ FFmpeg-based media decoder for video and audio streams More...

Go to the source code of this file.

Typedefs

typedef struct ffmpeg_decoder_t ffmpeg_decoder_t
 Opaque FFmpeg decoder handle.

Enumerations

enum  ffmpeg_frame_status_t { FFMPEG_FRAME_READY , FFMPEG_FRAME_WAITING , FFMPEG_FRAME_EOF , FFMPEG_FRAME_FAILED }
 Decode next video frame. More...

Functions

ffmpeg_decoder_t * ffmpeg_decoder_create (const char *path)
 Create FFmpeg decoder from file path.
ffmpeg_decoder_t * ffmpeg_decoder_create_stdin (void)
 Create FFmpeg decoder from stdin.
void ffmpeg_decoder_destroy (ffmpeg_decoder_t *decoder)
 Destroy FFmpeg decoder and free resources.
asciichat_error_t ffmpeg_decoder_start_prefetch (ffmpeg_decoder_t *decoder)
 Start background frame prefetching thread.
void ffmpeg_decoder_stop_prefetch (ffmpeg_decoder_t *decoder)
 Stop background frame prefetching thread.
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.
bool ffmpeg_decoder_is_prefetch_running (ffmpeg_decoder_t *decoder)
 Check if background frame prefetching thread is running.
ffmpeg_frame_status_t ffmpeg_decoder_poll_video (ffmpeg_decoder_t *decoder, image_t **frame, asciichat_error_context_t *failure)
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.
asciichat_error_t ffmpeg_decoder_get_video_dimensions (ffmpeg_decoder_t *decoder, int *width, int *height)
 Get video dimensions.
double ffmpeg_decoder_get_video_fps (ffmpeg_decoder_t *decoder)
 Get video frame rate.
size_t ffmpeg_decoder_read_audio_samples (ffmpeg_decoder_t *decoder, float *buffer, size_t num_samples)
 Decode audio samples.
bool ffmpeg_decoder_has_audio (ffmpeg_decoder_t *decoder)
 Check if decoder has audio stream.
asciichat_error_t ffmpeg_decoder_rewind (ffmpeg_decoder_t *decoder)
 Seek to beginning of media.
asciichat_error_t ffmpeg_decoder_seek_to_timestamp (ffmpeg_decoder_t *decoder, double timestamp_sec)
 Seek to specific timestamp in media.
bool ffmpeg_decoder_at_end (ffmpeg_decoder_t *decoder)
 Check if decoder reached end of stream.
double ffmpeg_decoder_get_duration (ffmpeg_decoder_t *decoder)
 Get media duration in seconds.
double ffmpeg_decoder_get_position (ffmpeg_decoder_t *decoder)
 Get current playback position in seconds.
ffmpeg_decoder_t * ffmpeg_decoder_create_interruptible (const char *path, bool(*cancel)(void *), void *data)
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)

Detailed Description

🎞️ FFmpeg-based media decoder for video and audio streams

Definition in file ffmpeg_decoder.h.

Function Documentation

◆ ffmpeg_decoder_create_interruptible()

ffmpeg_decoder_t * ffmpeg_decoder_create_interruptible ( const char * path,
bool(* cancel )(void *),
void * data )

Definition at line 867 of file media/ffmpeg_decoder.c.

869 {
870 return ffmpeg_decoder_create_with_request_options(path, cancel, data, NULL,
871 NULL, NULL);
872}
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)

References ffmpeg_decoder_create_with_request_options().

Referenced by ffmpeg_decoder_create(), and http_renderer_render_file().

◆ ffmpeg_decoder_create_with_request_options()

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 )

Definition at line 874 of file media/ffmpeg_decoder.c.

876 {
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}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_DISMISSED
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
#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_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_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
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void ffmpeg_decoder_destroy(ffmpeg_decoder_t *decoder)
Destroy FFmpeg decoder and free resources.
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:181
image_t * image_new(size_t width, size_t height)
Create a new image with standard allocation.
#define LOG_IO(prefix, block)
Definition io.h:106
#define MEDIA_FFMPEG_DECODER_DECODER_NAME_BUFFER_SIZE
#define TARGET_CHANNELS
#define TARGET_SAMPLE_RATE
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
int platform_strncasecmp(const char *s1, const char *s2, size_t n)
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.
mutex_t prefetch_mutex
Protect prefetch state and FFmpeg decoder access.
AVCodecContext * video_codec_ctx
Video codec context.
image_t * prefetch_image_a
First prefetch buffer.
AVFormatContext * format_ctx
FFmpeg format/container context.
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.
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.
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.
double last_audio_pts
Last audio presentation timestamp.
AVCodecContext * audio_codec_ctx
Audio codec context.
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.
int audio_stream_idx
Audio stream index (-1 if none).
AVFrame * frame
Reusable frame for decoding.
struct SwsContext * sws_ctx
Software scaler for format conversion.

References ASCII_OTEL_SCOPE, ASCIICHAT_ERRNO_DISMISSED, ASCIICHAT_OK, atomic_ptr_store(), ffmpeg_decoder_t::audio_buffer, ffmpeg_decoder_t::audio_buffer_size, ffmpeg_decoder_t::audio_codec_ctx, ffmpeg_decoder_t::audio_sample_rate, ffmpeg_decoder_t::audio_stream_idx, ffmpeg_decoder_t::current_prefetch_image, ffmpeg_decoder_t::eof_reached, errno_scope_begin(), errno_scope_end(), ERROR_INVALID_PARAM, ERROR_MEDIA_DECODE, ERROR_MEDIA_OPEN, ERROR_MEMORY, ffmpeg_decoder_t::exit_callback_user_data, ffmpeg_decoder_destroy(), ffmpeg_decoder_t::format_ctx, ffmpeg_decoder_t::frame, height, image_new(), ffmpeg_decoder_t::last_audio_pts, ffmpeg_decoder_t::last_video_pts, log_debug, LOG_IO, log_warn, MEDIA_FFMPEG_DECODER_DECODER_NAME_BUFFER_SIZE, NAMED_REGISTER_ATOMIC, NAMED_REGISTER_FFMPEG_DECODER, ffmpeg_decoder_t::packet, platform_strncasecmp(), ffmpeg_decoder_t::prefetch_cond, ffmpeg_decoder_t::prefetch_frame_ready, ffmpeg_decoder_t::prefetch_image_a, ffmpeg_decoder_t::prefetch_image_b, ffmpeg_decoder_t::prefetch_mutex, ffmpeg_decoder_t::prefetch_should_stop, ffmpeg_decoder_t::prefetch_thread_running, ffmpeg_decoder_t::read_frame_mutex, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, ffmpeg_decoder_t::should_exit_callback, ffmpeg_decoder_t::swr_ctx, ffmpeg_decoder_t::sws_ctx, TARGET_CHANNELS, TARGET_SAMPLE_RATE, url_is_valid(), ffmpeg_decoder_t::video_codec_ctx, ffmpeg_decoder_t::video_stream_idx, and width.

Referenced by ffmpeg_decoder_create_interruptible(), and media_source_create_interruptible().