ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
ffmpeg_encoder.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define MEDIA_FFMPEG_ENCODER_MESSAGE_BUFFER_SIZE 2048
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define FFMPEG_STDOUT_AVIO_BUFFER_SIZE 32768
12
14#include <ascii-chat/log/io.h>
15#include <ascii-chat/log/log.h>
19#include <libplatform/compiler.h>
20#include <libplatform/filesystem.h>
21#include <libplatform/memory.h>
22#include <libplatform/system.h>
23#include <libplatform/terminal.h>
24#include <options/options.h>
25#include <string.h>
26
27#include <libavcodec/avcodec.h>
28#include <libavformat/avformat.h>
29#include <libavutil/cpu.h>
30#include <libavutil/opt.h>
31#include <libswresample/swresample.h>
32#include <libswscale/swscale.h>
33
41 // Video stream
42 AVCodecContext *codec_ctx;
43 AVStream *stream;
44 AVFrame *frame;
45 AVFrame *frame_encoded; // Frame in target pixel format for encoding
46 struct SwsContext *sws_ctx;
47
48 // Audio stream
49 AVStream *audio_stream;
50 AVCodecContext *audio_codec_ctx;
51 struct SwrContext *audio_swr_ctx;
52 AVFrame *audio_frame;
53 int64_t audio_pts;
54 int audio_frame_size; // Codec's required samples per frame
55 float *audio_partial_buf; // Accumulator for partial frames
57
58 // Shared
59 AVFormatContext *fmt_ctx;
60 AVPacket *pkt;
68 int64_t video_pts; // Cumulative PTS for proper frame timestamps
69 int fps; // Frames per second (for duration calculation)
70 int is_image; // Single-frame format (PNG, JPG)
71 enum AVPixelFormat target_pix_fmt; // RGB24 for images, YUV420P for video
72 int has_audio_stream; // Whether audio stream was created
73 int is_stdout_pipe; // Whether writing to stdout (non-seekable)
74 FILE *stdout_stream; // Retained before LOG_IO temporarily redirects stdio
75 uint64_t previous_captured_ns; // Previous frame's capture timestamp (for
76 // snapshot mode)
77 double snapshot_actual_duration; // Actual wall-clock duration in snapshot
78 // mode (seconds)
79 uint64_t snapshot_elapsed_ns; // Current elapsed time in snapshot mode for
80 // dynamic frame duration
81
82 // Frame timing from capture timestamps
83 uint64_t first_frame_captured_ns; // Wall-clock timestamp of first frame (0 =
84 // not set)
85
86 // Snapshot mode frame distribution
87 int estimated_frame_count; // Expected frame count for snapshot mode (fps *
88 // snapshot_delay)
89 int64_t estimated_frame_duration; // Duration each frame should have in stream
90 // time_base units
91};
92
93// Determine audio codec from file extension
94static void get_audio_codec_from_extension(const char *path,
95 const char **audio_codec,
96 enum AVSampleFormat *sample_fmt,
97 int *has_audio) {
98 const char *dot = strrchr(path, '.');
99 *has_audio = 0;
100 *audio_codec = NULL;
101 *sample_fmt = AV_SAMPLE_FMT_NONE;
102
103 if (!dot) {
104 // Use Opus for stdout (pipe/non-seekable output, part of WebM), otherwise
105 // default to AAC
106 if (path && strcmp(path, "-") == 0) {
107 *has_audio = 1;
108 *audio_codec = "libopus";
109 *sample_fmt = AV_SAMPLE_FMT_FLT;
110 } else {
111 *has_audio = 1;
112 *audio_codec = "aac";
113 *sample_fmt = AV_SAMPLE_FMT_FLTP;
114 }
115 return;
116 }
117
118 const char *ext = dot + 1;
119 // Video formats with audio support
120 // NOLINTNEXTLINE(bugprone-branch-clone) - Each format requires distinct codec
121 // configuration
122 if (strcmp(ext, "mp4") == 0 || strcmp(ext, "mov") == 0) {
123 *has_audio = 1;
124 *audio_codec = "aac";
125 *sample_fmt = AV_SAMPLE_FMT_FLTP;
126 } else if (strcmp(ext, "mkv") == 0 || strcmp(ext, "mka") == 0) {
127 *has_audio = 1;
128 *audio_codec = "aac"; // Matroska supports both AAC and Opus
129 *sample_fmt = AV_SAMPLE_FMT_FLTP;
130 } else if (strcmp(ext, "webm") == 0) {
131 *has_audio = 1;
132 *audio_codec = "libopus";
133 *sample_fmt = AV_SAMPLE_FMT_FLT;
134 } else if (strcmp(ext, "avi") == 0) {
135 *has_audio = 1;
136 *audio_codec = "pcm_s16le";
137 *sample_fmt = AV_SAMPLE_FMT_S16;
138 } else if (strcmp(ext, "flv") == 0) {
139 *has_audio = 1;
140 *audio_codec = "aac";
141 *sample_fmt = AV_SAMPLE_FMT_FLTP;
142 } else if (strcmp(ext, "ogv") == 0 || strcmp(ext, "ogg") == 0) {
143 *has_audio = 1;
144 *audio_codec = "libvorbis";
145 *sample_fmt = AV_SAMPLE_FMT_FLTP;
146 } else if (strcmp(ext, "3gp") == 0) {
147 *has_audio = 1;
148 *audio_codec = "aac";
149 *sample_fmt = AV_SAMPLE_FMT_FLTP;
150 } else if (strcmp(ext, "gif") == 0 || strcmp(ext, "png") == 0 ||
151 strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0 ||
152 strcmp(ext, "bmp") == 0 || strcmp(ext, "webp") == 0) {
153 *has_audio = 0;
154 *audio_codec = NULL;
155 *sample_fmt = AV_SAMPLE_FMT_NONE;
156 } else {
157 // Default for unknown formats
158 *has_audio = 1;
159 *audio_codec = "aac";
160 *sample_fmt = AV_SAMPLE_FMT_FLTP;
161 }
162}
163
164// Determine codec, format, and pixel format from file extension
165static void get_codec_from_extension(const char *path, const char **codec,
166 const char **format, int *is_image,
167 enum AVPixelFormat *pix_fmt) {
168 const char *dot = strrchr(path, '.');
169 *is_image = 0;
170 *pix_fmt = AV_PIX_FMT_YUV420P; // Default
171
172 if (!dot) {
173 // Default to MP4 for any output without extension (including stdout piping)
174 *codec = "libx264";
175 *format = "mp4";
176 return;
177 }
178
179 const char *ext = dot + 1;
180 // Video formats
181 // NOLINTNEXTLINE(bugprone-branch-clone) - Each format requires distinct codec
182 // setup
183 if (strcmp(ext, "mp4") == 0 || strcmp(ext, "mov") == 0) {
184 *codec = "libx264";
185 *format = strcmp(ext, "mov") == 0 ? "mov" : "mp4";
186 *pix_fmt = AV_PIX_FMT_YUV420P;
187 } // NOLINTNEXTLINE(bugprone-branch-clone)
188 else if (strcmp(ext, "mkv") == 0) {
189 *codec = "libx264";
190 *format = "matroska";
191 *pix_fmt = AV_PIX_FMT_YUV420P;
192 } // NOLINTNEXTLINE(bugprone-branch-clone)
193 else if (strcmp(ext, "mka") == 0) {
194 // MKA is audio-only Matroska
195 *codec = "libx264";
196 *format = "matroska";
197 *pix_fmt = AV_PIX_FMT_YUV420P;
198 } else if (strcmp(ext, "webm") == 0) {
199 *codec = "libvpx-vp9";
200 *format = "webm";
201 *pix_fmt = AV_PIX_FMT_YUV420P;
202 } else if (strcmp(ext, "avi") == 0) {
203 *codec = "mpeg4";
204 *format = "avi";
205 *pix_fmt = AV_PIX_FMT_YUV420P;
206 } else if (strcmp(ext, "flv") == 0) {
207 *codec = "libx264";
208 *format = "flv";
209 *pix_fmt = AV_PIX_FMT_YUV420P;
210 } else if (strcmp(ext, "ogv") == 0 || strcmp(ext, "ogg") == 0) {
211 *codec = "libtheora";
212 *format = "ogg";
213 *pix_fmt = AV_PIX_FMT_YUV420P;
214 } else if (strcmp(ext, "3gp") == 0) {
215 *codec = "libx264";
216 *format = "3gp";
217 *pix_fmt = AV_PIX_FMT_YUV420P;
218 } else if (strcmp(ext, "gif") == 0) {
219 *codec = "gif";
220 *format = "gif";
221 *pix_fmt = AV_PIX_FMT_RGB8;
222 } else if (strcmp(ext, "png") == 0) {
223 *codec = "png";
224 *format = "image2";
225 *is_image = 1;
226 *pix_fmt = AV_PIX_FMT_RGB24; // PNG uses RGB24
227 } else if (strcmp(ext, "bmp") == 0 || strcmp(ext, "webp") == 0) {
228 *codec = strcmp(ext, "bmp") == 0 ? "bmp" : "libwebp";
229 *format = "image2";
230 *is_image = 1;
231 *pix_fmt = strcmp(ext, "bmp") == 0 ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_YUV420P;
232 } else if (strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0) {
233 *codec = "mjpeg";
234 *format = "image2";
235 *is_image = 1;
236 *pix_fmt = AV_PIX_FMT_YUVJ420P; // MJPEG uses YUVJ420P
237 } else {
238 // Default for unknown formats
239 *codec = "libx264";
240 *format = "mp4";
241 *pix_fmt = AV_PIX_FMT_YUV420P;
242 }
243}
244
245// Initialize audio stream for encoder
246static asciichat_error_t encoder_init_audio_stream(ffmpeg_encoder_t *enc,
247 const char *output_path) {
248 const char *audio_codec_name = NULL;
249 enum AVSampleFormat target_sample_fmt = AV_SAMPLE_FMT_NONE;
250 int has_audio = 0;
251
252 get_audio_codec_from_extension(output_path, &audio_codec_name,
253 &target_sample_fmt, &has_audio);
254
255 if (!has_audio) {
256 log_debug("no audio for format");
257 enc->has_audio_stream = 0;
258 return ASCIICHAT_OK;
259 }
260
261 // Find audio encoder
262 const AVCodec *audio_codec = avcodec_find_encoder_by_name(audio_codec_name);
263 if (!audio_codec) {
264 log_warn("audio encoder '%s' not found, skipping audio", audio_codec_name);
265 enc->has_audio_stream = 0;
266 return ASCIICHAT_OK;
267 }
268
269 // Create audio stream
270 enc->audio_stream = avformat_new_stream(enc->fmt_ctx, audio_codec);
271 if (!enc->audio_stream) {
272 log_warn("avformat_new_stream for audio failed");
273 enc->has_audio_stream = 0;
274 return ASCIICHAT_OK;
275 }
276
277 // Allocate audio codec context
278 enc->audio_codec_ctx = avcodec_alloc_context3(audio_codec);
279 if (!enc->audio_codec_ctx) {
280 log_warn("avcodec_alloc_context3 for audio failed");
281 enc->has_audio_stream = 0;
282 return ASCIICHAT_OK;
283 }
284
285 // Configure audio codec context
286 enc->audio_codec_ctx->sample_rate = 48000; // 48kHz (from audio pipeline)
287 AVChannelLayout ch_layout = AV_CHANNEL_LAYOUT_STEREO;
288 av_channel_layout_copy(&enc->audio_codec_ctx->ch_layout, &ch_layout);
289 enc->audio_codec_ctx->sample_fmt = target_sample_fmt;
290 enc->audio_codec_ctx->time_base = (AVRational){1, 48000};
291 enc->audio_codec_ctx->bit_rate = 128000; // 128 kbps
292
293 // Open audio codec (capture FFmpeg logs)
294 int ret = 0;
295 LOG_IO("ffmpeg",
296 { ret = avcodec_open2(enc->audio_codec_ctx, audio_codec, NULL); });
297 if (ret < 0) {
298 log_warn("avcodec_open2 for audio failed");
299 avcodec_free_context(&enc->audio_codec_ctx);
300 enc->has_audio_stream = 0;
301 return ASCIICHAT_OK;
302 }
303
304 // Copy codec parameters to stream
305 ret = avcodec_parameters_from_context(enc->audio_stream->codecpar,
306 enc->audio_codec_ctx);
307 if (ret < 0) {
308 log_warn("avcodec_parameters_from_context for audio failed");
309 avcodec_free_context(&enc->audio_codec_ctx);
310 enc->has_audio_stream = 0;
311 return ASCIICHAT_OK;
312 }
313
314 // Create audio frame
315 enc->audio_frame = av_frame_alloc();
316 if (!enc->audio_frame) {
317 log_warn("av_frame_alloc for audio failed");
318 avcodec_free_context(&enc->audio_codec_ctx);
319 enc->has_audio_stream = 0;
320 return ASCIICHAT_OK;
321 }
322
323 enc->audio_frame->sample_rate = 48000;
324 AVChannelLayout frame_ch_layout = AV_CHANNEL_LAYOUT_STEREO;
325 av_channel_layout_copy(&enc->audio_frame->ch_layout, &frame_ch_layout);
326 enc->audio_frame->format = target_sample_fmt;
327
328 // Get frame size from codec (if specified)
329 enc->audio_frame_size = enc->audio_codec_ctx->frame_size;
330 if (enc->audio_frame_size == 0) {
331 // Default frame size for codecs that don't specify
332 enc->audio_frame_size = 1024;
333 }
334
335 // Allocate buffer for partial frames (accumulator)
336 enc->audio_partial_buf =
337 SAFE_MALLOC(enc->audio_frame_size * 2 * sizeof(float), float *);
338 enc->audio_partial_len = 0;
339
340 // Create resampler from input format (AV_SAMPLE_FMT_FLT interleaved stereo
341 // 48kHz) to target format
342 enc->audio_swr_ctx = swr_alloc();
343 if (!enc->audio_swr_ctx) {
344 log_warn("swr_alloc failed");
346 av_frame_free(&enc->audio_frame);
347 avcodec_free_context(&enc->audio_codec_ctx);
348 enc->has_audio_stream = 0;
349 return ASCIICHAT_OK;
350 }
351
352 // Set input format (interleaved stereo 48kHz float32)
353 AVChannelLayout in_ch_layout = AV_CHANNEL_LAYOUT_STEREO;
354 av_opt_set_chlayout(enc->audio_swr_ctx, "in_chlayout", &in_ch_layout, 0);
355 av_opt_set_int(enc->audio_swr_ctx, "in_sample_rate", 48000, 0);
356 av_opt_set_sample_fmt(enc->audio_swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_FLT,
357 0);
358
359 // Set output format
360 AVChannelLayout out_ch_layout = AV_CHANNEL_LAYOUT_STEREO;
361 av_opt_set_chlayout(enc->audio_swr_ctx, "out_chlayout", &out_ch_layout, 0);
362 av_opt_set_int(enc->audio_swr_ctx, "out_sample_rate", 48000, 0);
363 av_opt_set_sample_fmt(enc->audio_swr_ctx, "out_sample_fmt", target_sample_fmt,
364 0);
365
366 // Initialize the resampler
367 ret = swr_init(enc->audio_swr_ctx);
368 if (ret < 0) {
369 log_warn("swr_init failed");
370 swr_free(&enc->audio_swr_ctx);
372 av_frame_free(&enc->audio_frame);
373 avcodec_free_context(&enc->audio_codec_ctx);
374 enc->has_audio_stream = 0;
375 return ASCIICHAT_OK;
376 }
377
378 enc->audio_pts = 0;
379 enc->has_audio_stream = 1;
380 log_debug("audio stream initialized with codec=%s, frame_size=%d",
381 audio_codec_name, enc->audio_frame_size);
382
383 return ASCIICHAT_OK;
384}
385
386static void encoder_init_snapshot_timing(ffmpeg_encoder_t *enc, int fps) {
387 // For snapshot mode, calculate output FPS based on input FPS and snapshot
388 // duration If we capture for N seconds at input_fps, we'll get ~(N *
389 // input_fps) frames Output duration should be snapshot_delay seconds So
390 // output_fps = (input_fps * snapshot_delay) / snapshot_delay = input_fps
391 // EXCEPT: if the input was probed, fps parameter is the actual input fps
392 // Then output_fps should equal input_fps to make frame durations sum
393 // correctly
394 bool snapshot_mode = GET_OPTION(snapshot_mode);
395 double snapshot_delay = GET_OPTION(snapshot_delay);
396 log_debug("snapshot_mode=%d, snapshot_delay=%.1f, input_fps=%d",
397 snapshot_mode, snapshot_delay, fps);
398
399 if (snapshot_mode && snapshot_delay > 0) {
400 // For snapshot mode: if we capture at input_fps for snapshot_delay seconds,
401 // we get approximately (input_fps * snapshot_delay) frames
402 // To make output span exactly snapshot_delay seconds:
403 // output_fps = frame_count / snapshot_delay = (input_fps * snapshot_delay)
404 // / snapshot_delay = input_fps So we should use input_fps as output_fps!
405 // Example: 30fps input for 3s → ~90 frames → output at 30fps → 90/30 = 3
406 // seconds ✓
407
408 log_info("Snapshot mode snapshot_delay=%.1f, input_fps=%d", snapshot_delay,
409 fps);
410 log_info(" → Will estimate ~%.0f frames, output FPS=%d makes durations "
411 "sum to %.1f seconds",
412 fps * snapshot_delay, fps, snapshot_delay);
413 }
414
415 enc->fps = fps;
416
417 // Snapshot mode frame distribution setup
418 enc->estimated_frame_count = 0;
420 if (snapshot_mode && snapshot_delay > 0 && fps > 0) {
421 // Estimate how many frames we'll capture
422 enc->estimated_frame_count = (int)(fps * snapshot_delay + 0.5);
423 // Each frame should have uniform duration in stream time_base (1/90000 for
424 // MP4) frame_duration = total_duration / estimated_frame_count
425 // = snapshot_delay seconds * time_base.den /
426 // estimated_frame_count
427 // We'll set this to stream->time_base later after it's initialized
428 log_info("Snapshot mode ENABLED - estimated_frame_count=%d (fps=%d * "
429 "snapshot_delay=%.2f)",
430 enc->estimated_frame_count, fps, snapshot_delay);
431 } else {
432 log_info("Snapshot mode disabled or invalid - snapshot_mode=%d, "
433 "snapshot_delay=%.2f, fps=%d",
434 snapshot_mode, snapshot_delay, fps);
435 }
436}
437
438static const AVCodec *encoder_find_video_codec(const char *codec_name) {
439 // Find encoder (with fallback for FFmpeg builds without libx264)
440 const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
441 if (!codec && strcmp(codec_name, "libx264") == 0) {
442 // libx264 not available - try built-in H.264 encoders
443 static const char *h264_fallbacks[] = {"libopenh264", "h264_mf", NULL};
444 for (int i = 0; h264_fallbacks[i] && !codec; i++) {
445 codec = avcodec_find_encoder_by_name(h264_fallbacks[i]);
446 }
447 if (!codec) {
448 // Last resort: ask FFmpeg for any H.264 encoder
449 codec = avcodec_find_encoder(AV_CODEC_ID_H264);
450 }
451 if (codec) {
452 log_info(
453 "ffmpeg: using fallback H.264 encoder '%s' (libx264 not available)",
454 codec->name);
455 }
456 }
457 if (!codec && strcmp(codec_name, "libvpx-vp9") == 0) {
458 // Homebrew and distribution FFmpeg builds do not consistently expose the
459 // libvpx VP9 encoder under the preferred name. Both VP9 and VP8 remain
460 // valid WebM video codecs.
461 static const char *webm_fallbacks[] = {"libvpx", "vp9", "libvpx-vp8", "vp8",
462 NULL};
463 for (int i = 0; webm_fallbacks[i] && !codec; ++i)
464 codec = avcodec_find_encoder_by_name(webm_fallbacks[i]);
465 if (codec) {
466 log_info(
467 "ffmpeg: using fallback WebM encoder '%s' (libvpx-vp9 not available)",
468 codec->name);
469 }
470 }
471 return codec;
472}
473
474// On failure, setup helpers release the partially initialized encoder.
475static asciichat_error_t encoder_init_video_stream(ffmpeg_encoder_t *enc,
476 const char *codec_name) {
477 int ret;
478 int width_px = enc->width_px;
479 int height_px = enc->height_px;
480 int fps = enc->fps;
481 const AVCodec *codec = encoder_find_video_codec(codec_name);
482 if (!codec) {
483 avformat_free_context(enc->fmt_ctx);
484 SAFE_FREE(enc);
485 return SET_ERRNO(ERROR_INIT, "ffmpeg: encoder '%s' not found", codec_name);
486 }
487
488 // Create new stream
489 enc->stream = avformat_new_stream(enc->fmt_ctx, codec);
490 if (!enc->stream) {
491 avformat_free_context(enc->fmt_ctx);
492 SAFE_FREE(enc);
493 return SET_ERRNO(ERROR_INIT, "ffmpeg: avformat_new_stream failed");
494 }
495
496 // Allocate codec context
497 enc->codec_ctx = avcodec_alloc_context3(codec);
498 if (!enc->codec_ctx) {
499 avformat_free_context(enc->fmt_ctx);
500 SAFE_FREE(enc);
501 return SET_ERRNO(ERROR_INIT, "ffmpeg: avcodec_alloc_context3 failed");
502 }
503
504 // Set codec parameters
505 enc->codec_ctx->width = width_px;
506 enc->codec_ctx->height = height_px;
507 enc->codec_ctx->pix_fmt = enc->target_pix_fmt;
508 enc->codec_ctx->time_base = (AVRational){1, fps};
509 enc->codec_ctx->framerate = (AVRational){fps, 1};
510 enc->stream->time_base = enc->codec_ctx->time_base;
511 enc->stream->avg_frame_rate = enc->codec_ctx->framerate;
512 if (enc->fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
513 enc->codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
514
515 // Set bitrate for high quality (music-level quality)
516 // Use ~5-10 Mbps per megapixel for visually lossless quality
517 int bitrate =
518 (width_px * height_px * 10) / 1024; // higher quality estimate in kbps
519 if (bitrate < 4000)
520 bitrate = 4000; // Minimum 4000 kbps for quality
521 if (bitrate > 50000)
522 bitrate = 50000; // Cap at 50 Mbps max
523 enc->codec_ctx->bit_rate = bitrate * 1000;
524 log_debug("bitrate set to %d kbps for %dx%d", bitrate, width_px, height_px);
525
526 // Configure codec-specific options for quality
527 AVDictionary *codec_opts = NULL;
528 if (strcmp(codec->name, "libx264") == 0) {
529 av_dict_set(&codec_opts, "preset", "ultrafast", 0);
530 av_dict_set(&codec_opts, "crf", "28", 0);
531 log_debug("x264 preset=ultrafast crf=28");
532 } else if (strcmp(codec->name, "libx265") == 0) {
533 av_dict_set(&codec_opts, "preset", "ultrafast", 0);
534 av_dict_set(&codec_opts, "crf", "32", 0);
535 // x265 tag must be hvc1 for MP4 container compatibility (Apple/browser
536 // playback)
537 enc->stream->codecpar->codec_tag = MKTAG('h', 'v', 'c', '1');
538 log_debug("x265 preset=ultrafast crf=32");
539 }
540
541 // Open codec (capture encoder startup logs).
542 LOG_IO("ffmpeg",
543 { ret = avcodec_open2(enc->codec_ctx, codec, &codec_opts); });
544 av_dict_free(&codec_opts);
545 if (ret < 0) {
546 char error_message[AV_ERROR_MAX_STRING_SIZE];
547 av_strerror(ret, error_message, sizeof(error_message));
548 avcodec_free_context(&enc->codec_ctx);
549 avformat_free_context(enc->fmt_ctx);
550 SAFE_FREE(enc);
551 return SET_ERRNO(ERROR_INIT, "ffmpeg: avcodec_open2 failed for %s: %s (%d)",
552 codec->name, error_message, ret);
553 }
554
555 // Copy codec parameters to stream
556 ret = avcodec_parameters_from_context(enc->stream->codecpar, enc->codec_ctx);
557 if (ret < 0) {
558 avcodec_free_context(&enc->codec_ctx);
559 avformat_free_context(enc->fmt_ctx);
560 SAFE_FREE(enc);
561 return SET_ERRNO(ERROR_INIT,
562 "ffmpeg: avcodec_parameters_from_context failed");
563 }
564
565 return ASCIICHAT_OK;
566}
567
568static AVDictionary *encoder_create_muxer_options(const ffmpeg_encoder_t *enc,
569 const char *output_path) {
570 // Muxer options for proper MP4 container structure
571 AVDictionary *opts = NULL;
572
573 // Muxer flags configuration
574 // For stdout/non-seekable output, use fragmented MP4 (frag_keyframe)
575 // For regular files, use faststart (moov at front for streaming)
576 bool is_stdout = (output_path && strcmp(output_path, "-") == 0);
577 if (is_stdout) {
578 // Use fragmented MP4 for stdout - starts a new fragment at each video
579 // keyframe This allows streaming without requiring file seeking (FFmpeg
580 // docs recommended)
581 av_dict_set(&opts, "movflags", "+frag_keyframe", 0);
582 log_debug("Using fragmented MP4 (+frag_keyframe) for stdout output");
583 } else {
584 // Move moov atom to the front (faststart) - helps with streaming and player
585 // compatibility
586 av_dict_set(&opts, "movflags", "faststart", 0);
587 }
588
589 if (enc->is_image) {
590 // Use -update flag for single frame output
591 av_dict_set(&opts, "update", "1", 0);
592 }
593
594 return opts;
595}
596
597static asciichat_error_t encoder_init_video_frames(ffmpeg_encoder_t *enc) {
598 int ret;
599 int width_px = enc->width_px;
600 int height_px = enc->height_px;
601 // Allocate frames
602 enc->frame = av_frame_alloc();
603 enc->frame_encoded = av_frame_alloc();
604 enc->pkt = av_packet_alloc();
605 if (!enc->frame || !enc->frame_encoded || !enc->pkt) {
606 av_frame_free(&enc->frame);
607 av_frame_free(&enc->frame_encoded);
608 av_packet_free(&enc->pkt);
609 avcodec_free_context(&enc->codec_ctx);
610 avformat_free_context(enc->fmt_ctx);
611 SAFE_FREE(enc);
612 return SET_ERRNO(ERROR_INIT, "ffmpeg: frame allocation failed");
613 }
614
615 // Set frame properties for target pixel format
616 enc->frame_encoded->format = enc->target_pix_fmt;
617 enc->frame_encoded->width = width_px;
618 enc->frame_encoded->height = height_px;
619 ret = av_frame_get_buffer(enc->frame_encoded, 32);
620 if (ret < 0) {
621 av_frame_free(&enc->frame);
622 av_frame_free(&enc->frame_encoded);
623 av_packet_free(&enc->pkt);
624 avcodec_free_context(&enc->codec_ctx);
625 avformat_free_context(enc->fmt_ctx);
626 SAFE_FREE(enc);
627 return SET_ERRNO(ERROR_INIT, "ffmpeg: av_frame_get_buffer failed");
628 }
629
630 // Large recordings otherwise convert millions of pixels on one thread.
631 // swscale owns its workers; small outputs avoid the synchronization cost.
632 int conversion_threads = av_cpu_count();
633 if (conversion_threads > 4)
634 conversion_threads = 4;
635 LOG_IO("swscaler", {
636 if ((int64_t)width_px * height_px >= 1000000 && conversion_threads > 1) {
637 struct SwsContext *context = sws_alloc_context();
638 if (context) {
639 int configured =
640 av_opt_set_int(context, "srcw", enc->source_width, 0) |
641 av_opt_set_int(context, "srch", enc->source_height, 0) |
642 av_opt_set_int(context, "dstw", width_px, 0) |
643 av_opt_set_int(context, "dsth", height_px, 0) |
644 av_opt_set_int(context, "src_format", AV_PIX_FMT_RGBA, 0) |
645 av_opt_set_int(context, "dst_format", enc->target_pix_fmt, 0) |
646 av_opt_set_int(context, "sws_flags", SWS_BICUBIC, 0) |
647 av_opt_set_int(context, "threads", conversion_threads, 0);
648 if (configured >= 0 && sws_init_context(context, NULL, NULL) >= 0)
649 enc->sws_ctx = context;
650 else
651 sws_freeContext(context);
652 }
653 }
654 if (!enc->sws_ctx)
655 enc->sws_ctx = sws_getContext(
656 enc->source_width, enc->source_height, AV_PIX_FMT_RGBA, width_px,
657 height_px, enc->target_pix_fmt, SWS_BICUBIC, NULL, NULL, NULL);
658 });
659 if (!enc->sws_ctx) {
660 av_frame_free(&enc->frame);
661 av_frame_free(&enc->frame_encoded);
662 av_packet_free(&enc->pkt);
663 avcodec_free_context(&enc->codec_ctx);
664 avformat_free_context(enc->fmt_ctx);
665 SAFE_FREE(enc);
666 return SET_ERRNO(ERROR_INIT, "ffmpeg: sws_getContext failed");
667 }
668
669 return ASCIICHAT_OK;
670}
671
672#if LIBAVFORMAT_VERSION_MAJOR >= 61
673static int encoder_stdout_write(void *opaque, const uint8_t *data, int size) {
674#else
675static int encoder_stdout_write(void *opaque, uint8_t *data, int size) {
676#endif
677 if (size < 0)
678 return AVERROR(EINVAL);
679 return stdout_writer_write(opaque, data, (size_t)size) == ASCIICHAT_OK
680 ? size
681 : AVERROR(EIO);
682}
683
684static void encoder_log_callback(void *context, int level, const char *format,
685 va_list args) {
686 (void)context;
687 if (level > av_log_get_level())
688 return;
690 vsnprintf(message, sizeof(message), format, args);
691 if (level <= AV_LOG_ERROR)
692 log_error("ffmpeg: %s", message);
693 else if (level <= AV_LOG_WARNING)
694 log_warn("ffmpeg: %s", message);
695 else
696 log_debug("ffmpeg: %s", message);
697}
698
699static void encoder_close_io(ffmpeg_encoder_t *enc) {
700 if (!enc->fmt_ctx->pb)
701 return;
702 if (enc->is_stdout_pipe) {
703 av_freep(&enc->fmt_ctx->pb->buffer);
704 avio_context_free(&enc->fmt_ctx->pb);
705 if (enc->stdout_stream) {
706 fclose(enc->stdout_stream);
707 enc->stdout_stream = NULL;
708 }
709 } else {
710 avio_closep(&enc->fmt_ctx->pb);
711 }
712}
713
714static asciichat_error_t encoder_open_output(ffmpeg_encoder_t *enc,
715 const char *output_path,
716 AVDictionary *opts) {
717 int ret;
718 // Open output file or stdout
719 if (!(enc->fmt_ctx->oformat->flags & AVFMT_NOFILE)) {
720 const char *open_path = output_path;
721 if (enc->is_stdout_pipe) {
722 int fd = platform_dup(STDOUT_FILENO);
723 if (fd >= 0) {
724 enc->stdout_stream = platform_fdopen("render stdout", fd, "wb");
725 if (!enc->stdout_stream)
726 platform_close(fd);
727 }
728 uint8_t *buffer = av_malloc(FFMPEG_STDOUT_AVIO_BUFFER_SIZE);
729 if (buffer && enc->stdout_stream)
730 enc->fmt_ctx->pb = avio_alloc_context(
731 buffer, FFMPEG_STDOUT_AVIO_BUFFER_SIZE, 1, enc->stdout_stream, NULL,
732 encoder_stdout_write, NULL);
733 if (!enc->fmt_ctx->pb) {
734 av_free(buffer);
735 if (enc->stdout_stream) {
736 fclose(enc->stdout_stream);
737 enc->stdout_stream = NULL;
738 }
739 }
740 ret = enc->fmt_ctx->pb ? 0 : AVERROR(ENOMEM);
741 enc->fmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO;
742 } else {
743 ret = avio_open(&enc->fmt_ctx->pb, open_path, AVIO_FLAG_WRITE);
744 }
745 if (ret < 0) {
746 sws_freeContext(enc->sws_ctx);
747 av_frame_free(&enc->frame);
748 av_frame_free(&enc->frame_encoded);
749 av_packet_free(&enc->pkt);
750 avcodec_free_context(&enc->codec_ctx);
751 avformat_free_context(enc->fmt_ctx);
752 SAFE_FREE(enc);
753 return SET_ERRNO(ERROR_INIT, "ffmpeg: avio_open failed for '%s'",
754 open_path);
755 }
756 }
757
758 // Write header (capture FFmpeg format muxer logs)
759 LOG_IO("ffmpeg", { ret = avformat_write_header(enc->fmt_ctx, &opts); });
760 av_dict_free(&opts); // Free options after use
761 if (ret < 0) {
762 encoder_close_io(enc);
763 sws_freeContext(enc->sws_ctx);
764 av_frame_free(&enc->frame);
765 av_frame_free(&enc->frame_encoded);
766 av_packet_free(&enc->pkt);
767 avcodec_free_context(&enc->codec_ctx);
768 avformat_free_context(enc->fmt_ctx);
769 SAFE_FREE(enc);
770 return SET_ERRNO(ERROR_INIT, "ffmpeg: avformat_write_header failed");
771 }
772
773 return ASCIICHAT_OK;
774}
775
776static void encoder_set_snapshot_frame_duration(ffmpeg_encoder_t *enc) {
777 // Now that stream->time_base is set, calculate estimated frame duration for
778 // snapshot mode
779 bool snapshot_mode_after_header = GET_OPTION(snapshot_mode);
780 double snapshot_delay_after_header = GET_OPTION(snapshot_delay);
781 if (snapshot_mode_after_header && enc->estimated_frame_count > 0 &&
782 snapshot_delay_after_header > 0) {
783 // Each frame should span: snapshot_delay / estimated_frame_count seconds
784 // In stream time_base units: (snapshot_delay * time_base.den) /
785 // estimated_frame_count
787 (int64_t)((snapshot_delay_after_header *
788 (double)enc->stream->time_base.den) /
790 log_debug("Calculated estimated_frame_duration=%lld time_base units "
791 "for snapshot mode (snapshot_delay=%.2f, estimated_frames=%d, "
792 "time_base=%d/%d)",
793 (long long)enc->estimated_frame_duration,
794 snapshot_delay_after_header, enc->estimated_frame_count,
795 enc->stream->time_base.num, enc->stream->time_base.den);
796 }
797}
798
799asciichat_error_t ffmpeg_encoder_create(const char *output_path, int width_px,
800 int height_px, int fps,
802 return ffmpeg_encoder_create_scaled(output_path, width_px, height_px,
803 width_px, height_px, fps, out);
804}
805
807 int source_width,
808 int source_height, int width_px,
809 int height_px, int fps,
811 log_info("output=%s, %dx%d @ %dfps", output_path, width_px, height_px, fps);
812
813 if (!output_path || !out || source_width <= 0 || source_height <= 0 ||
814 width_px <= 0 || height_px <= 0)
815 return SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameters");
816 if (strcmp(output_path, "pipe:") == 0)
817 output_path = "-";
818 // Codec workers can log after LOG_IO restores the process descriptors.
819 // The session logger routes diagnostics to stderr when binary stdout is
820 // active.
821 if (strcmp(output_path, "-") == 0)
822 av_log_set_callback(encoder_log_callback);
823
824 // Use default FPS if not specified (0 from config means "use default")
825 if (fps <= 0) {
826 fps = 60;
827 log_debug("fps was 0, using default 60");
828 }
829
830 ffmpeg_encoder_t *enc = SAFE_CALLOC(1, sizeof(*enc), ffmpeg_encoder_t *);
831 enc->width_px = width_px;
832 enc->height_px = height_px;
833 enc->source_width = source_width;
834 enc->source_height = source_height;
835
836 encoder_init_snapshot_timing(enc, fps);
837
838 enc->is_stdout_pipe = (output_path && strcmp(output_path, "-") == 0) ? 1 : 0;
839
840 // For codec/format detection, use output_path unless it's "-" (stdout)
841 // For stdout, use "fake.mp4" to default to MP4 format
842 const char *detection_path = output_path;
843 if (output_path && strcmp(output_path, "-") == 0) {
844 detection_path =
845 "fake.mp4"; // Fake path for format detection when piping to stdout
846 log_debug("Using MP4 format for stdout piping");
847 }
848
849 const char *codec_name = NULL, *format_name = NULL;
850 get_codec_from_extension(detection_path, &codec_name, &format_name,
851 &enc->is_image, &enc->target_pix_fmt);
852
853 log_debug("%s (%s, %dx%d @ %dfps, %s)", output_path, codec_name, width_px,
854 height_px, fps, enc->is_image ? "image" : "video");
855
856 // Allocate output media context
857 int ret = avformat_alloc_output_context2(&enc->fmt_ctx, NULL, format_name,
858 output_path);
859 if (ret < 0) {
860 SAFE_FREE(enc);
861 return SET_ERRNO(ERROR_INIT,
862 "ffmpeg: avformat_alloc_output_context2 failed");
863 }
864
865 asciichat_error_t result = encoder_init_video_stream(enc, codec_name);
866 if (result != ASCIICHAT_OK)
867 return result;
868
869 AVDictionary *opts = encoder_create_muxer_options(enc, output_path);
870
871 result = encoder_init_video_frames(enc);
872 if (result != ASCIICHAT_OK)
873 return result;
874
875 // Initialize audio stream if supported
876 encoder_init_audio_stream(enc, output_path);
877
878 result = encoder_open_output(enc, output_path, opts);
879 if (result != ASCIICHAT_OK)
880 return result;
881
882 encoder_set_snapshot_frame_duration(enc);
883
884 enc->frame_count = 0;
885 enc->video_pts = 0;
886 enc->snapshot_actual_duration = 0.0;
887 enc->snapshot_elapsed_ns = 0;
888 enc->first_frame_captured_ns = 0; // Initialize first frame timestamp
889 *out = enc;
890
891 /* Register encoder with named registry */
892 NAMED_REGISTER_FFMPEG_ENCODER(enc, output_path, NULL);
893
894 log_info("SUCCESS: encoder initialized, frame_count=0, fps=%d, dims=%dx%d",
895 enc->fps, enc->width_px, enc->height_px);
896 return ASCIICHAT_OK;
897}
898
900 const uint8_t *rgb, int pitch,
901 uint64_t captured_ns) {
902 if (!enc || !rgb)
903 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL input");
904
905 // Initialize first frame capture time on first call
906 if (enc->first_frame_captured_ns == 0) {
907 enc->first_frame_captured_ns = captured_ns;
908 log_debug("first frame captured at %llu ns",
909 (unsigned long long)captured_ns);
910 }
911
912 log_debug_every(5 * US_PER_SEC_INT, "Encoding frame %d, %dx%d",
913 enc->frame_count, enc->width_px, enc->height_px);
914
915 // Set up RGBA frame for conversion
916 uint8_t *data[1] = {(uint8_t *)rgb};
917 int linesize[1] = {pitch};
918
919 // Encoders may retain references to earlier frames for motion or transparency
920 // detection.
921 if (av_frame_make_writable(enc->frame_encoded) < 0)
922 return SET_ERRNO(ERROR_MEMORY, "ffmpeg: cannot make video frame writable");
923
924 // Ensure frame format is set before each sws_scale call.
925 // Some FFmpeg versions reset the format field, so we set it explicitly.
926 enc->frame_encoded->format = enc->target_pix_fmt;
927
928 // Convert RGBA to target format
929 uint64_t conversion_started_ns = time_get_ns();
930 sws_scale(enc->sws_ctx, (const uint8_t *const *)data, linesize, 0,
931 enc->source_height, enc->frame_encoded->data,
932 enc->frame_encoded->linesize);
933 uint64_t converted_ns = time_get_ns();
934
935 // Set frame duration based on mode
936 int64_t frame_duration;
937 bool snapshot_mode = GET_OPTION(snapshot_mode);
938
939 if (enc->frame_count == 0) {
940 log_info("frame 0, snapshot_mode=%d", snapshot_mode);
941 }
942
943 // Use FPS-based frame duration (snapshot mode adjusts total duration in
944 // destroy())
945 frame_duration = enc->codec_ctx->time_base.den /
946 (enc->codec_ctx->time_base.num * enc->fps);
947
948 enc->frame_encoded->duration = frame_duration;
949
950 // Track this frame's capture timestamp for duration calculation of next frame
951 if (snapshot_mode) {
952 uint64_t frame_dur_ms =
953 (enc->previous_captured_ns > 0)
954 ? (captured_ns - enc->previous_captured_ns) / 1000000
955 : 0;
956 if (enc->frame_count <= 2) {
957 log_info("ffmpeg: frame %d SET duration=%lld units (%.3fms since last, "
958 "codec_base=1/%d)",
959 enc->frame_count, (long long)frame_duration,
960 (double)frame_dur_ms, enc->codec_ctx->time_base.den);
961 }
962 enc->previous_captured_ns = captured_ns;
963 }
964
965 // Calculate PTS from actual capture timestamp
966 // time_base is {1, fps}, so 1 PTS unit = 1/fps seconds
967 // Convert elapsed nanoseconds to PTS units: elapsed_ns * fps / 1_000_000_000
968 uint64_t elapsed_ns = captured_ns - enc->first_frame_captured_ns;
969 int64_t pts_from_timestamp =
970 (int64_t)((elapsed_ns * (uint64_t)enc->fps) / 1000000000ULL);
971
972 // Normal file rendering is constant-frame-rate. Wall-clock capture timestamps
973 // include scheduler jitter and can create gaps or duplicate PTS values, so
974 // use the encoded frame index for exact N / FPS duration. File snapshots with
975 // audio use this same timeline, excluding capture initialization delays.
976 // Live sources preserve wall-clock gaps between received frames.
977 if ((!snapshot_mode || enc->has_audio_stream) && !enc->live_timing) {
978 pts_from_timestamp = enc->frame_count;
979 }
980
981 // For snapshot sources without an estimated frame count, distribute frames
982 // linearly across the actual duration once the capture duration is known.
983 if (snapshot_mode && !enc->has_audio_stream && !enc->live_timing &&
984 enc->estimated_frame_count == 0) {
988 // Distribute frames linearly based on their capture timestamp relative to
989 // total duration pts = (frame_elapsed_ns / total_elapsed_ns) *
990 // actual_duration_sec * fps This ensures frame 0 is at 0s and last frame
991 // is at actual_duration_sec
992 double actual_duration_sec =
993 (double)g_snapshot_actual_duration_ms / 1000.0;
994 double total_elapsed_sec =
996
997 if (total_elapsed_sec > 0.001) {
998 double frame_fraction =
999 (double)elapsed_ns / (double)g_snapshot_last_capture_elapsed_ns;
1000 double target_pts_sec = frame_fraction * actual_duration_sec;
1001 int64_t pts_before = pts_from_timestamp;
1002 // Convert target seconds to time_base units: pts = target_sec *
1003 // time_base.den / time_base.num
1004 pts_from_timestamp =
1005 (int64_t)(target_pts_sec * (double)enc->codec_ctx->time_base.den /
1006 (double)enc->codec_ctx->time_base.num);
1007
1008 if (enc->frame_count < 3 || enc->frame_count % 10 == 0) {
1009 log_debug(
1010 "ffmpeg: snapshot frame %d: PTS distributed (before=%lld, "
1011 "after=%lld, sec=%lld->%lld, frac=%.3f)",
1012 enc->frame_count, (long long)pts_before,
1013 (long long)pts_from_timestamp,
1014 (long long)((double)pts_before * enc->codec_ctx->time_base.num /
1015 enc->codec_ctx->time_base.den),
1016 (long long)target_pts_sec, frame_fraction);
1017 }
1018 }
1019 }
1020 }
1021
1022 // Use timestamp-based (or scaled) PTS
1023 enc->frame_encoded->pts = pts_from_timestamp;
1024 enc->last_video_pts = pts_from_timestamp;
1025 enc->video_pts += frame_duration;
1026
1027 if (!snapshot_mode) {
1030 "PTS calculation - elapsed_ns=%llu, pts_from_timestamp=%lld, fps=%d",
1031 (unsigned long long)elapsed_ns, (long long)pts_from_timestamp,
1032 enc->fps);
1033 }
1034
1035 // Send frame to encoder
1036 int ret = avcodec_send_frame(enc->codec_ctx, enc->frame_encoded);
1037 uint64_t submitted_ns = time_get_ns();
1038 if (ret < 0) {
1039 return SET_ERRNO(ERROR_MEDIA_INIT, "Cannot encode recording frame: %d",
1040 ret);
1041 }
1042
1043 // Receive packets from encoder and write to file
1044 static int write_frame_pkt_count = 0;
1045
1046 while (ret >= 0) {
1047 ret = avcodec_receive_packet(enc->codec_ctx, enc->pkt);
1048 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1049 break;
1050 if (ret < 0) {
1052 "ffmpeg: avcodec_receive_packet failed: %d", ret);
1053 }
1054
1055 write_frame_pkt_count++;
1056
1057 // Set packet duration in codec time base (duration of one frame at target
1058 // FPS) This ensures proper stream duration calculation
1059 if (enc->pkt->duration == 0) {
1060 enc->pkt->duration = enc->codec_ctx->time_base.den /
1061 (enc->codec_ctx->time_base.num * enc->fps);
1062 }
1063
1064 av_packet_rescale_ts(enc->pkt, enc->codec_ctx->time_base,
1065 enc->stream->time_base);
1066 enc->pkt->stream_index = enc->stream->index;
1067
1068 // In snapshot mode, apply adjusted duration if snapshot_actual_duration is
1069 // set This happens when we get the actual duration from the capture thread
1070 bool is_snapshot_mode = GET_OPTION(snapshot_mode);
1071 if (is_snapshot_mode && !enc->has_audio_stream &&
1072 enc->snapshot_actual_duration > 0 && enc->frame_count > 0) {
1073 int64_t adjusted_dur = (int64_t)((enc->snapshot_actual_duration *
1074 enc->stream->time_base.den) /
1075 enc->frame_count);
1076 // Only apply if it's significantly different from the default
1077 if (adjusted_dur > enc->pkt->duration * 2) {
1078 enc->pkt->duration = adjusted_dur;
1079 log_debug("ffmpeg: write_frame packet %d duration adjusted to %lld "
1080 "units based on actual duration",
1081 write_frame_pkt_count, (long long)enc->pkt->duration);
1082 }
1083 } else if (!is_snapshot_mode && write_frame_pkt_count < 3) {
1084 log_debug("ffmpeg: write_frame pkt %d, duration=%lld, snapshot_mode=%d, "
1085 "actual_dur=%.2f, frame_count=%d",
1086 write_frame_pkt_count, (long long)enc->pkt->duration,
1087 is_snapshot_mode, enc->snapshot_actual_duration,
1088 enc->frame_count);
1089 }
1090
1091 if (write_frame_pkt_count <= 2 || write_frame_pkt_count >= 16) {
1093 "ffmpeg: write_frame pkt %d with final duration=%lld "
1094 "(%.6f sec in stream time_base), total frames=%d",
1095 write_frame_pkt_count, (long long)enc->pkt->duration,
1096 (double)enc->pkt->duration / enc->stream->time_base.den,
1097 enc->frame_count);
1098 }
1099
1100 ret = av_interleaved_write_frame(enc->fmt_ctx, enc->pkt);
1101 av_packet_unref(enc->pkt);
1102 if (ret < 0) {
1104 "ffmpeg: av_interleaved_write_frame failed: %d", ret);
1105 }
1106
1107 // Flush output buffer for stdout to ensure frames are written immediately
1108 if (enc->is_stdout_pipe) {
1109 avio_flush(enc->fmt_ctx->pb);
1110 }
1111 }
1112
1113 uint64_t muxed_ns = time_get_ns();
1116 "ENCODER_STAGE: convert_ms=%.2f submit_ms=%.2f packets_ms=%.2f",
1117 (double)(converted_ns - conversion_started_ns) / NS_PER_MS_INT,
1118 (double)(submitted_ns - converted_ns) / NS_PER_MS_INT,
1119 (double)(muxed_ns - submitted_ns) / NS_PER_MS_INT);
1120 enc->frame_count++;
1121 return ASCIICHAT_OK;
1122}
1123
1124static asciichat_error_t encoder_prepare_audio_frame(ffmpeg_encoder_t *enc) {
1125 enc->audio_frame->nb_samples = enc->audio_frame_size;
1126 if (!enc->audio_frame->buf[0] && av_frame_get_buffer(enc->audio_frame, 0) < 0)
1127 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate recording audio frame");
1128 if (av_frame_make_writable(enc->audio_frame) < 0)
1129 return SET_ERRNO(ERROR_MEMORY,
1130 "Cannot make recording audio frame writable");
1131 const uint8_t *input[] = {(const uint8_t *)enc->audio_partial_buf};
1132 int converted =
1133 swr_convert(enc->audio_swr_ctx, enc->audio_frame->data,
1134 enc->audio_frame_size, input, enc->audio_frame_size);
1135 if (converted < 0)
1137 "Cannot convert recording audio samples: %d", converted);
1138 enc->audio_frame->nb_samples = converted;
1139 enc->audio_frame->pts = enc->audio_pts;
1140 return ASCIICHAT_OK;
1141}
1142
1144 const float *samples,
1145 int num_samples) {
1146 if (!enc || !samples || num_samples <= 0)
1147 return ASCIICHAT_OK; // Silently ignore invalid calls
1148
1149 // No audio stream for this format
1150 if (!enc->has_audio_stream)
1151 return ASCIICHAT_OK;
1152
1153 // Accumulate samples into partial buffer
1154 int samples_to_process = num_samples;
1155 int samples_offset = 0;
1156
1157 while (samples_to_process > 0) {
1158 // How many samples can we add to the partial buffer?
1159 int space_in_buffer = enc->audio_frame_size * 2 - enc->audio_partial_len;
1160 int samples_to_copy = (samples_to_process < space_in_buffer)
1161 ? samples_to_process
1162 : space_in_buffer;
1163
1164 // Copy samples to partial buffer
1165 memcpy(&enc->audio_partial_buf[enc->audio_partial_len],
1166 &samples[samples_offset], samples_to_copy * sizeof(float));
1167 enc->audio_partial_len += samples_to_copy;
1168 samples_offset += samples_to_copy;
1169 samples_to_process -= samples_to_copy;
1170
1171 // If buffer is full, encode and write frame
1172 if (enc->audio_partial_len >= enc->audio_frame_size * 2) {
1173 // Set up audio frame with accumulated samples
1174 asciichat_error_t prepare_result = encoder_prepare_audio_frame(enc);
1175 if (prepare_result != ASCIICHAT_OK)
1176 return prepare_result;
1177
1178 // Send frame to encoder
1179 int ret = avcodec_send_frame(enc->audio_codec_ctx, enc->audio_frame);
1180 if (ret < 0) {
1181 return SET_ERRNO(ERROR_MEDIA_INIT, "Cannot encode recording audio: %d",
1182 ret);
1183 } else {
1184 // Receive and write packets
1185 while (ret >= 0) {
1186 ret = avcodec_receive_packet(enc->audio_codec_ctx, enc->pkt);
1187 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1188 break;
1189 if (ret < 0) {
1190 return SET_ERRNO(
1192 "ffmpeg: avcodec_receive_packet for audio failed: %d", ret);
1193 }
1194
1195 // Rescale timestamp and write
1196 av_packet_rescale_ts(enc->pkt, enc->audio_codec_ctx->time_base,
1197 enc->audio_stream->time_base);
1198 enc->pkt->stream_index = enc->audio_stream->index;
1199 ret = av_interleaved_write_frame(enc->fmt_ctx, enc->pkt);
1200 av_packet_unref(enc->pkt);
1201 if (ret < 0) {
1202 return SET_ERRNO(
1204 "ffmpeg: av_interleaved_write_frame for audio failed: %d", ret);
1205 }
1206 }
1207 }
1208
1209 // Update PTS for next frame
1210 enc->audio_pts += enc->audio_frame_size;
1211 enc->audio_partial_len = 0;
1212 }
1213 }
1214
1215 return ASCIICHAT_OK;
1216}
1217
1219 double actual_duration_sec) {
1220 if (!enc)
1221 return;
1222 enc->snapshot_actual_duration = actual_duration_sec;
1223
1224 // If we already have frame count, we can calculate the adjusted packet
1225 // duration now This will be used for any remaining frames and during flush
1226 if (enc->frame_count > 0 && actual_duration_sec > 0) {
1227 // Calculate the packet duration that would make all frames fit in
1228 // actual_duration_sec packet_duration_units = (actual_duration_sec *
1229 // time_base.den) / frame_count This is only a starting point - the actual
1230 // duration might be different if more frames are captured
1231 log_debug("%.3f sec with %d frames so far", actual_duration_sec,
1232 enc->frame_count);
1233 } else {
1234 log_info("Setting duration to %.3f seconds (already encoded %d frames)",
1235 actual_duration_sec, enc->frame_count);
1236 }
1237}
1238
1239// Drain output before retrying input rejected by the encoder's backpressure.
1240// A NULL frame enters draining mode only after the encoder accepts it.
1241static asciichat_error_t finish_audio_frame(ffmpeg_encoder_t *enc,
1242 const AVFrame *frame) {
1244 LOG_IO("ffmpeg", {
1245 int send_ret;
1246 do {
1247 send_ret = avcodec_send_frame(enc->audio_codec_ctx, frame);
1248 if (send_ret < 0 && send_ret != AVERROR(EAGAIN) &&
1249 send_ret != AVERROR_EOF) {
1250 result = SET_ERRNO(ERROR_MEDIA_INIT, "Cannot finalize audio frame: %d",
1251 send_ret);
1252 break;
1253 }
1254
1255 bool received_packet = false;
1256 while (1) {
1257 int ret = avcodec_receive_packet(enc->audio_codec_ctx, enc->pkt);
1258 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1259 break;
1260 if (ret < 0) {
1261 result = SET_ERRNO(ERROR_MEDIA_INIT,
1262 "Cannot receive final audio packet: %d", ret);
1263 goto capture_done;
1264 }
1265
1266 received_packet = true;
1267 av_packet_rescale_ts(enc->pkt, enc->audio_codec_ctx->time_base,
1268 enc->audio_stream->time_base);
1269 enc->pkt->stream_index = enc->audio_stream->index;
1270 int write_ret = av_interleaved_write_frame(enc->fmt_ctx, enc->pkt);
1271 if (write_ret < 0)
1273 "Cannot write final audio packet: %d", write_ret);
1274 av_packet_unref(enc->pkt);
1275 }
1276
1277 // FFmpeg guarantees that a rejected send allows receiving output.
1278 if (send_ret == AVERROR(EAGAIN) && !received_packet) {
1279 result =
1281 "Audio encoder made no progress during finalization");
1282 break;
1283 }
1284 } while (send_ret == AVERROR(EAGAIN));
1285 capture_done:;
1286 });
1287 return result;
1288}
1289
1290static void encoder_log_snapshot_duration(const ffmpeg_encoder_t *enc) {
1291 // In snapshot mode, calculate the FPS needed to match the target duration
1292 bool snapshot_mode = GET_OPTION(snapshot_mode);
1293 int64_t adjusted_packet_duration = 0;
1294 double snapshot_delay = GET_OPTION(snapshot_delay);
1295
1296 if (snapshot_mode && !enc->has_audio_stream && !enc->live_timing &&
1297 enc->frame_count > 0 && snapshot_delay > 0) {
1298 // Calculate output FPS that distributes frames across snapshot_delay
1299 // seconds output_fps = frame_count / snapshot_delay packet_duration (in
1300 // stream time_base) = stream_time_base.den / output_fps
1301 // = (stream_time_base.den *
1302 // snapshot_delay) / frame_count
1303 adjusted_packet_duration =
1304 (int64_t)((snapshot_delay * enc->stream->time_base.den) /
1305 enc->frame_count);
1306 log_info("Snapshot mode - adjusting packet durations for %d frames over "
1307 "%.2f seconds",
1308 enc->frame_count, snapshot_delay);
1309 log_debug(" Adjusted packet duration: %lld units (%.6f seconds per frame)",
1310 (long long)adjusted_packet_duration,
1311 (double)adjusted_packet_duration / enc->stream->time_base.den);
1312 }
1313}
1314
1315static asciichat_error_t encoder_flush_video(ffmpeg_encoder_t *enc) {
1317 // Flush delayed video packets. Encoders such as VP9 may buffer every short
1318 // snapshot frame until this point.
1319 LOG_IO("ffmpeg", {
1320 int flush_ret = avcodec_send_frame(enc->codec_ctx, NULL);
1321 if (flush_ret < 0 && flush_ret != AVERROR_EOF)
1322 result = SET_ERRNO(ERROR_MEDIA_INIT, "Cannot flush video encoder: %d",
1323 flush_ret);
1324 while (1) {
1325 int ret = avcodec_receive_packet(enc->codec_ctx, enc->pkt);
1326 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1327 break;
1328 if (ret < 0) {
1329 result = SET_ERRNO(ERROR_MEDIA_INIT,
1330 "Cannot receive final video packet: %d", ret);
1331 break;
1332 }
1333
1334 // Set packet duration in codec time base if not already set
1335 if (enc->pkt->duration == 0) {
1336 enc->pkt->duration = enc->codec_ctx->time_base.den /
1337 (enc->codec_ctx->time_base.num * enc->fps);
1338 }
1339
1340 av_packet_rescale_ts(enc->pkt, enc->codec_ctx->time_base,
1341 enc->stream->time_base);
1342 enc->pkt->stream_index = enc->stream->index;
1343 int write_ret = av_interleaved_write_frame(enc->fmt_ctx, enc->pkt);
1344 if (write_ret < 0)
1346 "Cannot write final video packet: %d", write_ret);
1347 av_packet_unref(enc->pkt);
1348 }
1349 });
1350
1351 return result;
1352}
1353
1354static asciichat_error_t encoder_flush_audio(ffmpeg_encoder_t *enc) {
1356 // Flush audio encoder if present
1357 if (enc->has_audio_stream && enc->audio_codec_ctx) {
1358 // Write any remaining partial audio samples as padding
1359 if (enc->audio_partial_len > 0) {
1360 // Zero-pad the remaining samples
1361 memset(&enc->audio_partial_buf[enc->audio_partial_len], 0,
1362 (enc->audio_frame_size * 2 - enc->audio_partial_len) *
1363 sizeof(float));
1364 asciichat_error_t pad_result = encoder_prepare_audio_frame(enc);
1365 if (pad_result == ASCIICHAT_OK)
1366 pad_result = finish_audio_frame(enc, enc->audio_frame);
1367 if (pad_result != ASCIICHAT_OK)
1368 result = pad_result;
1369 }
1370
1371 // Flush any remaining packets (capture FFmpeg audio codec logs)
1372 asciichat_error_t flush_result = finish_audio_frame(enc, NULL);
1373 if (flush_result != ASCIICHAT_OK)
1374 result = flush_result;
1375 }
1376
1377 return result;
1378}
1379
1380static void encoder_set_stream_duration(ffmpeg_encoder_t *enc) {
1381 // Set stream duration for proper metadata (must be before trailer)
1382 if (enc->stream && enc->frame_count > 0) {
1383 int64_t duration;
1384 bool snapshot_mode = GET_OPTION(snapshot_mode);
1385 if (snapshot_mode && !enc->has_audio_stream && !enc->live_timing) {
1387 double snapshot_delay = GET_OPTION(snapshot_delay);
1388 // Use actual capture elapsed time if available, otherwise use
1389 // snapshot_delay This ensures frames are distributed across the correct
1390 // time window
1391 double actual_capture_duration = g_snapshot_actual_duration_ms / 1000.0;
1392 double effective_duration = (actual_capture_duration > 0)
1393 ? actual_capture_duration
1394 : snapshot_delay;
1395
1396 // In snapshot mode with wall-clock timing, the video duration should
1397 // equal the actual elapsed time duration_seconds = effective_duration
1398 // duration_time_base_units = effective_duration * time_base.den
1399 duration = (int64_t)(effective_duration * enc->stream->time_base.den);
1400
1401 // Calculate what the frame durations should be to sum to
1402 // effective_duration This ensures FFmpeg plays the captured frames across
1403 // the full effective_duration effective_frame_duration =
1404 // effective_duration / frame_count (seconds per frame)
1405 int64_t effective_frame_duration =
1406 (int64_t)((effective_duration / (double)enc->frame_count) *
1407 enc->stream->time_base.den);
1408
1409 log_info("Snapshot mode - snapshot_delay=%.2f, frames=%d, "
1410 "output_duration=%.2f sec",
1411 snapshot_delay, enc->frame_count, effective_duration);
1412 log_debug(" Using effective_duration=%.2f seconds for output",
1413 effective_duration);
1414 log_debug(" stream->time_base=%d/%d, effective frame duration=%lld "
1415 "time_base units",
1416 enc->stream->time_base.num, enc->stream->time_base.den,
1417 (long long)effective_frame_duration);
1418 log_debug(" (each frame should span %.3f seconds to total %.2f seconds)",
1419 effective_duration / (double)enc->frame_count,
1420 effective_duration);
1421
1422 log_info("Setting stream->duration=%lld (effective_duration=%.3f, "
1423 "time_base=%d/%d, "
1424 "equiv=%.3f sec)",
1425 (long long)duration, effective_duration,
1426 enc->stream->time_base.num, enc->stream->time_base.den,
1427 (double)duration * enc->stream->time_base.num /
1428 enc->stream->time_base.den);
1429 } else {
1430 // Normal mode: calculate duration from frame count and FPS
1431 // time_base = 1 / time_base.den seconds per unit
1432 // Each frame is 1/fps seconds, so duration = frame_count / fps seconds
1433 // In time base units: duration = (frame_count / fps) * time_base.den =
1434 // frame_count * time_base.den / fps
1435 duration = (enc->live_timing ? enc->last_video_pts + 1
1436 : (int64_t)enc->frame_count) *
1437 enc->stream->time_base.den / enc->fps;
1438 log_debug("Normal mode - Set stream duration=%lld (frames=%d, fps=%d, "
1439 "time_base=%d/%d)",
1440 (long long)duration, enc->frame_count, enc->fps, 1,
1441 enc->stream->time_base.den);
1442 }
1443 enc->stream->duration = duration;
1444
1445 // Each frame was encoded with FPS-based duration, but snapshot mode needs
1446 // them distributed across the actual capture duration. Since we can't
1447 // change past frame durations, we extend the last frame's duration to make
1448 // the sum equal the desired total.
1449 if (snapshot_mode) {
1450 // Calculate sum of all frame durations (each frame currently has the same
1451 // FPS-based duration)
1452 int64_t current_total_duration =
1453 enc->video_pts; // This is the sum of all frame durations so far
1454 int64_t desired_duration = duration;
1455
1456 // The last frame needs to be extended to: desired - (sum of all other
1457 // frames) This ensures the video plays for exactly the snapshot_delay
1458 // duration
1459 int64_t last_frame_extension = desired_duration - current_total_duration;
1460
1461 if (last_frame_extension > 0) {
1462 // We need to extend the last frame. But we can't modify it directly
1463 // after encoding. Instead, the muxer will use stream->duration as the
1464 // authoritative source.
1465 log_debug(
1466 "Last frame would need extension of %lld units to reach total %lld "
1467 "(currently %lld)",
1468 (long long)last_frame_extension, (long long)desired_duration,
1469 (long long)current_total_duration);
1470 }
1471 }
1472 }
1473}
1474
1475static asciichat_error_t encoder_finalize_output(ffmpeg_encoder_t *enc) {
1477 // Write trailer (capture FFmpeg muxer logs and final frame statistics)
1478 LOG_IO("ffmpeg", {
1479 int trailer_ret = av_write_trailer(enc->fmt_ctx);
1480 if (trailer_ret < 0)
1481 result = SET_ERRNO(ERROR_FILE_OPERATION, "Cannot finalize recording: %d",
1482 trailer_ret);
1483 });
1484
1485 // Flush output buffer for stdout/pipes before closing
1486 if (enc->fmt_ctx && enc->fmt_ctx->pb) {
1487 avio_flush(enc->fmt_ctx->pb);
1488 if (enc->fmt_ctx->pb->error < 0)
1489 result = SET_ERRNO(ERROR_FILE_OPERATION, "Recording output failed: %d",
1490 enc->fmt_ctx->pb->error);
1491 log_debug("Flushed output buffer");
1492 }
1493
1494 // Close output file
1495 if (enc->fmt_ctx && !(enc->fmt_ctx->oformat->flags & AVFMT_NOFILE)) {
1496 if (enc->is_stdout_pipe) {
1497 encoder_close_io(enc);
1498 } else {
1499 int close_ret = avio_closep(&enc->fmt_ctx->pb);
1500 if (close_ret < 0)
1501 result = SET_ERRNO(ERROR_FILE_OPERATION, "Cannot close recording: %d",
1502 close_ret);
1503 }
1504 }
1505
1506 return result;
1507}
1508
1509static void encoder_free(ffmpeg_encoder_t *enc) {
1510 // Cleanup
1511 sws_freeContext(enc->sws_ctx);
1512 av_frame_free(&enc->frame);
1513 av_frame_free(&enc->frame_encoded);
1514
1515 // Cleanup audio resources (capture any remaining FFmpeg logs from codec
1516 // cleanup)
1517 if (enc->has_audio_stream) {
1518 swr_free(&enc->audio_swr_ctx);
1519 av_frame_free(&enc->audio_frame);
1520 LOG_IO("ffmpeg", { avcodec_free_context(&enc->audio_codec_ctx); });
1522 }
1523
1524 av_packet_free(&enc->pkt);
1525 LOG_IO("ffmpeg", { avcodec_free_context(&enc->codec_ctx); });
1526 if (enc->fmt_ctx)
1527 avformat_free_context(enc->fmt_ctx);
1528
1529 log_debug("wrote %d frames", enc->frame_count);
1530 SAFE_FREE(enc);
1531}
1532
1534 if (!enc)
1535 return ASCIICHAT_OK;
1536
1538 NAMED_UNREGISTER(enc);
1539
1540 encoder_log_snapshot_duration(enc);
1541
1542 result = encoder_flush_video(enc);
1543
1544 asciichat_error_t audio_result = encoder_flush_audio(enc);
1545 if (audio_result != ASCIICHAT_OK)
1546 result = audio_result;
1547
1548 encoder_set_stream_duration(enc);
1549
1550 asciichat_error_t output_result = encoder_finalize_output(enc);
1551 if (output_result != ASCIICHAT_OK)
1552 result = output_result;
1553
1554 encoder_free(enc);
1555 return result;
1556}
1557
1559 if (enc)
1560 enc->live_timing = true;
1561}
#define SET_ERRNO(code,...)
Named object registry for debugging — log identifiable resource names.
void ffmpeg_encoder_set_snapshot_actual_duration(ffmpeg_encoder_t *enc, double actual_duration_sec)
asciichat_error_t ffmpeg_encoder_create_scaled(const char *output_path, int source_width, int source_height, int width_px, int height_px, int fps, ffmpeg_encoder_t **out)
void ffmpeg_encoder_set_live_timing(ffmpeg_encoder_t *enc)
asciichat_error_t ffmpeg_encoder_write_frame(ffmpeg_encoder_t *enc, const uint8_t *rgb, int pitch, uint64_t captured_ns)
asciichat_error_t ffmpeg_encoder_destroy(ffmpeg_encoder_t *enc)
#define MEDIA_FFMPEG_ENCODER_MESSAGE_BUFFER_SIZE
asciichat_error_t ffmpeg_encoder_write_audio(ffmpeg_encoder_t *enc, const float *samples, int num_samples)
asciichat_error_t ffmpeg_encoder_create(const char *output_path, int width_px, int height_px, int fps, ffmpeg_encoder_t **out)
#define FFMPEG_STDOUT_AVIO_BUFFER_SIZE
FFmpeg video/image file encoder — codec selected from file extension.
struct ffmpeg_encoder_s ffmpeg_encoder_t
int platform_close(int fd)
Definition filesystem.c:91
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_FFMPEG_ENCODER(encoder, name, parent_ptr)
Register an FFmpeg encoder with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
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_INIT
Definition error_codes.h:60
@ ERROR_MEDIA_INIT
Definition error_codes.h:70
@ ERROR_FILE_OPERATION
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1339
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:106
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
action_args_t args
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
static bool size_t gotel_query_t * out
Definition queries.h:10
uint64_t g_snapshot_last_capture_elapsed_ns
uint64_t g_snapshot_actual_duration_ms
asciichat_error_t stdout_writer_write(FILE *stream, const void *data, size_t size)
🔤 String Manipulation and Shell Escaping Utilities
This is the handoff point for ffmpeg encoder. Callers fill codec_ctx, stream, frame,...
struct SwsContext * sws_ctx
AVFrame * frame_encoded
uint64_t first_frame_captured_ns
AVFrame * audio_frame
enum AVPixelFormat target_pix_fmt
float * audio_partial_buf
AVStream * audio_stream
AVCodecContext * audio_codec_ctx
struct SwrContext * audio_swr_ctx
uint64_t snapshot_elapsed_ns
AVFormatContext * fmt_ctx
double snapshot_actual_duration
AVCodecContext * codec_ctx
int64_t estimated_frame_duration
uint64_t previous_captured_ns
⏱️ High-precision timing utilities using sokol_time.h and uthash