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

FFmpeg video/image file encoder for render-file output. More...

Go to the source code of this file.

Data Structures

struct  ffmpeg_encoder_s
 This is the handoff point for ffmpeg encoder. Callers fill codec_ctx, stream, frame, frame_encoded before passing it on; consumers read the values during the operation and return ownership only where the member contract explicitly says they do. More...

Macros

#define MEDIA_FFMPEG_ENCODER_MESSAGE_BUFFER_SIZE   2048
#define FFMPEG_STDOUT_AVIO_BUFFER_SIZE   32768

Functions

asciichat_error_t ffmpeg_encoder_create (const char *output_path, int width_px, int height_px, int fps, ffmpeg_encoder_t **out)
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)
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_write_audio (ffmpeg_encoder_t *enc, const float *samples, int num_samples)
void ffmpeg_encoder_set_snapshot_actual_duration (ffmpeg_encoder_t *enc, double actual_duration_sec)
asciichat_error_t ffmpeg_encoder_destroy (ffmpeg_encoder_t *enc)
void ffmpeg_encoder_set_live_timing (ffmpeg_encoder_t *enc)

Detailed Description

FFmpeg video/image file encoder for render-file output.

Definition in file ffmpeg_encoder.c.

Macro Definition Documentation

◆ FFMPEG_STDOUT_AVIO_BUFFER_SIZE

#define FFMPEG_STDOUT_AVIO_BUFFER_SIZE   32768

Definition at line 11 of file ffmpeg_encoder.c.

◆ MEDIA_FFMPEG_ENCODER_MESSAGE_BUFFER_SIZE

#define MEDIA_FFMPEG_ENCODER_MESSAGE_BUFFER_SIZE   2048

Definition at line 8 of file ffmpeg_encoder.c.

Function Documentation

◆ ffmpeg_encoder_create()

asciichat_error_t ffmpeg_encoder_create ( const char * output_path,
int width_px,
int height_px,
int fps,
ffmpeg_encoder_t ** out )

Create and initialize a video/image encoder.

The output format and codec are automatically determined from the file extension. See Supported Formats & Codecs for supported formats.

Bitrate: Automatically calculated from resolution (~1 Mbps per megapixel, clamped to 500-5000 kbps).

Color Space: Input is expected in RGBA format. Internal conversion to the appropriate output pixel format (YUV420P for video, RGB24 for PNG, YUVJ420P for JPEG) is handled automatically.

Parameters
output_pathPath to the output file (extension determines format and codec)
width_pxVideo width in pixels (must be > 0)
height_pxVideo height in pixels (must be > 0)
fpsFrames per second (must be > 0)
[out]outPointer to encoder handle (set on success)
Returns
ASCIICHAT_OK on success, error code otherwise
Note
The encoder acquires resources (file handles, memory buffers) that must be released with ffmpeg_encoder_destroy(). Failure to do so may leak file handles and memory.
See also
ffmpeg_encoder_write_frame, ffmpeg_encoder_destroy, ffmpeg_encoder_formats

Definition at line 799 of file ffmpeg_encoder.c.

801 {
802 return ffmpeg_encoder_create_scaled(output_path, width_px, height_px,
803 width_px, height_px, fps, out);
804}
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)
static bool size_t gotel_query_t * out
Definition queries.h:10

References ffmpeg_encoder_create_scaled(), and out.

◆ ffmpeg_encoder_create_scaled()

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 )

Create an encoder that scales RGBA input to the requested video dimensions.

Definition at line 806 of file ffmpeg_encoder.c.

810 {
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}
#define SET_ERRNO(code,...)
struct ffmpeg_encoder_s ffmpeg_encoder_t
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_FFMPEG_ENCODER(encoder, name, parent_ptr)
Register an FFmpeg encoder with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_INVALID_PARAM
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
uint64_t first_frame_captured_ns
enum AVPixelFormat target_pix_fmt
uint64_t snapshot_elapsed_ns
AVFormatContext * fmt_ctx
double snapshot_actual_duration

References ASCIICHAT_OK, ERROR_INIT, ERROR_INVALID_PARAM, ffmpeg_encoder_s::first_frame_captured_ns, ffmpeg_encoder_s::fmt_ctx, ffmpeg_encoder_s::fps, ffmpeg_encoder_s::frame_count, ffmpeg_encoder_s::height_px, ffmpeg_encoder_s::is_image, ffmpeg_encoder_s::is_stdout_pipe, log_debug, log_info, NAMED_REGISTER_FFMPEG_ENCODER, out, SAFE_CALLOC, SAFE_FREE, SET_ERRNO, ffmpeg_encoder_s::snapshot_actual_duration, ffmpeg_encoder_s::snapshot_elapsed_ns, ffmpeg_encoder_s::source_height, ffmpeg_encoder_s::source_width, ffmpeg_encoder_s::target_pix_fmt, ffmpeg_encoder_s::video_pts, and ffmpeg_encoder_s::width_px.

Referenced by ffmpeg_encoder_create(), and render_file_create().

◆ ffmpeg_encoder_destroy()

asciichat_error_t ffmpeg_encoder_destroy ( ffmpeg_encoder_t * enc)

Close and finalize the output file, releasing all encoder resources.

This function flushes any pending frames in the encoder, writes the file trailer, and releases all allocated resources (memory buffers, file handles, codecs).

Critical: This MUST be called to properly finalize the output file. Without this call, the file may be incomplete or unplayable.

Parameters
encEncoder handle (created with ffmpeg_encoder_create())
Returns
ASCIICHAT_OK on success (currently always succeeds)
Note
Safe to call with NULL pointer (returns ASCIICHAT_OK).
After this call, enc must not be used again.
The output file is NOT guaranteed to be complete until this function returns.
See also
ffmpeg_encoder_create

Definition at line 1533 of file ffmpeg_encoder.c.

1533 {
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}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.

References ASCIICHAT_OK, and NAMED_UNREGISTER.

Referenced by render_file_create(), and render_file_destroy().

◆ ffmpeg_encoder_set_live_timing()

void ffmpeg_encoder_set_live_timing ( ffmpeg_encoder_t * enc)

Definition at line 1558 of file ffmpeg_encoder.c.

1558 {
1559 if (enc)
1560 enc->live_timing = true;
1561}

References ffmpeg_encoder_s::live_timing.

Referenced by render_file_set_live_timing().

◆ ffmpeg_encoder_set_snapshot_actual_duration()

void ffmpeg_encoder_set_snapshot_actual_duration ( ffmpeg_encoder_t * enc,
double actual_duration_sec )

Set the actual wall-clock duration for snapshot mode frame timing.

In snapshot mode, frames are captured over a wall-clock duration (e.g., 3 seconds of real time). This function should be called after all frames are captured to provide the actual elapsed time, allowing the encoder to calculate correct frame durations so the output video duration matches the actual capture time.

Parameters
encEncoder handle (created with ffmpeg_encoder_create())
actual_duration_secActual wall-clock duration in seconds (e.g., 3.5 for 3.5 seconds)
Note
Only used in snapshot mode. In normal mode, this is ignored.
Should be called before ffmpeg_encoder_destroy() for the adjustment to take effect.
If not called, frame durations are calculated from FPS, which may not match actual wall-clock capture time.
See also
ffmpeg_encoder_create, ffmpeg_encoder_destroy

Definition at line 1218 of file ffmpeg_encoder.c.

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

References ffmpeg_encoder_s::frame_count, log_debug, log_info, and ffmpeg_encoder_s::snapshot_actual_duration.

Referenced by render_file_set_snapshot_actual_duration().

◆ ffmpeg_encoder_write_audio()

asciichat_error_t ffmpeg_encoder_write_audio ( ffmpeg_encoder_t * enc,
const float * samples,
int num_samples )

Write audio samples to the output file.

Encodes and writes audio samples to the output file. Audio samples must be in 48kHz mono float32 format. The function internally buffers and accumulates samples into codec frames before encoding.

Audio Format Requirements:

  • Sample rate: 48000 Hz (48 kHz)
  • Channels: Mono (1 channel)
  • Format: 32-bit IEEE float (AV_SAMPLE_FMT_FLT)

Notes:

  • Audio is only written if the output format supports audio (MP4, WebM, AVI).
  • Image formats (PNG, JPEG, GIF) ignore audio writes.
  • Samples are buffered internally and encoded in chunks as needed.
  • Timing is automatically synchronized with video using PTS (presentation timestamp).
Parameters
encEncoder handle (created with ffmpeg_encoder_create())
samplesPointer to audio samples in float32 format (not owned, used immediately)
num_samplesNumber of samples to write (must be > 0)
Returns
ASCIICHAT_OK on success, error code otherwise
Note
Input sample data is NOT owned by the encoder. The caller must ensure the buffer remains valid throughout the call.
Safe to call on encoders without audio streams (no-op).
See also
ffmpeg_encoder_create, ffmpeg_encoder_write_frame

Definition at line 1143 of file ffmpeg_encoder.c.

1145 {
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}
@ ERROR_MEDIA_INIT
Definition error_codes.h:70
@ ERROR_FILE_OPERATION
AVFrame * audio_frame
float * audio_partial_buf
AVStream * audio_stream
AVCodecContext * audio_codec_ctx

References ASCIICHAT_OK, ffmpeg_encoder_s::audio_codec_ctx, ffmpeg_encoder_s::audio_frame, ffmpeg_encoder_s::audio_frame_size, ffmpeg_encoder_s::audio_partial_buf, ffmpeg_encoder_s::audio_partial_len, ffmpeg_encoder_s::audio_pts, ffmpeg_encoder_s::audio_stream, ERROR_FILE_OPERATION, ERROR_MEDIA_INIT, ffmpeg_encoder_s::fmt_ctx, ffmpeg_encoder_s::has_audio_stream, ffmpeg_encoder_s::pkt, and SET_ERRNO.

Referenced by render_file_destroy().

◆ ffmpeg_encoder_write_frame()

asciichat_error_t ffmpeg_encoder_write_frame ( ffmpeg_encoder_t * enc,
const uint8_t * rgb,
int pitch,
uint64_t captured_ns )

Write a single video frame to the output file.

The frame must be in RGBA format (8-bit per channel, 32-bit per pixel). Internal color space conversion is performed automatically based on the output format (see Encoder Options & Quality Tradeoffs for details).

Pitch Parameter: The pitch parameter specifies the byte offset from one row to the next. For tightly-packed RGBA data: pitch = width_px × 4. For padded/aligned buffers: pitch must reflect the actual row size.

Timestamp Parameter: The captured_ns parameter is the wall-clock timestamp (in nanoseconds) when the frame was captured. This ensures video playback uses actual capture timing, not encoder processing time. For correct frame timing in the output video, captured_ns should be the time when the frame was acquired from the media source.

Parameters
encEncoder handle (created with ffmpeg_encoder_create())
rgbPointer to frame data in RGBA format (not copied, used immediately)
pitchByte offset between rows (must match actual buffer layout)
captured_nsWall-clock timestamp in nanoseconds when frame was captured
Returns
ASCIICHAT_OK on success, error code otherwise
Note
Input frame data is NOT owned by the encoder. The caller must ensure the buffer remains valid throughout the call.
For image-only formats (PNG, JPEG), only the last frame written is kept. Previous frames are discarded when the next frame is written.
See also
ffmpeg_encoder_create, ffmpeg_encoder_destroy

Definition at line 899 of file ffmpeg_encoder.c.

901 {
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}
unsigned long long uint64_t
unsigned char uint8_t
@ ERROR_MEMORY
Definition error_codes.h:55
#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
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
uint64_t g_snapshot_last_capture_elapsed_ns
uint64_t g_snapshot_actual_duration_ms
struct SwsContext * sws_ctx
AVFrame * frame_encoded
AVCodecContext * codec_ctx
uint64_t previous_captured_ns

References ASCIICHAT_OK, ffmpeg_encoder_s::codec_ctx, ERROR_FILE_OPERATION, ERROR_INVALID_PARAM, ERROR_MEDIA_INIT, ERROR_MEMORY, ffmpeg_encoder_s::estimated_frame_count, ffmpeg_encoder_s::first_frame_captured_ns, ffmpeg_encoder_s::fmt_ctx, ffmpeg_encoder_s::fps, ffmpeg_encoder_s::frame_count, ffmpeg_encoder_s::frame_encoded, g_snapshot_actual_duration_ms, g_snapshot_last_capture_elapsed_ns, GET_OPTION, ffmpeg_encoder_s::has_audio_stream, ffmpeg_encoder_s::height_px, ffmpeg_encoder_s::is_stdout_pipe, ffmpeg_encoder_s::last_video_pts, ffmpeg_encoder_s::live_timing, log_debug, log_debug_every, log_info, NS_PER_MS_INT, NS_PER_SEC_INT, ffmpeg_encoder_s::pkt, ffmpeg_encoder_s::previous_captured_ns, SET_ERRNO, ffmpeg_encoder_s::snapshot_actual_duration, ffmpeg_encoder_s::source_height, ffmpeg_encoder_s::stream, ffmpeg_encoder_s::sws_ctx, ffmpeg_encoder_s::target_pix_fmt, US_PER_SEC_INT, ffmpeg_encoder_s::video_pts, and ffmpeg_encoder_s::width_px.