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

Files

file  ffmpeg_encoder.c
 FFmpeg video/image file encoder for render-file output.
file  renderer.c
 render_file_* — ties together font resolution, platform renderer, FFmpeg encoder
file  terminal.c
 Pixel renderer for render-file: libvterm + FreeType2 software compositor.
file  yt_dlp.c
 yt-dlp stream URL extraction implementation
file  ffmpeg_decoder.c
 WASM bridge to ffmpeg.wasm for video/audio decoding.
file  codecs.h
 Video and audio codec definitions and capability bitmasks.
file  ffmpeg_decoder.h
 🎞️ FFmpeg-based media decoder for video and audio streams
file  ffmpeg_encoder.h
 FFmpeg video/image file encoder — codec selected from file extension.
file  renderer.h
 Terminal-to-pixel renderer and render-file output (audio + video).
file  source.h
 🎬 Unified media source abstraction for webcam, files, and stdin
file  yt_dlp.h
 yt-dlp stream URL extraction

Typedefs

typedef struct ffmpeg_decoder_t ffmpeg_decoder_t
 Opaque FFmpeg decoder handle.
typedef struct media_source_t media_source_t
 Opaque media source handle.

Enumerations

enum  ffmpeg_frame_status_t { FFMPEG_FRAME_READY , FFMPEG_FRAME_WAITING , FFMPEG_FRAME_EOF , FFMPEG_FRAME_FAILED }
 Decode next video frame. More...
enum  media_source_type_t { MEDIA_SOURCE_WEBCAM , MEDIA_SOURCE_FILE , MEDIA_SOURCE_STDIN , MEDIA_SOURCE_TEST }
 Media source type enumeration. 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.
media_source_t * media_source_create (media_source_type_t type, const char *path)
 Create a new media source.
void media_source_destroy (media_source_t *source)
 Destroy media source and free resources.
image_t * media_source_read_video (media_source_t *source)
 Read next video frame from media source.
bool media_source_has_video (media_source_t *source)
 Check if media source has video stream.
size_t media_source_read_audio (media_source_t *source, float *buffer, size_t num_samples)
 Read audio samples from media source.
bool media_source_has_audio (media_source_t *source)
 Check if media source has audio stream.
void media_source_set_loop (media_source_t *source, bool loop)
 Enable or disable looping.
void media_source_pause (media_source_t *source)
 Pause media playback.
void media_source_resume (media_source_t *source)
 Resume media playback after pause.
bool media_source_is_paused (media_source_t *source)
 Check if media source is paused.
void media_source_toggle_pause (media_source_t *source)
 Toggle pause state of media source.
bool media_source_at_end (media_source_t *source)
 Check if media source reached end of stream.
asciichat_error_t media_source_rewind (media_source_t *source)
 Rewind media source to beginning.
asciichat_error_t media_source_seek (media_source_t *source, double timestamp_sec)
 Seek media source to timestamp.
media_source_type_t media_source_get_type (media_source_t *source)
 Get media source type.
double media_source_get_duration (media_source_t *source)
 Get media duration in seconds.
double media_source_get_position (media_source_t *source)
 Get current playback position in seconds.
double media_source_get_video_fps (media_source_t *source)
 Get video frame rate in frames per second.
void media_source_set_audio_context (media_source_t *source, void *audio_ctx)
 Set audio context for playback buffer management.
void media_source_set_exit_callback (media_source_t *source, bool(*should_exit_callback)(void *), void *user_data)
 Set exit signal callback for graceful shutdown during I/O.
asciichat_error_t yt_dlp_extract_stream_urls (const char *url, const char *yt_dlp_options, char *output_url, size_t output_size, char *audio_url, size_t audio_size)
 For yt dlp request options, this is the live record that ties proxy_specified together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.
bool yt_dlp_is_available (void)
 Check if yt-dlp is installed and accessible.

Video Codec Bitmask Constants

Bitmasks for video codec capabilities

Each codec is represented by a single bit, allowing multiple codecs to be advertised simultaneously in the codec_capabilities_video field.

#define VIDEO_CODEC_CAP_ALL
 Default video codec capabilities (all codecs supported).

Audio Codec Bitmask Constants

Bitmasks for audio codec capabilities

Each codec is represented by a single bit, allowing multiple codecs to be advertised simultaneously in the codec_capabilities_audio field.

#define AUDIO_CAP_STEREO    ((uint32_t)(1u << 8))
 Default audio codec capabilities (all codecs supported).
#define VIDEO_CODEC_SUPPORTED(cap, codec)
 Check if a video codec is supported in capabilities bitmask.
#define AUDIO_CODEC_SUPPORTED(cap, codec)
 Check if an audio codec is supported in capabilities bitmask.

Detailed Description

This header provides FFmpeg integration for decoding various media formats. It wraps FFmpeg's complex API into a simple interface for extracting RGB video frames and float audio samples.

CORE FEATURES:

  • Multi-format container support (mp4, avi, mkv, webm, etc.)
  • Video decoding to RGB24 format
  • Audio decoding to 48kHz interleaved stereo float
  • Stdin input support via custom AVIOContext
  • Seeking for loop support
  • Automatic stream detection

FFMPEG LIBRARIES USED:

  • libavformat: Container demuxing
  • libavcodec: Video/audio codec decoding
  • libavutil: Utilities and error handling
  • libswscale: Video format conversion (YUV -> RGB)
  • libswresample: Audio resampling (any rate -> 48kHz stereo)

SUPPORTED CODECS:

  • Video: H.264, H.265, VP8, VP9, AV1, MPEG-4, etc.
  • Audio: AAC, MP3, Opus, Vorbis, FLAC, PCM, etc.
  • Containers: MP4, AVI, MKV, WebM, MOV, FLV, GIF, etc.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026

This header provides a unified interface for media sources in ascii-chat, abstracting over webcams, media files, and stdin input. This allows the capture thread to work with any media source transparently.

CORE FEATURES:

  • Unified API for webcam, files, and stdin
  • FFmpeg-based decoding for all common formats
  • Video frame extraction (RGB format)
  • Audio sample extraction (48kHz interleaved stereo float)
  • Loop support for file playback
  • Automatic format detection

SUPPORTED SOURCES:

  • MEDIA_SOURCE_WEBCAM: Hardware webcam device
  • MEDIA_SOURCE_FILE: Media file (mp4, avi, mkv, gif, mp3, etc.)
  • MEDIA_SOURCE_STDIN: Piped or redirected media data
  • MEDIA_SOURCE_TEST: Test pattern (existing)

SUPPORTED FORMATS:

  • Video: mp4, avi, mkv, webm, mov, flv, wmv, gif (animated)
  • Audio: mp3, aac, opus, flac, wav, ogg, m4a
  • Images: gif, png, jpg (static - single frame)

COMMAND-LINE EXAMPLES:

# Webcam preview with a deterministic source instead of a camera
ascii-chat mirror --test-pattern --color-mode 256
# Play a file repeatedly, starting at one minute and thirty seconds
ascii-chat mirror --file "demo recording.mp4" --loop --seek 01:30
# Decode a URL through the normal FFmpeg/yt-dlp resolver
ascii-chat mirror --url "https://example.com/clip.m3u8"
# Feed any FFmpeg-readable format through stdin
ffmpeg -i input.mkv -f matroska - | ascii-chat mirror --file -

PROGRAMMATIC EXAMPLE:

if (!source) return ERROR_MEDIA;
for (;;) {
if (frame) {
render_frame(frame);
continue;
}
// A temporary decode miss is not EOF; let the capture loop try again.
}
float samples[960]; // 20 ms of interleaved 48 kHz stereo float audio
size_t count = media_source_read_audio(source, samples, 960);
(void)count;
audio_visualization_source_t source
Definition fft.c:25
bool media_source_at_end(media_source_t *source)
Check if media source reached end of stream.
Definition source.c:922
size_t media_source_read_audio(media_source_t *source, float *buffer, size_t num_samples)
Read audio samples from media source.
Definition source.c:795
void media_source_destroy(media_source_t *source)
Destroy media source and free resources.
Definition source.c:561
image_t * media_source_read_video(media_source_t *source)
Read next video frame from media source.
Definition source.c:653
media_source_t * media_source_create(media_source_type_t type, const char *path)
Create a new media source.
Definition source.c:243
void media_source_set_loop(media_source_t *source, bool loop)
Enable or disable looping.
Definition source.c:910
@ MEDIA_SOURCE_FILE
Media file (video/audio).
Definition source.h:104
Media source for video and audio capture.
Definition source.c:48
Note
The CLI examples use the same media-source abstraction as the C API.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026

Macro Definition Documentation

◆ AUDIO_CAP_STEREO

#define AUDIO_CAP_STEREO    ((uint32_t)(1u << 8))

#include <include/ascii-chat/media/codecs.h>

Default audio codec capabilities (all codecs supported).

Interleaved stereo PCM and stereo Opus output

Definition at line 87 of file codecs.h.

87#define AUDIO_CAP_STEREO \
88 ((uint32_t)(1u << 8))

◆ AUDIO_CODEC_SUPPORTED

#define AUDIO_CODEC_SUPPORTED ( cap,
codec )

#include <include/ascii-chat/media/codecs.h>

Value:
(((cap) & (1 << (codec))) != 0)

Check if an audio codec is supported in capabilities bitmask.

Parameters
capCodec capabilities bitmask (AUDIO_CODEC_CAP_*)
codecCodec type to check (audio_codec_t)
Returns
true if codec is supported, false otherwise

Definition at line 108 of file codecs.h.

◆ VIDEO_CODEC_CAP_ALL

#define VIDEO_CODEC_CAP_ALL

#include <include/ascii-chat/media/codecs.h>

Value:
#define VIDEO_CODEC_CAP_H265
Bit 1: H.265 support.
Definition codecs.h:45
#define VIDEO_CODEC_CAP_RGBA
Bit 0: RGBA support.
Definition codecs.h:43
#define VIDEO_CODEC_CAP_H264
Bit 3: H.264 support.
Definition codecs.h:49
#define VIDEO_CODEC_CAP_JPEG
Bit 2: JPEG support.
Definition codecs.h:47

Default video codec capabilities (all codecs supported).

Definition at line 56 of file codecs.h.

56#define VIDEO_CODEC_CAP_ALL \
57 (VIDEO_CODEC_CAP_H264 | VIDEO_CODEC_CAP_RGBA | VIDEO_CODEC_CAP_H265 | \
58 VIDEO_CODEC_CAP_JPEG)

Referenced by session_protocol_build_capabilities().

◆ VIDEO_CODEC_SUPPORTED

#define VIDEO_CODEC_SUPPORTED ( cap,
codec )

#include <include/ascii-chat/media/codecs.h>

Value:
(((cap) & (1 << (codec))) != 0)

Check if a video codec is supported in capabilities bitmask.

Parameters
capCodec capabilities bitmask (VIDEO_CODEC_CAP_*)
codecCodec type to check (video_codec_t)
Returns
true if codec is supported, false otherwise

Definition at line 99 of file codecs.h.

Referenced by handle_image_frame_h265_packet(), and handle_image_frame_packet().

Typedef Documentation

◆ ffmpeg_decoder_t

typedef struct ffmpeg_decoder_t ffmpeg_decoder_t

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Opaque FFmpeg decoder handle.

Forward declaration of FFmpeg decoder structure. Use ffmpeg_decoder_create() to create and ffmpeg_decoder_destroy() to cleanup.

Definition at line 64 of file ffmpeg_decoder.h.

◆ media_source_t

typedef struct media_source_t media_source_t

#include <include/ascii-chat/media/source.h>

Opaque media source handle.

Forward declaration of media source structure. Use media_source_create() to create and media_source_destroy() to cleanup.

THREAD SAFETY:

  • media_source_read_video() and media_source_read_audio() may be called from different threads (e.g., video render thread + audio callback thread)
  • Both operations access the shared FFmpeg decoder
  • FFmpeg decoders are NOT thread-safe for concurrent operations
  • media_source_t uses internal synchronization to protect decoder access
  • Callers do NOT need external locking

Definition at line 126 of file source.h.

Enumeration Type Documentation

◆ ffmpeg_frame_status_t

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Decode next video frame.

Parameters
decoderDecoder (must not be NULL)
Returns
Pointer to image_t frame, or NULL on error/EOF

Decodes the next video frame from the media stream. Returns an image_t structure in RGB24 format.

Frame format:

  • Pixel format: RGB24 (8 bits per channel)
  • Dimensions: Original video dimensions
  • Memory: Owned by decoder (do NOT free)

Return values:

Decoding process:

  1. Read packet from format context
  2. Send packet to video decoder
  3. Receive decoded frame
  4. Convert frame to RGB24 using swscale
  5. Wrap in image_t structure
Note
Returned frame is valid until next call or decoder destruction
Skips non-video packets automatically
Enumerator
FFMPEG_FRAME_READY 
FFMPEG_FRAME_WAITING 
FFMPEG_FRAME_EOF 
FFMPEG_FRAME_FAILED 

Definition at line 238 of file ffmpeg_decoder.h.

238 {
ffmpeg_frame_status_t
Decode next video frame.
@ FFMPEG_FRAME_READY
@ FFMPEG_FRAME_WAITING
@ FFMPEG_FRAME_FAILED
@ FFMPEG_FRAME_EOF

◆ media_source_type_t

#include <include/ascii-chat/media/source.h>

Media source type enumeration.

Identifies the type of media source being used.

Enumerator
MEDIA_SOURCE_WEBCAM 

Hardware webcam device.

MEDIA_SOURCE_FILE 

Media file (video/audio).

MEDIA_SOURCE_STDIN 

Piped or redirected input.

MEDIA_SOURCE_TEST 

Test pattern generator.

Definition at line 102 of file source.h.

102 {
media_source_type_t
Media source type enumeration.
Definition source.h:102
@ MEDIA_SOURCE_STDIN
Piped or redirected input.
Definition source.h:105
@ MEDIA_SOURCE_WEBCAM
Hardware webcam device.
Definition source.h:103
@ MEDIA_SOURCE_TEST
Test pattern generator.
Definition source.h:106

Function Documentation

◆ ffmpeg_decoder_at_end()

bool ffmpeg_decoder_at_end ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Check if decoder reached end of stream.

Parameters
decoderDecoder (must not be NULL)
Returns
true if EOF reached, false otherwise

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

1970 {
1971 return decoder && atomic_load_bool(&decoder->eof_reached);
1972}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
atomic_t eof_reached
Whether end of file was reached.

References atomic_load_bool(), and ffmpeg_decoder_t::eof_reached.

Referenced by ffmpeg_decoder_poll_video(), media_source_at_end(), media_source_read_audio(), and media_source_read_video().

◆ ffmpeg_decoder_create()

ffmpeg_decoder_t * ffmpeg_decoder_create ( const char * path)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Create FFmpeg decoder from file path.

Parameters
pathFile path to media file (must not be NULL)
Returns
Pointer to decoder, or NULL on failure

Creates and initializes an FFmpeg decoder for the specified file. Opens the file, detects streams, and initializes codecs.

Initialization process:

  1. Open format context (avformat_open_input)
  2. Find stream information (avformat_find_stream_info)
  3. Detect video and audio streams
  4. Open codec contexts for detected streams
  5. Initialize swscale/swresample contexts
Note
Sets errno context on failure
Call ffmpeg_decoder_destroy() to cleanup

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

863 {
864 return ffmpeg_decoder_create_interruptible(path, NULL, NULL);
865}
ffmpeg_decoder_t * ffmpeg_decoder_create_interruptible(const char *path, bool(*cancel)(void *), void *data)

References ffmpeg_decoder_create_interruptible().

◆ ffmpeg_decoder_create_stdin()

ffmpeg_decoder_t * ffmpeg_decoder_create_stdin ( void )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Create FFmpeg decoder from stdin.

Returns
Pointer to decoder, or NULL on failure

Creates an FFmpeg decoder that reads from stdin using a custom AVIOContext. This allows piping media data directly into ascii-chat.

Usage:

cat video.mp4 | ascii-chat client --file -
ffmpeg -i input.avi -f matroska - | ascii-chat client --file -

Limitations:

  • Cannot seek (no loop support)
  • Some formats may not work well with stdin (require seekable input)
  • Recommend using formats designed for streaming (matroska, mpegts)
Note
Sets errno context on failure
Call ffmpeg_decoder_destroy() to cleanup

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

1166 {
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}
#define SET_ERRNO(code,...)
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_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.
#define GET_OPTION(field)
Definition options.h:1339
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 TARGET_CHANNELS
#define AVIO_BUFFER_SIZE
#define TARGET_SAMPLE_RATE
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
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.
image_t * prefetch_image_b
Second prefetch buffer.
cond_t prefetch_cond
Condition variable for pausing during seek.
AVIOContext * avio_ctx
Custom I/O context for stdin.
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).
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.
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.
size_t pos
Current read position (per-decoder).
stdin_buffer_t * buffer
Pointer to shared buffer.

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ffmpeg_decoder_t::audio_buffer, ffmpeg_decoder_t::audio_buffer_size, ffmpeg_decoder_t::audio_codec_ctx, ffmpeg_decoder_t::audio_stream_idx, ffmpeg_decoder_t::avio_buffer, AVIO_BUFFER_SIZE, ffmpeg_decoder_t::avio_ctx, stdin_buffer_reader_t::buffer, ffmpeg_decoder_t::current_prefetch_image, ffmpeg_decoder_t::eof_reached, ERROR_MEDIA_DECODE, ERROR_MEDIA_OPEN, ERROR_MEMORY, ffmpeg_decoder_destroy(), ffmpeg_decoder_t::format_ctx, ffmpeg_decoder_t::frame, GET_OPTION, height, image_new(), ffmpeg_decoder_t::is_stdin, ffmpeg_decoder_t::last_audio_pts, ffmpeg_decoder_t::last_video_pts, log_debug, LOG_IO, log_warn, NAMED_REGISTER_ATOMIC, NAMED_REGISTER_FFMPEG_DECODER, ffmpeg_decoder_t::packet, stdin_buffer_reader_t::pos, 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::read_frame_mutex, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, ffmpeg_decoder_t::swr_ctx, ffmpeg_decoder_t::sws_ctx, TARGET_CHANNELS, TARGET_SAMPLE_RATE, ffmpeg_decoder_t::video_codec_ctx, ffmpeg_decoder_t::video_stream_idx, and width.

Referenced by media_source_create_interruptible().

◆ ffmpeg_decoder_destroy()

void ffmpeg_decoder_destroy ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Destroy FFmpeg decoder and free resources.

Parameters
decoderDecoder to destroy (can be NULL)

Cleans up FFmpeg decoder and releases all resources. Safe to call with NULL. Automatically stops the background prefetch thread if running.

Cleanup process:

  1. Stop prefetch thread if running
  2. Free video frame ringbuffer
  3. Free swscale/swresample contexts
  4. Close codec contexts
  5. Close format context
  6. Free frame and packet structures
  7. Free decoder structure

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

1453 {
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}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
void image_destroy(image_t *image)
Destroy an image allocated with image_new().
platform_thread_t prefetch_thread
Prefetch thread handle.
bool prefetch_thread_running
Whether prefetch thread is active.
_Atomic bool prefetch_should_stop
Signal to stop prefetch thread.
image_t * current_image
Working buffer for decoding.

References ASCII_OTEL_SCOPE, ffmpeg_decoder_t::audio_buffer, ffmpeg_decoder_t::audio_codec_ctx, ffmpeg_decoder_t::avio_ctx, ffmpeg_decoder_t::current_image, ffmpeg_decoder_t::eof_reached, ffmpeg_decoder_t::format_ctx, ffmpeg_decoder_t::frame, image_destroy(), ffmpeg_decoder_t::is_stdin, NAMED_UNREGISTER, ffmpeg_decoder_t::packet, ffmpeg_decoder_t::prefetch_cond, 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, ffmpeg_decoder_t::prefetch_thread_running, ffmpeg_decoder_t::read_frame_mutex, SAFE_FREE, ffmpeg_decoder_t::swr_ctx, ffmpeg_decoder_t::sws_ctx, and ffmpeg_decoder_t::video_codec_ctx.

Referenced by ffmpeg_decoder_create_stdin(), ffmpeg_decoder_create_with_request_options(), http_renderer_render_file(), media_source_create_interruptible(), and media_source_destroy().

◆ ffmpeg_decoder_get_duration()

double ffmpeg_decoder_get_duration ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Get media duration in seconds.

Parameters
decoderDecoder (must not be NULL)
Returns
Duration in seconds, or -1.0 if unknown

Returns the total duration from the container metadata.

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

1974 {
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}

References ffmpeg_decoder_t::format_ctx.

Referenced by media_source_get_duration().

◆ ffmpeg_decoder_get_position()

double ffmpeg_decoder_get_position ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Get current playback position in seconds.

Parameters
decoderDecoder (must not be NULL)
Returns
Current position in seconds, or -1.0 if unknown

Returns the presentation timestamp of the last decoded frame.

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

1986 {
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}
uint64_t audio_samples_read
Total audio samples decoded and output.
int audio_sample_rate
Audio sample rate (Hz).

References ffmpeg_decoder_t::audio_sample_rate, ffmpeg_decoder_t::audio_samples_read, ffmpeg_decoder_t::last_audio_pts, and ffmpeg_decoder_t::last_video_pts.

Referenced by media_source_get_position(), media_source_read_audio(), and media_source_seek().

◆ ffmpeg_decoder_get_video_dimensions()

asciichat_error_t ffmpeg_decoder_get_video_dimensions ( ffmpeg_decoder_t * decoder,
int * width,
int * height )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Get video dimensions.

Parameters
decoderDecoder (must not be NULL)
widthOutput pointer for width (can be NULL)
heightOutput pointer for height (can be NULL)
Returns
ASCIICHAT_OK on success, error code if no video stream

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

1691 {
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}
@ ERROR_INVALID_PARAM

References ASCIICHAT_OK, ERROR_INVALID_PARAM, height, SET_ERRNO, ffmpeg_decoder_t::video_codec_ctx, ffmpeg_decoder_t::video_stream_idx, and width.

◆ ffmpeg_decoder_get_video_fps()

double ffmpeg_decoder_get_video_fps ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Get video frame rate.

Parameters
decoderDecoder (must not be NULL)
Returns
Frame rate in FPS, or -1.0 if unknown/no video

Returns the average frame rate of the video stream.

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

1706 {
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}

References ffmpeg_decoder_t::format_ctx, and ffmpeg_decoder_t::video_stream_idx.

Referenced by media_source_get_video_fps().

◆ ffmpeg_decoder_has_audio()

bool ffmpeg_decoder_has_audio ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Check if decoder has audio stream.

Parameters
decoderDecoder (must not be NULL)
Returns
true if audio stream exists, false otherwise

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

1871 {
1872 return decoder && decoder->audio_stream_idx >= 0;
1873}

References ffmpeg_decoder_t::audio_stream_idx.

Referenced by media_source_create_interruptible(), and media_source_has_audio().

◆ ffmpeg_decoder_has_video()

bool ffmpeg_decoder_has_video ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Check if decoder has video stream.

Parameters
decoderDecoder (must not be NULL)
Returns
true if video stream exists, false otherwise

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

1686 {
1687 return decoder && decoder->video_stream_idx >= 0;
1688}

References ffmpeg_decoder_t::video_stream_idx.

Referenced by media_source_create_interruptible(), and media_source_has_video().

◆ ffmpeg_decoder_is_prefetch_running()

bool ffmpeg_decoder_is_prefetch_running ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Check if background frame prefetching thread is running.

Parameters
decoderDecoder (must not be NULL)
Returns
true if prefetch thread is running, false otherwise

Utility function to check if the prefetch thread is currently active. Used during seeking to determine if thread needs to be stopped/restarted.

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

1679 {
1680 if (!decoder) {
1681 return false;
1682 }
1683 return decoder->prefetch_thread_running;
1684}

References ffmpeg_decoder_t::prefetch_thread_running.

◆ ffmpeg_decoder_poll_video()

ffmpeg_frame_status_t ffmpeg_decoder_poll_video ( ffmpeg_decoder_t * decoder,
image_t ** frame,
asciichat_error_context_t * failure )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Failure is an owned snapshot; no worker stack or thread lifetime dependency.

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

1548 {
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}
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
asciichat_errno_scope_t errno_checkpoint(void)
bool ffmpeg_decoder_at_end(ffmpeg_decoder_t *decoder)
Check if decoder reached end of stream.
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
asciichat_error_context_t prefetch_failure

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ffmpeg_decoder_t::buffer_a_in_use, ffmpeg_decoder_t::buffer_b_in_use, asciichat_error_context_t::code, ffmpeg_decoder_t::current_image, ffmpeg_decoder_t::current_prefetch_image, ffmpeg_decoder_t::current_read_buffer, errno_checkpoint(), errno_peek_since(), ERROR_INVALID_PARAM, ffmpeg_decoder_at_end(), FFMPEG_FRAME_EOF, FFMPEG_FRAME_FAILED, FFMPEG_FRAME_READY, FFMPEG_FRAME_WAITING, ffmpeg_decoder_t::prefetch_cond, ffmpeg_decoder_t::prefetch_failed, ffmpeg_decoder_t::prefetch_failure, ffmpeg_decoder_t::prefetch_frame_ready, ffmpeg_decoder_t::prefetch_image_a, ffmpeg_decoder_t::prefetch_image_b, ffmpeg_decoder_t::prefetch_mutex, and SET_ERRNO.

Referenced by ffmpeg_decoder_read_video_frame(), and http_renderer_render_file().

◆ ffmpeg_decoder_read_audio_samples()

size_t ffmpeg_decoder_read_audio_samples ( ffmpeg_decoder_t * decoder,
float * buffer,
size_t num_samples )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Decode audio samples.

Parameters
decoderDecoder (must not be NULL)
bufferOutput buffer for samples (must not be NULL)
num_samplesNumber of samples to read
Returns
Number of samples actually read (0 to num_samples)

Decodes audio samples from the media stream. Samples are resampled to 48kHz interleaved stereo float format, compatible with ascii-chat's Opus encoding.

Audio format:

  • Format: 32-bit float
  • Channels: Stereo (2 channels); sample counts include both channels
  • Sample rate: 48000 Hz
  • Range: -1.0 to 1.0

Decoding process:

  1. Read packet from format context
  2. Send packet to audio decoder
  3. Receive decoded frame
  4. Resample to 48kHz stereo using swresample
  5. Copy to output buffer
Note
Skips non-audio packets automatically
May return fewer samples than requested at EOF

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

1732 {
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}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
unsigned long long uint64_t
unsigned char uint8_t
#define US_PER_SEC_INT
Definition time.h:177
#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
size_t audio_buffer_offset
Current offset in audio buffer.

References ASCII_OTEL_SCOPE, atomic_load_bool(), atomic_store_bool(), ffmpeg_decoder_t::audio_buffer, ffmpeg_decoder_t::audio_buffer_offset, ffmpeg_decoder_t::audio_buffer_size, ffmpeg_decoder_t::audio_codec_ctx, ffmpeg_decoder_t::audio_samples_read, ffmpeg_decoder_t::audio_stream_idx, ffmpeg_decoder_t::eof_reached, ffmpeg_decoder_t::format_ctx, ffmpeg_decoder_t::frame, ffmpeg_decoder_t::last_audio_pts, log_debug_every, log_warn_every, ffmpeg_decoder_t::packet, ffmpeg_decoder_t::read_frame_mutex, ffmpeg_decoder_t::swr_ctx, TARGET_CHANNELS, and US_PER_SEC_INT.

Referenced by media_source_read_audio().

◆ ffmpeg_decoder_read_video_frame()

image_t * ffmpeg_decoder_read_video_frame ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

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

1596 {
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}
asciichat_error_t errno_import(const asciichat_error_context_t *cause)
ffmpeg_frame_status_t ffmpeg_decoder_poll_video(ffmpeg_decoder_t *decoder, image_t **frame, asciichat_error_context_t *failure)

References ASCII_OTEL_SCOPE, errno_import(), ffmpeg_decoder_poll_video(), and FFMPEG_FRAME_FAILED.

Referenced by media_source_read_video().

◆ ffmpeg_decoder_rewind()

asciichat_error_t ffmpeg_decoder_rewind ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Seek to beginning of media.

Parameters
decoderDecoder (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Seeks to the beginning of the media file. Used for loop implementation.

Seek process:

  1. Flush codec buffers (avcodec_flush_buffers)
  2. Seek to timestamp 0 (av_seek_frame)
  3. Clear decoder state
Note
Stdin decoders cannot seek (returns ERROR_NOT_SUPPORTED)
Some formats may not support seeking

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

1880 {
1881 return ffmpeg_decoder_seek_to_timestamp(decoder, 0);
1882}
asciichat_error_t ffmpeg_decoder_seek_to_timestamp(ffmpeg_decoder_t *decoder, double timestamp_sec)
Seek to specific timestamp in media.

References ffmpeg_decoder_seek_to_timestamp().

Referenced by media_source_rewind().

◆ ffmpeg_decoder_seek_to_timestamp()

asciichat_error_t ffmpeg_decoder_seek_to_timestamp ( ffmpeg_decoder_t * decoder,
double timestamp_sec )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Seek to specific timestamp in media.

Parameters
decoderDecoder (must not be NULL)
timestamp_secSeek target in seconds
Returns
ASCIICHAT_OK on success, error code on failure

Seeks to the specified timestamp in the media file. Used for audio/video synchronization in multi-decoder scenarios.

Seek process:

  1. Flush codec buffers (avcodec_flush_buffers)
  2. Seek to timestamp (av_seek_frame with AV_TIME_BASE conversion)
  3. Clear decoder state
Note
Stdin decoders cannot seek (returns ERROR_NOT_SUPPORTED)
Some formats may not support seeking
Seeks approximately - may land before/after exact timestamp

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

1885 {
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}
@ ERROR_MEDIA_SEEK
Definition error_codes.h:73
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:74
_Atomic bool seeking_in_progress
Signal to pause prefetch thread during seek.
bool video_draining
Whether EOF was sent to the video decoder.
_Atomic uint64_t seek_generation
Detect seeks before and after packet reads.

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, atomic_store_bool(), ffmpeg_decoder_t::audio_buffer, ffmpeg_decoder_t::audio_buffer_offset, ffmpeg_decoder_t::audio_buffer_size, ffmpeg_decoder_t::audio_codec_ctx, ffmpeg_decoder_t::audio_sample_rate, ffmpeg_decoder_t::audio_samples_read, ffmpeg_decoder_t::eof_reached, ERROR_INVALID_PARAM, ERROR_MEDIA_SEEK, ERROR_NOT_SUPPORTED, ffmpeg_decoder_t::format_ctx, ffmpeg_decoder_t::is_stdin, ffmpeg_decoder_t::last_audio_pts, ffmpeg_decoder_t::last_video_pts, ffmpeg_decoder_t::prefetch_cond, ffmpeg_decoder_t::prefetch_frame_ready, ffmpeg_decoder_t::prefetch_mutex, ffmpeg_decoder_t::read_frame_mutex, ffmpeg_decoder_t::seek_generation, ffmpeg_decoder_t::seeking_in_progress, SET_ERRNO, ffmpeg_decoder_t::video_codec_ctx, and ffmpeg_decoder_t::video_draining.

Referenced by ffmpeg_decoder_rewind(), and media_source_seek().

◆ ffmpeg_decoder_set_exit_callback()

void ffmpeg_decoder_set_exit_callback ( ffmpeg_decoder_t * decoder,
bool(* should_exit_callback )(void *),
void * user_data )

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Set exit signal callback for graceful shutdown during I/O.

Parameters
decoderDecoder (must not be NULL)
callbackFunction that returns true if app should exit (can be NULL)
user_dataUser data to pass to callback (can be NULL)

Sets a callback that allows the decoder's background prefetch thread to gracefully abort blocking I/O operations (like YouTube HTTP requests) when the application is shutting down (e.g., when user presses Ctrl+C).

When the callback returns true, the FFmpeg interrupt handler will abort any blocking av_read_frame() call, allowing the prefetch thread to exit cleanly rather than hanging indefinitely.

Note
Called automatically from media_source layer (no need to call manually)

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

1670 {
1671 if (!decoder) {
1672 return;
1673 }
1674 atomic_ptr_store(&decoder->exit_callback_user_data, user_data);
1676 (void *)should_exit_callback);
1677}
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
atomic_ptr_t exit_callback_user_data
User data for exit callback.
atomic_ptr_t should_exit_callback
Callback to check if app should exit.

References atomic_ptr_store(), ffmpeg_decoder_t::exit_callback_user_data, and ffmpeg_decoder_t::should_exit_callback.

Referenced by media_source_set_exit_callback().

◆ ffmpeg_decoder_start_prefetch()

asciichat_error_t ffmpeg_decoder_start_prefetch ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Start background frame prefetching thread.

Parameters
decoderDecoder (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Starts a background thread that continuously reads and decodes video frames, storing them in an internal ringbuffer. The render loop then pulls pre-decoded frames from this buffer without blocking on network I/O.

Purpose: Solves YouTube HTTP streaming performance issues by decoupling the blocking av_read_frame() calls from the render loop. Without this, frames take 93ms to arrive instead of the expected 41.7ms at 24 FPS.

Note
Should be called after decoder creation for FILE/HTTP sources
Automatically called when media source is created
Thread is stopped in ffmpeg_decoder_destroy()

Start background frame prefetching thread.

Starts a background thread that continuously reads and decodes video frames, storing them in double-buffer structures. The render loop pulls frames from these buffers. This prevents the render thread from blocking on YouTube HTTP requests.

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

1614 {
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}
@ ERROR_THREAD

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_THREAD, ffmpeg_decoder_t::prefetch_failed, ffmpeg_decoder_t::prefetch_failure, ffmpeg_decoder_t::prefetch_image_a, ffmpeg_decoder_t::prefetch_image_b, ffmpeg_decoder_t::prefetch_should_stop, ffmpeg_decoder_t::prefetch_thread, ffmpeg_decoder_t::prefetch_thread_running, SET_ERRNO, and ffmpeg_decoder_t::video_stream_idx.

Referenced by http_renderer_render_file(), and media_source_create_interruptible().

◆ ffmpeg_decoder_stop_prefetch()

void ffmpeg_decoder_stop_prefetch ( ffmpeg_decoder_t * decoder)

#include <include/ascii-chat/media/ffmpeg_decoder.h>

Stop background frame prefetching thread.

Parameters
decoderDecoder (must not be NULL)

Stops the background prefetch thread. Automatically called by ffmpeg_decoder_destroy(). Safe to call even if thread isn't running.

Stop background frame prefetching thread.

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

1649 {
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}
#define NS_PER_MS_INT
Definition time.h:172

References ASCIICHAT_OK, log_warn, NS_PER_MS_INT, ffmpeg_decoder_t::prefetch_cond, ffmpeg_decoder_t::prefetch_mutex, ffmpeg_decoder_t::prefetch_should_stop, ffmpeg_decoder_t::prefetch_thread, and ffmpeg_decoder_t::prefetch_thread_running.

◆ media_source_at_end()

bool media_source_at_end ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Check if media source reached end of stream.

Parameters
sourceMedia source (must not be NULL)
Returns
true if end reached, false otherwise

Determines if the media source has reached end of stream. This distinguishes between read errors and legitimate EOF conditions.

Return values:

  • true: End of stream reached (no more data)
  • false: More data available or error occurred
Note
WEBCAM/TEST sources never reach end (always return false)
FILE/STDIN sources return true when all packets consumed
If loop is enabled, this returns false (EOF triggers rewind)

Definition at line 922 of file source.c.

922 {
923 if (!source) {
924 return true;
925 }
926
927 switch (source->type) {
930 return false; // Webcam never ends
931
934 if (!source->video_decoder) {
935 return true;
936 }
937 // If loop is enabled, we never truly reach end
938 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
939 return false;
940 }
941 if (source->audio_only)
942 return source->audio_decoder &&
943 ffmpeg_decoder_at_end(source->audio_decoder);
944 return ffmpeg_decoder_at_end(source->video_decoder);
945
946 default:
947 return true;
948 }
949}

References ffmpeg_decoder_at_end(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

Referenced by media_source_read_video(), and session_capture_at_end().

◆ media_source_create()

media_source_t * media_source_create ( media_source_type_t type,
const char * path )

#include <include/ascii-chat/media/source.h>

Create a new media source.

Parameters
typeMedia source type
pathFile path (for FILE type), device index string (for WEBCAM), or NULL
Returns
Pointer to media source, or NULL on failure

Creates and initializes a media source of the specified type.

Path parameter usage:

  • MEDIA_SOURCE_FILE: File path (e.g., "video.mp4")
  • MEDIA_SOURCE_STDIN: Use "-" or NULL
  • MEDIA_SOURCE_WEBCAM: Device index as string (e.g., "0") or NULL for default
  • MEDIA_SOURCE_TEST: Ignored (use NULL)
Note
For WEBCAM type, delegates to webcam_init_context()
For FILE/STDIN types, uses FFmpeg decoder
Call media_source_destroy() to cleanup

Definition at line 243 of file source.c.

244 {
245 return media_source_create_interruptible(type, path, NULL, NULL);
246}
media_source_t * media_source_create_interruptible(media_source_type_t type, const char *path, bool(*cancel)(void *), void *data)
Definition source.c:248

References media_source_create_interruptible().

◆ media_source_destroy()

void media_source_destroy ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Destroy media source and free resources.

Parameters
sourceMedia source to destroy (can be NULL)

Cleans up media source and releases all resources. Safe to call with NULL.

Note
For WEBCAM type, calls webcam_cleanup_context()
For FILE/STDIN types, closes FFmpeg decoder

Definition at line 561 of file source.c.

561 {
562 ASCII_OTEL_SCOPE(MEDIA_SOURCE_DESTROY);
563 if (!source) {
564 return;
565 }
566
567 // Cleanup based on type
568 if (source->webcam_ctx) {
569 webcam_cleanup_context(source->webcam_ctx);
570 source->webcam_ctx = NULL;
571 }
572
573 // For YouTube (shared decoder), only destroy once
574 // For local files (separate decoders), destroy both
575 if (source->video_decoder) {
576 ffmpeg_decoder_destroy(source->video_decoder);
577 source->video_decoder = NULL;
578 }
579
580 if (source->audio_decoder) {
581 // Don't double-free if audio and video share the same decoder
582 if (!source->is_shared_decoder) {
583 ffmpeg_decoder_destroy(source->audio_decoder);
584 }
585 source->audio_decoder = NULL;
586 }
587
588 SAFE_FREE(source->file_path);
589 SAFE_FREE(source->original_youtube_url);
590
591 // Clean up test pattern frame
592 test_pattern_destroy(source->test_pattern);
593 source->test_pattern = NULL;
594
595 NAMED_UNREGISTER(&source->is_paused);
596
597 // Destroy mutexes
598 mutex_destroy(&source->decoder_mutex);
599
601}
void webcam_cleanup_context(webcam_context_t *ctx)
Clean up webcam context and release resources.
void test_pattern_destroy(test_pattern_t *p)

References ASCII_OTEL_SCOPE, ffmpeg_decoder_destroy(), NAMED_UNREGISTER, SAFE_FREE, source, test_pattern_destroy(), and webcam_cleanup_context().

Referenced by session_capture_create(), and session_capture_destroy().

◆ media_source_get_duration()

double media_source_get_duration ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Get media duration in seconds.

Parameters
sourceMedia source (must not be NULL)
Returns
Duration in seconds, or -1.0 if unknown/infinite

Returns the total duration of the media. Useful for progress display.

Return values:

  • Positive value: Duration in seconds (e.g., 120.5 for 2 minutes)
  • -1.0: Duration unknown (stdin, live streams) or infinite (webcam)
Note
WEBCAM/TEST sources return -1.0 (infinite)
FILE sources return actual duration from container
STDIN sources return -1.0 (cannot determine duration)

Definition at line 1103 of file source.c.

1103 {
1104 if (!source) {
1105 return -1.0;
1106 }
1107
1108 switch (source->type) {
1110 case MEDIA_SOURCE_TEST:
1111 return -1.0; // Infinite
1112
1113 case MEDIA_SOURCE_FILE:
1114 case MEDIA_SOURCE_STDIN:
1115 if (!source->video_decoder) {
1116 return -1.0;
1117 }
1118 return ffmpeg_decoder_get_duration(source->video_decoder);
1119
1120 default:
1121 return -1.0;
1122 }
1123}
double ffmpeg_decoder_get_duration(ffmpeg_decoder_t *decoder)
Get media duration in seconds.

References ffmpeg_decoder_get_duration(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

◆ media_source_get_position()

double media_source_get_position ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Get current playback position in seconds.

Parameters
sourceMedia source (must not be NULL)
Returns
Current position in seconds, or -1.0 if unknown

Returns the current playback position. Useful for progress display.

Return values:

  • Positive value: Position in seconds (e.g., 45.2)
  • -1.0: Position unknown or not applicable
Note
WEBCAM/TEST sources return -1.0 (no position concept)
FILE sources return position based on last decoded frame PTS

Definition at line 1125 of file source.c.

1125 {
1126 if (!source) {
1127 return -1.0;
1128 }
1129
1130 switch (source->type) {
1132 case MEDIA_SOURCE_TEST:
1133 return -1.0; // No position concept
1134
1135 case MEDIA_SOURCE_FILE:
1136 case MEDIA_SOURCE_STDIN:
1137 if (!source->video_decoder) {
1138 return -1.0;
1139 }
1141 source->audio_only ? source->audio_decoder : source->video_decoder);
1142
1143 default:
1144 return -1.0;
1145 }
1146}
double ffmpeg_decoder_get_position(ffmpeg_decoder_t *decoder)
Get current playback position in seconds.

References ffmpeg_decoder_get_position(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

◆ media_source_get_type()

media_source_type_t media_source_get_type ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Get media source type.

Parameters
sourceMedia source (must not be NULL)
Returns
Media source type

Returns the type of the media source.

Definition at line 1099 of file source.c.

1099 {
1100 return source ? source->type : MEDIA_SOURCE_TEST;
1101}

References MEDIA_SOURCE_TEST, and source.

Referenced by session_capture_at_end(), session_capture_toggle_media(), and session_pipeline_create().

◆ media_source_get_video_fps()

double media_source_get_video_fps ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Get video frame rate in frames per second.

Parameters
sourceMedia source (must not be NULL)
Returns
Frame rate in FPS, or 0.0 if unknown

Returns the native frame rate of the video stream.

Return values:

  • Positive value: Frame rate in FPS (e.g., 30.0, 60.0)
  • 0.0: Frame rate unknown or not applicable
Note
WEBCAM sources return the negotiated capture rate when available
TEST sources return 0.0
FILE/STDIN sources return the video stream's fps from FFmpeg

Definition at line 1148 of file source.c.

1148 {
1149 if (!source) {
1150 return 0.0;
1151 }
1152
1153 switch (source->type) {
1155 return source->webcam_ctx ? webcam_get_fps(source->webcam_ctx) : 0.0;
1156 case MEDIA_SOURCE_TEST:
1157 return 0.0;
1158
1159 case MEDIA_SOURCE_FILE:
1160 case MEDIA_SOURCE_STDIN:
1161 if (!source->video_decoder) {
1162 return 0.0;
1163 }
1164 return ffmpeg_decoder_get_video_fps(source->video_decoder);
1165
1166 default:
1167 return 0.0;
1168 }
1169}
double ffmpeg_decoder_get_video_fps(ffmpeg_decoder_t *decoder)
Get video frame rate.
double webcam_get_fps(webcam_context_t *ctx)

References ffmpeg_decoder_get_video_fps(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, source, and webcam_get_fps().

Referenced by session_capture_create().

◆ media_source_has_audio()

bool media_source_has_audio ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Check if media source has audio stream.

Parameters
sourceMedia source (must not be NULL)
Returns
true if source has audio, false otherwise

Determines if the media source provides audio samples.

Note
WEBCAM and TEST sources return false (no audio)
FILE/STDIN sources return true if audio stream detected

Definition at line 885 of file source.c.

885 {
886 if (!source) {
887 return false;
888 }
889
890 switch (source->type) {
893 return false; // Webcam/test don't have audio
894
897 return source->audio_decoder &&
898 ffmpeg_decoder_has_audio(source->audio_decoder);
899
900 default:
901 return false;
902 }
903}
bool ffmpeg_decoder_has_audio(ffmpeg_decoder_t *decoder)
Check if decoder has audio stream.

References ffmpeg_decoder_has_audio(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

Referenced by audio_connection_init(), audio_start_duplex(), session_audio_start_duplex(), session_capture_create(), and session_participant_start_audio().

◆ media_source_has_video()

bool media_source_has_video ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Check if media source has video stream.

Parameters
sourceMedia source (must not be NULL)
Returns
true if source has video, false otherwise

Determines if the media source provides video frames.

Note
WEBCAM and TEST sources always return true
FILE/STDIN sources return true if video stream detected

Definition at line 769 of file source.c.

769 {
770 if (!source) {
771 return false;
772 }
773
774 switch (source->type) {
777 return true; // Webcam/test always has video
778
781 return source->audio_only ||
782 (source->video_decoder &&
783 ffmpeg_decoder_has_video(source->video_decoder));
784
785 default:
786 return false;
787 }
788}
bool ffmpeg_decoder_has_video(ffmpeg_decoder_t *decoder)
Check if decoder has video stream.

References ffmpeg_decoder_has_video(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

◆ media_source_is_paused()

bool media_source_is_paused ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Check if media source is paused.

Parameters
sourceMedia source (must not be NULL)
Returns
true if paused, false if playing

Determines if the media source is currently paused.

Definition at line 1190 of file source.c.

1190 {
1191 if (!source) {
1192 return false;
1193 }
1194 return atomic_load_bool(&source->is_paused);
1195}

References atomic_load_bool(), and source.

◆ media_source_pause()

void media_source_pause ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Pause media playback.

Parameters
sourceMedia source (must not be NULL)

Pauses the media source. When paused, read_video and read_audio return no new data (NULL/silence) while maintaining the current playback position. Resume with media_source_resume() to continue from the paused position.

Behavior:

Note
All source types support pause (has no effect for WEBCAM/TEST)
Pausing is instantaneous (next read will return no data)

Definition at line 1176 of file source.c.

1176 {
1177 if (!source) {
1178 return;
1179 }
1180 atomic_store_bool(&source->is_paused, true);
1181}

References atomic_store_bool(), and source.

◆ media_source_read_audio()

size_t media_source_read_audio ( media_source_t * source,
float * buffer,
size_t num_samples )

#include <include/ascii-chat/media/source.h>

Read audio samples from media source.

Parameters
sourceMedia source (must not be NULL)
bufferOutput buffer for audio samples (must not be NULL)
num_samplesNumber of samples to read
Returns
Number of samples actually read (may be less than requested)

Reads audio samples from the media source. Samples are in 32-bit float format, interleaved stereo, 48kHz sample rate (compatible with Opus encoding).

Audio format:

  • Format: 32-bit float
  • Channels: Stereo (2 channels); sample counts include both channels
  • Sample rate: 48000 Hz
  • Range: -1.0 to 1.0

Return value:

  • Returns actual number of samples read (0 to num_samples)
  • Returns 0 on error or end of stream
  • Check media_source_at_end() to distinguish error from EOF
Note
WEBCAM type does NOT provide audio (returns 0)
FILE/STDIN types decode audio via FFmpeg if stream exists
Audio is resampled to 48kHz stereo automatically

Definition at line 795 of file source.c.

796 {
797 ASCII_OTEL_SCOPE(MEDIA_SOURCE_READ_AUDIO);
798 if (!source || !buffer || num_samples == 0) {
799 return 0;
800 }
801
802 static uint64_t call_count = 0;
803 call_count++;
804 if (call_count <= 5 || call_count % 1000 == 0) {
805 log_debug("#%lu: source_type=%d num_samples=%zu", call_count, source->type,
806 num_samples);
807 }
808
809 // Check pause state (thread-safe)
810 bool is_paused = atomic_load_bool(&source->is_paused);
811
812 // Return silence immediately if paused (maintaining position)
813 if (is_paused) {
814 memset(buffer, 0, num_samples * sizeof(float));
815 return num_samples;
816 }
817
818 switch (source->type) {
821 // Webcam/test pattern don't provide audio
822 return 0;
823
825 case MEDIA_SOURCE_STDIN: {
826 if (!source->audio_decoder) {
827 log_warn_every(US_PER_SEC_INT, "audio_decoder is NULL!");
828 return 0;
829 }
830
831 // Lock shared decoder if YouTube URL (protect against concurrent video
832 // thread access)
833 if (source->is_shared_decoder) {
834 mutex_lock(&source->decoder_mutex);
835 }
836
837 double audio_pos_before_read =
838 ffmpeg_decoder_get_position(source->audio_decoder);
839 size_t samples_read = ffmpeg_decoder_read_audio_samples(
840 source->audio_decoder, buffer, num_samples);
841 double audio_pos_after_read =
842 ffmpeg_decoder_get_position(source->audio_decoder);
843
844 static double last_audio_pos = 0;
845 if (audio_pos_after_read >= 0 && last_audio_pos >= 0 &&
846 audio_pos_after_read < last_audio_pos) {
849 "Audio position moved backward: %.2f → %.2f (LOOPING!)",
850 last_audio_pos, audio_pos_after_read);
851 }
852 if (audio_pos_after_read >= 0) {
853 last_audio_pos = audio_pos_after_read;
854 }
855
857 "Audio: read %zu samples, pos %.2f → %.2f",
858 samples_read, audio_pos_before_read, audio_pos_after_read);
859
860 // Handle EOF with loop
861 if (samples_read == 0 && ffmpeg_decoder_at_end(source->audio_decoder)) {
862 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
863 log_debug("End of file reached (audio), rewinding for loop");
865 // Try reading again after rewind
867 source->audio_decoder, buffer, num_samples);
868 }
869 }
870 }
871
872 // Unlock shared decoder
873 if (source->is_shared_decoder) {
874 mutex_unlock(&source->decoder_mutex);
875 }
876
877 return samples_read;
878 }
879
880 default:
881 return 0;
882 }
883}
asciichat_error_t media_source_rewind(media_source_t *source)
Rewind media source to beginning.
Definition source.c:951
size_t ffmpeg_decoder_read_audio_samples(ffmpeg_decoder_t *decoder, float *buffer, size_t num_samples)
Decode audio samples.

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, atomic_load_bool(), ffmpeg_decoder_at_end(), ffmpeg_decoder_get_position(), ffmpeg_decoder_read_audio_samples(), log_debug, log_debug_every, log_warn_every, MEDIA_SOURCE_FILE, media_source_rewind(), MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, source, and US_PER_SEC_INT.

◆ media_source_read_video()

image_t * media_source_read_video ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Read next video frame from media source.

Parameters
sourceMedia source (must not be NULL)
Returns
Pointer to image_t frame, or NULL on error/end

Reads the next video frame from the media source. Returns an image_t structure in RGB format, compatible with existing ascii-chat pipeline.

Return values:

  • Non-NULL: Valid frame pointer (do NOT free - internal buffer)
  • NULL: Error or end of stream (check media_source_at_end())

Frame ownership:

  • Returned frame is owned by media source
  • Do NOT free the returned frame
  • Frame is valid until next call or source destruction
Note
For WEBCAM type, calls webcam_read_context()
For FILE/STDIN types, decodes next video frame via FFmpeg
Frame timing is handled by caller (capture thread)

Definition at line 653 of file source.c.

653 {
654 ASCII_OTEL_SCOPE(MEDIA_SOURCE_READ_VIDEO);
655 if (!source) {
656 return NULL;
657 }
658
659 // Check pause state (thread-safe)
660 bool is_paused = atomic_load_bool(&source->is_paused);
661
662 // Return NULL immediately if paused (maintaining position)
663 if (is_paused) {
664 return NULL;
665 }
666
667 if (source->audio_only && media_source_at_end(source))
668 return NULL;
669 // Audio visualizations replace the image at display time and need only a
670 // frame clock.
671 if ((source->audio_only && GET_OPTION(test_pattern)) ||
672 ((source->audio_only || source->type == MEDIA_SOURCE_WEBCAM) &&
673 (GET_OPTION(waveform) || GET_OPTION(fft))))
674 return read_test_pattern(source);
675 if ((source->audio_only || source->type == MEDIA_SOURCE_WEBCAM) &&
676 !source->webcam_ctx) {
678 return NULL;
679 }
680 if (source->webcam_ctx)
681 return webcam_read_context(source->webcam_ctx);
682
683 switch (source->type) {
685 // Read from webcam
686 if (source->webcam_ctx) {
687 return webcam_read_context(source->webcam_ctx);
688 }
689 return NULL;
690
691 case MEDIA_SOURCE_TEST: {
692 return read_test_pattern(source);
693 }
694
696 case MEDIA_SOURCE_STDIN: {
697 if (!source->video_decoder) {
698 return NULL;
699 }
700
701 // Lock shared decoder if YouTube URL (protect against concurrent audio
702 // thread access)
703 if (source->is_shared_decoder) {
704 mutex_lock(&source->decoder_mutex);
705 }
706
707 uint64_t frame_read_start_ns = time_get_ns();
708 image_t *frame = ffmpeg_decoder_read_video_frame(source->video_decoder);
709 uint64_t frame_read_ns =
710 time_elapsed_ns(frame_read_start_ns, time_get_ns());
711
712 // Track frame reading statistics for FPS diagnosis
713 static uint64_t total_attempts = 0;
714 static uint64_t successful_frames = 0;
715 static uint64_t null_frame_count = 0;
716 static uint64_t total_read_time_ns = 0;
717 static uint64_t max_read_time_ns = 0;
718
719 total_attempts++;
720 if (frame) {
721 successful_frames++;
722 total_read_time_ns += frame_read_ns;
723 if (frame_read_ns > max_read_time_ns) {
724 max_read_time_ns = frame_read_ns;
725 }
726
727 // Log statistics every 30 successful frames
728 if (successful_frames % 30 == 0) {
729 double avg_read_ms =
730 (double)total_read_time_ns / (double)successful_frames / NS_PER_MS;
731 double max_read_ms = (double)max_read_time_ns / NS_PER_MS;
732 double null_rate =
733 (double)null_frame_count * 100.0 / (double)total_attempts;
735 "FRAME_STATS[%lu]: avg_read=%.2f ms, max_read=%.2f ms, "
736 "null_rate=%.1f%% "
737 "(%lu null/%lu attempts)",
738 successful_frames, avg_read_ms, max_read_ms, null_rate,
739 null_frame_count, total_attempts);
740 }
741 } else {
742 null_frame_count++;
743 }
744
745 // Handle EOF with loop
746 if (!frame && ffmpeg_decoder_at_end(source->video_decoder)) {
747 if (source->loop_enabled && source->type == MEDIA_SOURCE_FILE) {
748 log_debug("End of file reached, rewinding for loop");
750 // Try reading again after rewind
751 frame = ffmpeg_decoder_read_video_frame(source->video_decoder);
752 }
753 }
754 }
755
756 // Unlock shared decoder
757 if (source->is_shared_decoder) {
758 mutex_unlock(&source->decoder_mutex);
759 }
760
761 return frame;
762 }
763
764 default:
765 return NULL;
766 }
767}
image_t * ffmpeg_decoder_read_video_frame(ffmpeg_decoder_t *decoder)
#define NS_PER_MS
Definition time.h:163
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
image_t * webcam_read_context(webcam_context_t *ctx)
Capture a frame from webcam context.
asciichat_error_t media_source_start_video(media_source_t *source)
Definition source.c:629
test pattern is intentionally a small, concrete record. Fields such as image, rgba give callers the i...

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, atomic_load_bool(), ffmpeg_decoder_at_end(), ffmpeg_decoder_read_video_frame(), GET_OPTION, log_debug, log_debug_every, media_source_at_end(), MEDIA_SOURCE_FILE, media_source_rewind(), media_source_start_video(), MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, NS_PER_MS, source, time_elapsed_ns(), US_PER_SEC_INT, and webcam_read_context().

◆ media_source_resume()

void media_source_resume ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Resume media playback after pause.

Parameters
sourceMedia source (must not be NULL)

Resumes playback from where it was paused. Continues reading frames and audio samples from the current position.

Note
Safe to call if not paused (no-op)
Resume is instantaneous (next read will return new data)

Definition at line 1183 of file source.c.

1183 {
1184 if (!source) {
1185 return;
1186 }
1187 atomic_store_bool(&source->is_paused, false);
1188}

References atomic_store_bool(), and source.

◆ media_source_rewind()

asciichat_error_t media_source_rewind ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Rewind media source to beginning.

Parameters
sourceMedia source (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Seeks to the beginning of the media source. Used for loop implementation.

Behavior:

  • FILE sources: Seek to timestamp 0 (if seekable)
  • STDIN sources: ERROR_NOT_SUPPORTED (cannot seek stdin)
  • WEBCAM/TEST sources: No-op (always returns OK)
Note
Called automatically by read functions if loop enabled
Can be called manually to restart playback

Definition at line 951 of file source.c.

951 {
952 ASCII_OTEL_SCOPE(MEDIA_SOURCE_REWIND);
953 if (!source) {
954 return ERROR_INVALID_PARAM;
955 }
956
957 switch (source->type) {
960 return ASCIICHAT_OK; // No-op for webcam
961
963 if (!source->video_decoder && !source->audio_decoder) {
964 return ERROR_INVALID_PARAM;
965 }
966
967 // Lock shared decoder if YouTube URL (protect against concurrent thread
968 // access)
969 if (source->is_shared_decoder) {
970 mutex_lock(&source->decoder_mutex);
971 }
972
973 // Rewind video decoder
974 asciichat_error_t video_result =
975 source->video_decoder ? ffmpeg_decoder_rewind(source->video_decoder)
976 : ASCIICHAT_OK;
977 if (video_result != ASCIICHAT_OK) {
978 if (source->is_shared_decoder) {
979 mutex_unlock(&source->decoder_mutex);
980 }
981 return video_result;
982 }
983
984 // For YouTube (shared decoder), don't rewind audio separately
985 // For local files (separate decoders), rewind audio too
987 if (!source->is_shared_decoder && source->audio_decoder) {
988 result = ffmpeg_decoder_rewind(source->audio_decoder);
989 }
990
991 // Unlock shared decoder
992 if (source->is_shared_decoder) {
993 mutex_unlock(&source->decoder_mutex);
994 }
995
996 return result;
997
999 return ERROR_NOT_SUPPORTED; // Cannot seek stdin
1000
1001 default:
1002 return ERROR_INVALID_PARAM;
1003 }
1004}
asciichat_error_t ffmpeg_decoder_rewind(ffmpeg_decoder_t *decoder)
Seek to beginning of media.

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, ffmpeg_decoder_rewind(), MEDIA_SOURCE_FILE, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, and source.

Referenced by media_source_read_audio(), and media_source_read_video().

◆ media_source_seek()

asciichat_error_t media_source_seek ( media_source_t * source,
double timestamp_sec )

#include <include/ascii-chat/media/source.h>

Seek media source to timestamp.

Parameters
sourceMedia source (must not be NULL)
timestamp_secTimestamp in seconds
Returns
ASCIICHAT_OK on success, error code on failure

Seeks both video and audio decoders to the specified timestamp. Handles shared decoder locking for YouTube URLs.

Behavior:

  • FILE sources: Seek to timestamp (if seekable)
  • STDIN sources: ERROR_NOT_SUPPORTED (cannot seek stdin)
  • WEBCAM/TEST sources: No-op (always returns OK)

Thread safety:

  • For YouTube URLs with shared decoder, automatically locks during seek
  • Safe to call from any thread
Note
FILE sources only (returns OK for others)
STDIN sources: ERROR_NOT_SUPPORTED (cannot seek stdin)
Negative timestamps are rejected
Seeks are approximate (may land before requested timestamp)

Definition at line 1006 of file source.c.

1007 {
1008 ASCII_OTEL_SCOPE(MEDIA_SOURCE_SEEK);
1009 if (!source) {
1010 SET_ERRNO(ERROR_INVALID_PARAM, "Media source is NULL");
1011 return ERROR_INVALID_PARAM;
1012 }
1013
1014 if (timestamp_sec < 0.0) {
1015 SET_ERRNO(ERROR_INVALID_PARAM, "Timestamp must be >= 0.0");
1016 return ERROR_INVALID_PARAM;
1017 }
1018
1019 // WEBCAM and TEST sources: no-op (always return OK)
1020 if (source->type == MEDIA_SOURCE_WEBCAM ||
1021 source->type == MEDIA_SOURCE_TEST) {
1022 return ASCIICHAT_OK;
1023 }
1024
1025 // STDIN: not supported
1026 if (source->type == MEDIA_SOURCE_STDIN) {
1027 SET_ERRNO(ERROR_NOT_SUPPORTED, "Cannot seek stdin");
1028 return ERROR_NOT_SUPPORTED;
1029 }
1030
1032
1033 // Clear audio playback buffer BEFORE seeking to prevent old audio from being
1034 // queued This ensures fresh audio starts playing immediately after seek
1035 // completes
1036 if (source->audio_ctx) {
1037 audio_context_t *audio_ctx = (audio_context_t *)source->audio_ctx;
1038 if (audio_ctx->playback_buffer) {
1039 audio_ring_buffer_clear(audio_ctx->playback_buffer);
1040 }
1041 }
1042
1043 // The seeking_in_progress flag in decoders blocks prefetch thread
1044 // seeking_in_progress coordinates with audio callback via condition variable
1045
1046 uint64_t seek_start_ns = time_get_ns();
1047 if (source->video_decoder) {
1048 double video_pos_before =
1049 ffmpeg_decoder_get_position(source->video_decoder);
1050 asciichat_error_t video_err =
1051 ffmpeg_decoder_seek_to_timestamp(source->video_decoder, timestamp_sec);
1052 double video_pos_after = ffmpeg_decoder_get_position(source->video_decoder);
1053 uint64_t video_seek_ns = time_elapsed_ns(seek_start_ns, time_get_ns());
1054 char video_seek_str[TIME_DURATION_BUFFER_SIZE];
1055 time_pretty(video_seek_ns, -1, video_seek_str, sizeof(video_seek_str));
1056 if (video_err != ASCIICHAT_OK) {
1057 log_warn("Video seek to %.2f failed %s (took %s)", timestamp_sec,
1058 asciichat_error_format(NULL, video_err), video_seek_str);
1059 result = video_err;
1060 } else {
1061 log_debug("Video SEEK: %.2f → %.2f sec (target %.2f, took %s)",
1062 video_pos_before, video_pos_after, timestamp_sec,
1063 video_seek_str);
1064 }
1065 }
1066
1067 // Seek audio decoder (if separate from video)
1068 if (source->audio_decoder && !source->is_shared_decoder) {
1069 log_debug("=== Starting audio seek to %.2f sec ===", timestamp_sec);
1070 uint64_t audio_seek_start_ns = time_get_ns();
1071 double audio_pos_before =
1072 ffmpeg_decoder_get_position(source->audio_decoder);
1073 log_debug("Audio position before seek: %.2f", audio_pos_before);
1074 asciichat_error_t audio_err =
1075 ffmpeg_decoder_seek_to_timestamp(source->audio_decoder, timestamp_sec);
1076 double audio_pos_after = ffmpeg_decoder_get_position(source->audio_decoder);
1077 uint64_t audio_seek_ns =
1078 time_elapsed_ns(audio_seek_start_ns, time_get_ns());
1079 log_debug("Audio position after seek: %.2f", audio_pos_after);
1080 char audio_seek_str[TIME_DURATION_BUFFER_SIZE];
1081 time_pretty(audio_seek_ns, -1, audio_seek_str, sizeof(audio_seek_str));
1082 if (audio_err != ASCIICHAT_OK) {
1083 log_warn("Audio seek to %.2f failed %s (took %s)", timestamp_sec,
1084 asciichat_error_format(NULL, audio_err), audio_seek_str);
1085 result = audio_err;
1086 } else {
1087 log_debug(
1088 "Audio SEEK COMPLETE: %.2f → %.2f sec (target %.2f, took %s)",
1089 audio_pos_before, audio_pos_after, timestamp_sec, audio_seek_str);
1090 }
1091 }
1092
1093 // Prefetch thread automatically resumes when seeking_in_progress is cleared
1094 // and signaled
1095
1096 return result;
1097}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
void audio_ring_buffer_clear(audio_ring_buffer_t *rb)
Clear all audio samples from ring buffer.
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
When code needs to work with audio device info, it keeps index, max_input_channels,...

References ASCII_OTEL_SCOPE, asciichat_error_format(), ASCIICHAT_OK, audio_ring_buffer_clear(), ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, ffmpeg_decoder_get_position(), ffmpeg_decoder_seek_to_timestamp(), log_debug, log_warn, MEDIA_SOURCE_STDIN, MEDIA_SOURCE_TEST, MEDIA_SOURCE_WEBCAM, audio_context_t::playback_buffer, SET_ERRNO, source, TIME_DURATION_BUFFER_SIZE, time_elapsed_ns(), and time_pretty().

Referenced by session_capture_create().

◆ media_source_set_audio_context()

void media_source_set_audio_context ( media_source_t * source,
void * audio_ctx )

#include <include/ascii-chat/media/source.h>

Set audio context for playback buffer management.

Parameters
sourceMedia source (must not be NULL)
audio_ctxAudio context pointer (opaque, may be NULL)

Associates an audio context with the media source. Used to clear playback buffers during seeking to prevent audio lag.

Definition at line 1206 of file source.c.

1206 {
1207 if (source) {
1208 source->audio_ctx = audio_ctx;
1209 }
1210}

References source.

◆ media_source_set_exit_callback()

void media_source_set_exit_callback ( media_source_t * source,
bool(* should_exit_callback )(void *),
void * user_data )

#include <include/ascii-chat/media/source.h>

Set exit signal callback for graceful shutdown during I/O.

Parameters
sourceMedia source (must not be NULL)
callbackFunction that returns true if app should exit (can be NULL)
user_dataUser data to pass to callback (can be NULL)

Sets a callback on the underlying decoders that allows graceful shutdown when the application is shutting down (e.g., Ctrl+C). This is particularly important for file/HTTP sources where av_read_frame() might block indefinitely.

Purpose: When the user presses Ctrl+C, the signal handler sets the app's exit flag. This callback is polled by FFmpeg's interrupt handler to abort blocking I/O operations, allowing the prefetch thread to exit cleanly instead of hanging indefinitely.

Note
Called automatically from session_capture_create (no need to call manually)

Definition at line 1212 of file source.c.

1214 {
1215 if (!source) {
1216 return;
1217 }
1218
1219 // Set exit callback on video decoder if present
1220 if (source->video_decoder) {
1222 should_exit_callback, user_data);
1223 }
1224
1225 // Set exit callback on audio decoder if present (only if different from video
1226 // decoder)
1227 if (source->audio_decoder && source->audio_decoder != source->video_decoder) {
1229 should_exit_callback, user_data);
1230 }
1231}
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.

References ffmpeg_decoder_set_exit_callback(), and source.

Referenced by session_capture_create().

◆ media_source_set_loop()

void media_source_set_loop ( media_source_t * source,
bool loop )

#include <include/ascii-chat/media/source.h>

Enable or disable looping.

Parameters
sourceMedia source (must not be NULL)
looptrue to enable looping, false to disable

Enables loop mode for media files. When looping is enabled, the media source will automatically seek to the beginning when EOF is reached.

Behavior:

  • FILE sources: Seek to beginning on EOF (if seekable)
  • STDIN sources: Looping NOT supported (cannot seek stdin)
  • WEBCAM/TEST sources: Ignored (infinite by nature)
Note
For stdin, loop flag is silently ignored
Looping works for both video and audio streams

Definition at line 910 of file source.c.

910 {
911 if (!source) {
912 return;
913 }
914
915 source->loop_enabled = loop;
916
917 if (loop && source->type == MEDIA_SOURCE_STDIN) {
918 log_warn("Loop mode not supported for stdin input (cannot seek)");
919 }
920}

References log_warn, MEDIA_SOURCE_STDIN, and source.

Referenced by session_capture_create().

◆ media_source_toggle_pause()

void media_source_toggle_pause ( media_source_t * source)

#include <include/ascii-chat/media/source.h>

Toggle pause state of media source.

Parameters
sourceMedia source (must not be NULL)

Toggles between paused and playing states. If paused, resumes playback. If playing, pauses playback.

Definition at line 1197 of file source.c.

1197 {
1198 if (!source) {
1199 return;
1200 }
1201 bool paused = atomic_load_bool(&source->is_paused);
1202 while (!atomic_cas_bool(&source->is_paused, &paused, !paused)) {
1203 }
1204}
bool atomic_cas_bool(atomic_t *a, bool *expected, bool new_value)
Atomically compare-and-swap a boolean.

References atomic_cas_bool(), atomic_load_bool(), and source.

◆ yt_dlp_extract_stream_urls()

asciichat_error_t yt_dlp_extract_stream_urls ( const char * url,
const char * yt_dlp_options,
char * output_url,
size_t output_size,
char * audio_url,
size_t audio_size )

#include <include/ascii-chat/media/yt_dlp.h>

For yt dlp request options, this is the live record that ties proxy_specified together. The owning code creates it, updates it while work is active, and releases its handles and pointed-to storage before freeing the record.

Extract stream URL using yt-dlp with optional parameters

Prefers a combined stream, falling back to separate video and audio streams. Results are cached for 30 seconds.

Parameters
urlInput URL (YouTube, Twitch, direct streams, etc.)
yt_dlp_optionsArbitrary yt-dlp options string e.g., "--cookies-from-browser=chrome --no-warnings" Quotes group arguments; no shell expansion is performed. Pass NULL or "" for no extra options.
output_urlOutput buffer for extracted stream URL
output_sizeSize of output buffer (recommend 8192+ bytes)
audio_urlOutput buffer for a separate audio URL, or an empty string when the first URL contains both streams
audio_sizeSize of the audio URL buffer
Returns
ASCIICHAT_OK on success, error code on failure
Note
On failure, logs error context via log_error()
Results are cached to avoid redundant yt-dlp calls

Definition at line 613 of file yt_dlp.c.

615 {
617 url, yt_dlp_options, output_url, output_size, audio_url, audio_size, NULL,
618 NULL);
619}
asciichat_error_t yt_dlp_extract_stream_urls_interruptible(const char *url, const char *yt_dlp_options, char *output_url, size_t output_size, char *audio_url, size_t audio_size, bool(*cancel)(void *), void *data)
Definition yt_dlp.c:602

References yt_dlp_extract_stream_urls_interruptible().

Referenced by yt_dlp_extract_stream_url().

◆ yt_dlp_is_available()

bool yt_dlp_is_available ( void )

#include <include/ascii-chat/media/yt_dlp.h>

Check if yt-dlp is installed and accessible.

Runs yt-dlp --version to verify yt-dlp is available in PATH.

Returns
true if yt-dlp –version succeeds, false otherwise
Note
Thread-safe: No static state

Definition at line 190 of file yt_dlp.c.

190 {
191 ASCII_OTEL_SCOPE(YTDLP_AVAILABLE);
192 ASCII_OTEL_ATTR_STRING("media.extractor", "yt-dlp");
193 const char *argv[] = {"yt-dlp", "--version", NULL};
194 int ret = 0;
195 LOG_IO("yt-dlp", {
196 ret = platform_execute_subprocess("yt-dlp", argv, NULL, 0, NULL, NULL);
197 });
198 return (ret == 0);
199}
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
int platform_execute_subprocess(const char *executable, const char **argv, char *output_buffer, size_t output_size, bool(*cancel)(void *), void *data)
Definition system.c:35

References ASCII_OTEL_ATTR_STRING, ASCII_OTEL_SCOPE, LOG_IO, and platform_execute_subprocess().