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

HEVC/H.265 encoder for ASCII art frames using libx265. More...

Go to the source code of this file.

Macros

#define H265_ENCODER_FLAG_KEYFRAME   0x01
#define H265_ENCODER_FLAG_SIZE_CHANGE   0x02

Functions

h265_encoder_t * h265_encoder_create (uint16_t initial_width, uint16_t initial_height)
h265_encoder_t * video_encoder_create (video_codec_t codec, uint16_t initial_width, uint16_t initial_height)
bool video_encoder_is_available (video_codec_t codec)
void h265_encoder_destroy (h265_encoder_t *encoder)
asciichat_error_t h265_encode (h265_encoder_t *encoder, uint16_t width, uint16_t height, const uint8_t *ascii_data, uint8_t *output_buf, size_t *output_size)
void h265_encoder_request_keyframe (h265_encoder_t *encoder)
asciichat_error_t h265_encoder_flush (h265_encoder_t *encoder, uint8_t *output_buf, size_t *output_size)
void h265_encoder_get_stats (h265_encoder_t *encoder, uint64_t *total_frames, uint64_t *keyframes, uint32_t *avg_bitrate)

Detailed Description

HEVC/H.265 encoder for ASCII art frames using libx265.

Encodes terminal ASCII grid data using x265 for efficient compression. Handles variable-sized frames by storing dimensions in the encoded packet.

FRAME SIZE CHANGES: When terminal resize occurs (width/height change), the encoder must be reconfigured. This is handled transparently - the encoder detects size changes and reinitializes as needed.

PACKET FORMAT: [flags: u8][width: u16][height: u16][encoded_data: x265]

  • flags: Encoding flags (keyframe, etc.)
  • width: Frame width in characters
  • height: Frame height in characters
  • encoded_data: x265-encoded frame data

Definition in file encoder.h.

Macro Definition Documentation

◆ H265_ENCODER_FLAG_KEYFRAME

#define H265_ENCODER_FLAG_KEYFRAME   0x01

Encoder flags

Definition at line 38 of file encoder.h.

Referenced by h265_encode(), and h265_encoder_flush().

◆ H265_ENCODER_FLAG_SIZE_CHANGE

#define H265_ENCODER_FLAG_SIZE_CHANGE   0x02

Definition at line 39 of file encoder.h.

Referenced by h265_encode().

Function Documentation

◆ h265_encode()

asciichat_error_t h265_encode ( h265_encoder_t * encoder,
uint16_t width,
uint16_t height,
const uint8_t * ascii_data,
uint8_t * output_buf,
size_t * output_size )

Encode an RGB24 upload frame

The encoder automatically detects size changes and reinitializes when needed. The output packet includes frame dimensions so decoder can reconfigure.

Parameters
encoderEncoder handle
widthCurrent frame width in pixels
heightCurrent frame height in pixels
ascii_dataRGB24 pixel data (width × height × 3 bytes)
output_bufBuffer for encoded output
output_sizeInput: buffer size, Output: actual encoded size
Returns
Error code (ASCIICHAT_OK on success)

OUTPUT PACKET FORMAT: [flags: u8][width: u16][height: u16][x265_data...]

Definition at line 316 of file encoder.c.

316 {
317 ASCII_OTEL_SCOPE(H265_ENCODE);
318 ASCII_OTEL_ATTR_INT("video.frame.width", width);
319 ASCII_OTEL_ATTR_INT("video.frame.height", height);
320 if (encoder && encoder->codec)
321 ASCII_OTEL_ATTR_STRING("video.codec", encoder->codec->id == AV_CODEC_ID_H264 ? "h264" : "h265");
322 if (!encoder || !ascii_data || !output_buf || !output_size) {
323 return SET_ERRNO(ERROR_INTERNAL, "Invalid encoder arguments");
324 }
325
326 if (!width || !height || (width & 1) || (height & 1)) {
327 return SET_ERRNO(ERROR_MEDIA_INIT, "Video encoding requires non-zero even dimensions, got %ux%u", width, height);
328 }
329
330 if (*output_size < 5) {
331 return SET_ERRNO(ERROR_NETWORK_SIZE, "Output buffer too small (minimum 5 bytes)");
332 }
333
334 bool size_changed = width != encoder->current_width || height != encoder->current_height;
335 asciichat_error_t result = h265_encoder_reconfigure(encoder, width, height);
336 if (result != ASCIICHAT_OK) {
337 return result;
338 }
339
340 h265_encoder_ascii_to_yuv420(ascii_data, width, height, encoder->yuv_buf);
341
342 // Setup frame data pointers
343 encoder->frame->data[0] = encoder->yuv_buf;
344 encoder->frame->data[1] = encoder->yuv_buf + width * height;
345 encoder->frame->data[2] = encoder->yuv_buf + width * height + (width / 2) * (height / 2);
346 encoder->frame->linesize[0] = width;
347 encoder->frame->linesize[1] = width / 2;
348 encoder->frame->linesize[2] = width / 2;
349 encoder->frame->width = width;
350 encoder->frame->height = height;
351 encoder->frame->format = AV_PIX_FMT_YUV420P;
352
353 encoder->frame->pts = (int64_t)encoder->frames_submitted++;
354 encoder->frame->pict_type = AV_PICTURE_TYPE_NONE;
355
356 // Request keyframe if needed
357 if (encoder->request_keyframe) {
358 encoder->frame->pict_type = AV_PICTURE_TYPE_I;
359 encoder->request_keyframe = false;
360 }
361
362 // Encode frame
363 uint64_t stats_codec_start = time_get_ns();
364 int send_ret = avcodec_send_frame(encoder->codec_ctx, encoder->frame);
365 if (send_ret < 0) {
366 stats_duration_record(stats_runtime_scope(), STATS_DURATION_ENCODE, time_get_ns() - stats_codec_start);
367 log_error("avcodec_send_frame failed: %d", send_ret);
368 return SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to send frame to encoder");
369 }
370
371 int recv_ret = avcodec_receive_packet(encoder->codec_ctx, encoder->packet);
372 stats_duration_record(stats_runtime_scope(), STATS_DURATION_ENCODE, time_get_ns() - stats_codec_start);
373 if (recv_ret == AVERROR(EAGAIN)) {
374 // EAGAIN is normal - encoder needs more frames before outputting a packet
375 log_dev("EAGAIN - encoder buffering frames (normal), waiting for next frame");
376 *output_size = 0; // No output this time
377 return ASCIICHAT_OK;
378 }
379 if (recv_ret < 0) {
380 log_error("avcodec_receive_packet failed: %d (EAGAIN=%d)", recv_ret, AVERROR(EAGAIN));
381 return SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to receive encoded packet");
382 }
383 log_debug_every(US_PER_SEC_INT, "Got encoded packet: size=%d", (int)encoder->packet->size);
384
385 uint8_t flags = 0;
386 if (encoder->packet->flags & AV_PKT_FLAG_KEY) {
388 encoder->keyframes++;
389 }
390
391 if (size_changed) {
393 }
394
395 size_t header_size = 5;
396 size_t packet_size = encoder->packet->size;
397 size_t required_size = header_size + packet_size;
398
399 if (required_size > *output_size) {
400 return SET_ERRNO(ERROR_NETWORK_SIZE, "Output buffer too small: need %zu, have %zu", required_size, *output_size);
401 }
402
403 // Write header: [flags][width:u16][height:u16]
404 output_buf[0] = flags;
405 output_buf[1] = (width >> 8) & 0xFF;
406 output_buf[2] = width & 0xFF;
407 output_buf[3] = (height >> 8) & 0xFF;
408 output_buf[4] = height & 0xFF;
409
410 // Write encoded data
411 if (packet_size > 0) {
412 memcpy(output_buf + header_size, encoder->packet->data, packet_size);
413 }
414
415 *output_size = required_size;
416 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_BYTES, (double)required_size);
417 if (encoder->packet->flags & AV_PKT_FLAG_KEY)
418 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_KEYFRAMES, 1);
419 ASCII_OTEL_ATTR_INT("video.packet.size", (int64_t)required_size);
420 ASCII_OTEL_ATTR_INT("video.frame.keyframe", (encoder->packet->flags & AV_PKT_FLAG_KEY) != 0);
421 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_FRAMES, 1);
422 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_INPUT, (double)width * height * 3);
423 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_BYTES_IN, (double)width * height * 3);
424 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_BYTES_OUT, (double)required_size);
425 encoder->total_frames++;
427 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_WIDTH, encoder->frame->width);
428 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_HEIGHT, encoder->frame->height);
429 if (required_size)
430 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_RATIO, (double)encoder->frame->width * encoder->frame->height * 3 / (double)required_size);
431 log_dev("[H265_ENCODE_DONE] Encoding complete, output_size=%zu", required_size);
432
433 return ASCIICHAT_OK;
434}
#define SET_ERRNO(code,...)
#define H265_ENCODER_FLAG_KEYFRAME
Definition encoder.h:38
#define H265_ENCODER_FLAG_SIZE_CHANGE
Definition encoder.h:39
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
unsigned long long uint64_t
unsigned char uint8_t
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_MEDIA_DECODE
Definition error_codes.h:72
@ ERROR_NETWORK_SIZE
Definition error_codes.h:83
@ ERROR_MEDIA_INIT
Definition error_codes.h:70
@ ERROR_INTERNAL
Definition error_codes.h:94
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define US_PER_SEC_INT
Definition time.h:177
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
uint64_t keyframes
Definition encoder.c:81
const AVCodec * codec
Definition encoder.c:66
uint64_t total_frames
Definition encoder.c:80
uint16_t current_height
Definition encoder.c:71
AVFrame * frame
Definition encoder.c:67
uint16_t current_width
Definition encoder.c:70
uint64_t frames_submitted
Definition encoder.c:79
uint8_t * yuv_buf
Definition encoder.c:73
AVCodecContext * codec_ctx
Definition encoder.c:65
bool request_keyframe
Definition encoder.c:77
AVPacket * packet
Definition encoder.c:68

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ascii_otel_metric(), ASCII_OTEL_SCOPE, ASCIICHAT_OK, h265_encoder::codec, h265_encoder::codec_ctx, h265_encoder::current_height, h265_encoder::current_width, ERROR_INTERNAL, ERROR_MEDIA_DECODE, ERROR_MEDIA_INIT, ERROR_NETWORK_SIZE, ERROR_NOT_SUPPORTED, h265_encoder::frame, h265_encoder::frames_submitted, H265_ENCODER_FLAG_KEYFRAME, H265_ENCODER_FLAG_SIZE_CHANGE, height, h265_encoder::keyframes, log_debug_every, log_dev, log_error, h265_encoder::packet, h265_encoder::request_keyframe, SET_ERRNO, stats_counter_add(), STATS_COUNTER_FRAMES_ENCODED, STATS_DURATION_ENCODE, stats_duration_record(), stats_runtime_scope(), h265_encoder::total_frames, US_PER_SEC_INT, width, and h265_encoder::yuv_buf.

Referenced by acip_send_image_frame_h265(), h265_client_capture_and_encode(), and threaded_send_image_frame_encoded().

◆ h265_encoder_create()

h265_encoder_t * h265_encoder_create ( uint16_t initial_width,
uint16_t initial_height )

Create a new x265 encoder for ASCII frames

Parameters
initial_widthInitial frame width (characters)
initial_heightInitial frame height (characters)
Returns
Encoder handle, or NULL on error

Definition at line 85 of file encoder.c.

85 {
86 ASCII_OTEL_SCOPE(H265_ENCODER_CREATE);
87 return video_encoder_create(VIDEO_CODEC_H265, initial_width, initial_height);
88}
@ VIDEO_CODEC_H265
H.265 (HEVC) video codec.
Definition codecs.h:30
h265_encoder_t * video_encoder_create(video_codec_t codec_type, uint16_t initial_width, uint16_t initial_height)
Definition encoder.c:90

References ASCII_OTEL_SCOPE, ERROR_NOT_SUPPORTED, SET_ERRNO, VIDEO_CODEC_H265, and video_encoder_create().

Referenced by h265_client_context_create().

◆ h265_encoder_destroy()

void h265_encoder_destroy ( h265_encoder_t * encoder)

Destroy an x265 encoder

Parameters
encoderEncoder to destroy (may be NULL)

Definition at line 178 of file encoder.c.

178 {
179 if (!encoder)
180 return;
181
182 if (encoder->frame) {
183 av_frame_free(&encoder->frame);
184 }
185 if (encoder->packet) {
186 av_packet_free(&encoder->packet);
187 }
188 if (encoder->codec_ctx) {
189 LOG_IO("video encoder", { avcodec_free_context(&encoder->codec_ctx); });
190 }
191 if (encoder->yuv_buf) {
192 SAFE_FREE(encoder->yuv_buf);
193 }
194 SAFE_FREE(encoder);
195}
#define SAFE_FREE(ptr)
#define LOG_IO(prefix, block)
Definition io.h:106

References h265_encoder::codec_ctx, h265_encoder::frame, LOG_IO, h265_encoder::packet, SAFE_FREE, and h265_encoder::yuv_buf.

Referenced by h265_client_context_create(), h265_client_context_destroy(), and video_encoder_create().

◆ h265_encoder_flush()

asciichat_error_t h265_encoder_flush ( h265_encoder_t * encoder,
uint8_t * output_buf,
size_t * output_size )

Flush remaining buffered frames from encoder

Sends a NULL frame to the encoder to flush all buffered frames. This should be called before destroying the encoder or when you need to ensure all encoded data is retrieved.

Parameters
encoderEncoder handle
output_bufBuffer for encoded output
output_sizeInput: buffer size, Output: actual encoded size
Returns
Error code (ASCIICHAT_OK on success, ASCIICHAT_OK with size=0 when no more data)

USAGE: // After final h265_encode() call, flush remaining frames while (size > 0) { size = max_size; h265_encoder_flush(encoder, buf, &size); if (size > 0) { // Send the flushed frame... } }

Definition at line 442 of file encoder.c.

442 {
443 ASCII_OTEL_SCOPE(H265_ENCODER_FLUSH);
444 if (!encoder || !output_buf || !output_size) {
445 return SET_ERRNO(ERROR_INTERNAL, "Invalid encoder or output parameters for flush");
446 }
447
448 if (*output_size < 5) {
449 return SET_ERRNO(ERROR_NETWORK_SIZE, "Output buffer too small (minimum 5 bytes)");
450 }
451
452 if (!encoder->codec_opened) {
453 *output_size = 0;
454 return ASCIICHAT_OK;
455 }
456
457 // Send NULL frame to signal end of stream (flushes encoder)
458 log_debug("H265_FLUSH: Sending NULL frame to encoder to flush buffered data");
459 uint64_t stats_codec_start = time_get_ns();
460 int send_ret = avcodec_send_frame(encoder->codec_ctx, NULL);
461 if (send_ret < 0) {
462 stats_duration_record(stats_runtime_scope(), STATS_DURATION_ENCODE, time_get_ns() - stats_codec_start);
463 log_error("H265_FLUSH: avcodec_send_frame(NULL) failed: %d", send_ret);
464 return SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to flush encoder");
465 }
466
467 // Try to receive a packet
468 log_debug("H265_FLUSH: Attempting to receive flushed packet...");
469 int recv_ret = avcodec_receive_packet(encoder->codec_ctx, encoder->packet);
470 stats_duration_record(stats_runtime_scope(), STATS_DURATION_ENCODE, time_get_ns() - stats_codec_start);
471 if (recv_ret == AVERROR(EAGAIN)) {
472 log_dev("H265_FLUSH: EAGAIN - no more frames available");
473 *output_size = 0;
474 return ASCIICHAT_OK;
475 }
476 if (recv_ret == AVERROR_EOF) {
477 log_debug("H265_FLUSH: EOF - encoder is flushed");
478 *output_size = 0;
479 return ASCIICHAT_OK;
480 }
481 if (recv_ret < 0) {
482 log_error("H265_FLUSH: avcodec_receive_packet failed: %d", recv_ret);
483 return SET_ERRNO(ERROR_MEDIA_DECODE, "Failed to receive flushed packet");
484 }
485
486 log_debug("H265_FLUSH: Got flushed packet: size=%d", (int)encoder->packet->size);
487
488 // Check if packet size exceeds output buffer
489 size_t header_size = 5;
490 size_t packet_size = encoder->packet->size;
491 size_t required_size = header_size + packet_size;
492
493 if (required_size > *output_size) {
494 return SET_ERRNO(ERROR_NETWORK_SIZE, "Output buffer too small: need %zu, have %zu", required_size, *output_size);
495 }
496
497 // Write header: [flags][width:u16][height:u16]
498 uint8_t flags = 0;
499 if (encoder->packet->flags & AV_PKT_FLAG_KEY) {
501 encoder->keyframes++;
502 }
503
504 output_buf[0] = flags;
505 output_buf[1] = (encoder->current_width >> 8) & 0xFF;
506 output_buf[2] = encoder->current_width & 0xFF;
507 output_buf[3] = (encoder->current_height >> 8) & 0xFF;
508 output_buf[4] = encoder->current_height & 0xFF;
509
510 // Write encoded data
511 if (packet_size > 0) {
512 memcpy(output_buf + header_size, encoder->packet->data, packet_size);
513 }
514
515 *output_size = required_size;
516 ASCII_OTEL_ATTR_INT("video.packet.size", (int64_t)required_size);
517 if (encoder->codec)
518 ASCII_OTEL_ATTR_STRING("video.codec", encoder->codec->id == AV_CODEC_ID_H264 ? "h264" : "h265");
519 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_FRAMES, 1);
520 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_ENCODE_BYTES_OUT, (double)required_size);
521 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_BYTES, (double)required_size);
522 if (encoder->packet->flags & AV_PKT_FLAG_KEY)
523 ascii_otel_metric(ASCII_OTEL_METRIC_VIDEO_KEYFRAMES, 1);
524 encoder->total_frames++;
526
527 return ASCIICHAT_OK;
528}
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
bool codec_opened
Definition encoder.c:76

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ascii_otel_metric(), ASCII_OTEL_SCOPE, ASCIICHAT_OK, h265_encoder::codec, h265_encoder::codec_ctx, h265_encoder::codec_opened, h265_encoder::current_height, h265_encoder::current_width, ERROR_INTERNAL, ERROR_INVALID_PARAM, ERROR_MEDIA_DECODE, ERROR_NETWORK_SIZE, H265_ENCODER_FLAG_KEYFRAME, h265_encoder::keyframes, log_debug, log_dev, log_error, h265_encoder::packet, SET_ERRNO, stats_counter_add(), STATS_COUNTER_FRAMES_ENCODED, STATS_DURATION_ENCODE, stats_duration_record(), stats_runtime_scope(), and h265_encoder::total_frames.

◆ h265_encoder_get_stats()

void h265_encoder_get_stats ( h265_encoder_t * encoder,
uint64_t * total_frames,
uint64_t * keyframes,
uint32_t * avg_bitrate )

Get encoder statistics

Parameters
encoderEncoder handle
total_framesOutput: total frames encoded
keyframesOutput: total keyframes encoded
avg_bitrateOutput: average bitrate in bits per second

Definition at line 530 of file encoder.c.

530 {
531 if (!encoder)
532 return;
533
534 if (total_frames)
535 *total_frames = encoder->total_frames;
536 if (keyframes)
537 *keyframes = encoder->keyframes;
538 if (avg_bitrate)
539 *avg_bitrate = encoder->avg_bitrate;
540}
uint32_t avg_bitrate
Definition encoder.c:82

References h265_encoder::avg_bitrate, h265_encoder::keyframes, and h265_encoder::total_frames.

Referenced by h265_client_get_stats().

◆ h265_encoder_request_keyframe()

void h265_encoder_request_keyframe ( h265_encoder_t * encoder)

Request a keyframe on the next encode

Forces the encoder to produce an I-frame (keyframe) on the next call to h265_encoder_encode(). Useful for error recovery or stream synchronization.

Parameters
encoderEncoder handle

Definition at line 436 of file encoder.c.

436 {
437 if (encoder) {
438 encoder->request_keyframe = true;
439 }
440}

References h265_encoder::request_keyframe.

Referenced by acip_send_image_frame_h265(), h265_client_request_keyframe(), and threaded_send_image_frame_encoded().

◆ video_encoder_create()

h265_encoder_t * video_encoder_create ( video_codec_t codec,
uint16_t initial_width,
uint16_t initial_height )

Create an HEVC or H.264 RGB24 upload encoder with the shared frame envelope. The legacy h265 encode/destroy functions also operate on H.264 instances.

Definition at line 90 of file encoder.c.

90 {
91 ASCII_OTEL_SCOPE(VIDEO_ENCODER_CREATE);
92 ASCII_OTEL_ATTR_STRING("video.codec", codec_type == VIDEO_CODEC_H264 ? "h264" : "h265");
93 ASCII_OTEL_ATTR_INT("video.frame.width", initial_width);
94 ASCII_OTEL_ATTR_INT("video.frame.height", initial_height);
95 if (codec_type != VIDEO_CODEC_H265 && codec_type != VIDEO_CODEC_H264) {
96 SET_ERRNO(ERROR_INVALID_PARAM, "Expected HEVC or H.264 codec");
97 return NULL;
98 }
99 if (initial_width == 0 || initial_height == 0) {
100 SET_ERRNO(ERROR_MEDIA_INIT, "Frame dimensions must be non-zero");
101 return NULL;
102 }
103
105 if (!enc) {
106 SET_ERRNO(ERROR_MEMORY, "Failed to allocate encoder structure");
107 return NULL;
108 }
109
110 defer_named(cleanup, h265_encoder_destroy(enc));
111
112 const AVCodec *codec = video_encoder_find_codec(codec_type);
113 if (!codec) {
114 SET_ERRNO(ERROR_MEDIA_INIT, "%s encoder not found", codec_type == VIDEO_CODEC_H264 ? "H.264" : "HEVC");
115 return NULL;
116 }
117 enc->codec = codec;
118
119 enc->codec_ctx = avcodec_alloc_context3(codec);
120 if (!enc->codec_ctx) {
121 SET_ERRNO(ERROR_MEMORY, "Failed to allocate codec context");
122 return NULL;
123 }
124
125 // Configure codec context
126 enc->codec_ctx->width = initial_width;
127 enc->codec_ctx->height = initial_height;
128 enc->codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
129 enc->codec_ctx->time_base = (AVRational){1, 30};
130 enc->codec_ctx->framerate = (AVRational){30, 1};
131
132 // Set ultrafast preset for low-latency encoding
133 if (av_opt_set(enc->codec_ctx->priv_data, "preset", "ultrafast", 0) < 0) {
134 log_warn("Failed to set preset to ultrafast, using default");
135 }
136 if (av_opt_set(enc->codec_ctx->priv_data, "tune", "zerolatency", 0) < 0) {
137 log_warn("Failed to set tune to zerolatency, using default");
138 }
139
140 enc->codec_ctx->thread_count = h265_thread_count();
141
142 // Defer avcodec_open2 to first encode call. The initial resolution (800x600) is
143 // usually wrong — the actual frame resolution is only known when the first capture
144 // arrives. Opening the codec here would create an x265 thread pool (~1s) that gets
145 // immediately discarded on reconfigure, wasting startup time.
146 enc->codec_opened = false;
147
148 // Allocate frame and packet
149 enc->frame = av_frame_alloc();
150 enc->packet = av_packet_alloc();
151
152 if (!enc->frame || !enc->packet) {
153 SET_ERRNO(ERROR_MEMORY, "Failed to allocate frame/packet");
154 return NULL;
155 }
156
157 enc->current_width = initial_width;
158 enc->current_height = initial_height;
159
160 // Allocate YUV420P buffer (Y plane + U/V planes)
161 size_t stride = initial_width;
162 enc->yuv_buf_size = stride * initial_height * 3 / 2;
163 enc->yuv_buf = SAFE_MALLOC(enc->yuv_buf_size, uint8_t *);
164 if (!enc->yuv_buf) {
165 SET_ERRNO(ERROR_MEMORY, "Failed to allocate YUV buffer");
166 return NULL;
167 }
168
169 log_info("FFmpeg video encoder created: %ux%u (codec: %s)", initial_width, initial_height, codec->name);
170
171 // Register encoder for debugging
172 NAMED_REGISTER_H265_ENCODER(enc, "h265_encoder", NULL);
173
174 defer_cancel(cleanup);
175 return enc;
176}
@ VIDEO_CODEC_H264
H.264 (AVC) video codec.
Definition codecs.h:32
void h265_encoder_destroy(h265_encoder_t *encoder)
Definition encoder.c:178
struct h265_encoder h265_encoder_t
h265 encoder is intentionally a small, concrete record. Fields such as codec_ctx, codec,...
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_H265_ENCODER(encoder, name, parent_ptr)
Register an H.265 encoder with automatic format specifier.
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
size_t yuv_buf_size
Definition encoder.c:74

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ASCII_OTEL_SCOPE, h265_encoder::codec, h265_encoder::codec_ctx, h265_encoder::codec_opened, h265_encoder::current_height, h265_encoder::current_width, ERROR_INVALID_PARAM, ERROR_MEDIA_INIT, ERROR_MEMORY, h265_encoder::frame, h265_encoder_destroy(), log_info, log_warn, NAMED_REGISTER_H265_ENCODER, h265_encoder::packet, SAFE_CALLOC, SAFE_MALLOC, SET_ERRNO, VIDEO_CODEC_H264, VIDEO_CODEC_H265, h265_encoder::yuv_buf, and h265_encoder::yuv_buf_size.

Referenced by h265_encoder_create(), and threaded_send_image_frame_encoded().

◆ video_encoder_is_available()

bool video_encoder_is_available ( video_codec_t codec)

Return whether a usable software encoder is registered for codec.

This probe is side-effect free: it does not allocate, open a codec context, or set errno. Automatic capture uses it to avoid probing unavailable codecs and reporting expected fallback failures to the user.

Definition at line 53 of file encoder.c.

53 {
54 if (codec != VIDEO_CODEC_H265 && codec != VIDEO_CODEC_H264)
55 return false;
56 return video_encoder_find_codec(codec) != NULL;
57}

References VIDEO_CODEC_H264, and VIDEO_CODEC_H265.