PR #26222 opened by Pu Cheng (GeekQAQ)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26222
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26222.patch
X264_flush() drains the delayed frames by calling x264_encoder_encode()
with a NULL picture. For libx264 this ends the stream: the lookahead
thread is stopped, and every later x264_encoder_encode() with a picture
fails ("lookahead thread is already stopped"). The wrapper declares
AV_CODEC_CAP_ENCODER_FLUSH, and avcodec_flush_buffers() documents that
such an encoder "can then be reused for a different stream", but after
the flush every avcodec_send_frame() returns an error.
Close and reopen the encoder with the same parameters after draining,
and fail encoding cleanly if reopening failed.
Signed-off-by: Pu Cheng <[email protected]>
>From d699d96375af8f64c1fe0362bd996d44cb9d70d3 Mon Sep 17 00:00:00 2001
From: Pu Cheng <[email protected]>
Date: Fri, 20 Nov 2026 14:34:00 +0800
Subject: [PATCH] avcodec/libx264: reopen the encoder in the flush callback
X264_flush() drains the delayed frames by calling x264_encoder_encode()
with a NULL picture. For libx264 this ends the stream: the lookahead
thread is stopped, and every later x264_encoder_encode() with a picture
fails ("lookahead thread is already stopped"). The wrapper declares
AV_CODEC_CAP_ENCODER_FLUSH, and avcodec_flush_buffers() documents that
such an encoder "can then be reused for a different stream", but after
the flush every avcodec_send_frame() returns an error.
Close and reopen the encoder with the same parameters after draining,
and fail encoding cleanly if reopening failed.
Signed-off-by: Pu Cheng <[email protected]>
---
libavcodec/libx264.c | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
index f83be47e0c1..2a63c68476d 100644
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -642,6 +642,9 @@ static int X264_frame(AVCodecContext *ctx, AVPacket *pkt,
const AVFrame *frame,
int64_t wallclock = 0;
X264Opaque *out_opaque;
+ if (!x4->enc)
+ return AVERROR_EXTERNAL;
+
ret = setup_frame(ctx, frame, &pic_in);
if (ret < 0)
return ret;
@@ -775,6 +778,14 @@ static void X264_flush(AVCodecContext *avctx)
ret = x264_encoder_encode(x4->enc, &nal, &nnal, NULL, &pic_out);
} while (ret > 0 && x264_encoder_delayed_frames(x4->enc));
+ /* Flushing with a NULL picture ends the stream in libx264 (the lookahead
+ * thread is stopped and later pictures are rejected), so reopen the
+ * encoder with the same parameters. */
+ x264_encoder_close(x4->enc);
+ x4->enc = x264_encoder_open(&x4->params);
+ if (!x4->enc)
+ av_log(avctx, AV_LOG_ERROR, "Error reopening the encoder after
flush\n");
+
for (int i = 0; i < x4->nb_reordered_opaque; i++)
opaque_uninit(&x4->reordered_opaque[i]);
--
2.54.1
_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]