Commit e47940a572 for ffmpeg

commit e47940a5721cc5dace23db84038a9a08319f4fca
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Sat Oct 17 11:18:11 2026 -0700

    avcodec/mpeg12enc: add optional sequence end code

    Add the seq_end option to append a sequence end code to the final
    MPEG-2 picture packet. Detect the final picture from both existing
    picture queues so B-frame draining emits exactly one end code.

    Include the sequence end code in VBV frame-size checks and accounting
    before calculating stuffing and vbv_delay.

    Keep the option in the encoder context and reject low-delay mode and
    frame skipping, which can leave no final picture packet to carry the
    end code. Document the option and add FATE coverage for partial and
    queued B-frame chains, CBR accounting and frame-skip option validation.

    Signed-off-by: Baptiste Coudurier <baptiste.coudurier@gmail.com>
    Assisted-by: Fairy

diff --git a/doc/encoders.texi b/doc/encoders.texi
index d3487b40a5..cf3861d679 100644
--- a/doc/encoders.texi
+++ b/doc/encoders.texi
@@ -3781,6 +3781,11 @@ Select the mpeg2 level to encode:
 @item low
 @end table

+@item seq_end @var{boolean}
+Write a sequence end code after the last picture. Disabled by default.
+Cannot be combined with @option{flags +low_delay} or frame skipping
+(@option{skip_threshold} or @option{skip_factor}).
+
 @item seq_disp_ext @var{integer}
 Specifies if the encoder should write a sequence_display_extension to the
 output.
diff --git a/libavcodec/mpeg12enc.c b/libavcodec/mpeg12enc.c
index ab2df9d1f9..06efdd065a 100644
--- a/libavcodec/mpeg12enc.c
+++ b/libavcodec/mpeg12enc.c
@@ -1056,6 +1056,16 @@ static av_cold int encode_init(AVCodecContext *avctx)
     int ret;
     int max_size = avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO ? 16383 : 4095;

+    if (m->seq_end && (avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
+        av_log(avctx, AV_LOG_ERROR, "Sequence end code is not supported with low delay\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (m->seq_end && (m->frame_skip_threshold || m->frame_skip_factor)) {
+        av_log(avctx, AV_LOG_ERROR, "Sequence end code is not supported with frame skipping\n");
+        return AVERROR(EINVAL);
+    }
+
     if (avctx->width > max_size || avctx->height > max_size) {
         av_log(avctx, AV_LOG_ERROR, "%s does not support resolutions above %dx%d\n",
                CONFIG_SMALL ? avctx->codec->name : avctx->codec->long_name,
@@ -1268,6 +1278,7 @@ static const AVOption mpeg2_options[] = {
       FF_MPV_OFFSET(c.intra_vlc_format),    AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
     { "non_linear_quant", "Use nonlinear quantizer.",    FF_MPV_OFFSET(c.q_scale_type),   AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
     { "alternate_scan",   "Enable alternate scantable.", FF_MPV_OFFSET(c.alternate_scan), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
+    { "seq_end",          "Write sequence end code.",    FF_MPV_MAIN_OFFSET(seq_end),     AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
     { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc),         AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
     { "seq_disp_ext",     "Write sequence_display_extension blocks.", OFFSET(seq_disp_ext), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE, .unit = "seq_disp_ext" },
     {     "auto",   NULL, 0, AV_OPT_TYPE_CONST,  {.i64 = -1},  0, 0, VE, .unit = "seq_disp_ext" },
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index b160626610..dd2cb487a2 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -1916,6 +1916,7 @@ int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
     MPVMainEncContext *const m = avctx->priv_data;
     MPVEncContext    *const s = &m->s;
     int stuffing_count, ret;
+    int seq_end = !pic_arg && m->seq_end;
     int context_count = s->c.slice_context_count;

     ff_mpv_unref_picture(&s->c.cur_pic);
@@ -1932,6 +1933,10 @@ int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
     if (ret < 0)
         return ret;

+    /* Both queues must be empty after selecting the last picture. */
+    for (int i = 1; seq_end && i <= MPVENC_MAX_B_FRAMES; i++)
+        seq_end = !m->input_picture[i] && !m->reordered_input_picture[i];
+
     /* output? */
     if (s->new_pic->data[0]) {
         int growing_buffer = context_count == 1 && !s->data_partitioning;
@@ -1980,7 +1985,7 @@ vbv_retry:
             int hq = (avctx->mb_decision == FF_MB_DECISION_RD || avctx->trellis);
             int min_step = hq ? 1 : (1<<(FF_LAMBDA_SHIFT + 7))/139;

-            if (put_bits_count(&s->pb) > max_size &&
+            if (put_bits_count(&s->pb) + 32 * seq_end > max_size &&
                 s->lambda < m->lmax) {
                 m->next_lambda = FFMAX(s->lambda + min_step, s->lambda *
                                        (s->c.qscale + 1) / s->c.qscale);
@@ -2025,7 +2030,8 @@ vbv_retry:
         flush_put_bits(&s->pb);
         m->frame_bits  = put_bits_count(&s->pb);

-        stuffing_count = ff_vbv_update(m, m->frame_bits);
+        /* The sequence end code is part of the last picture's VBV size. */
+        stuffing_count = ff_vbv_update(m, m->frame_bits + 32 * seq_end);
         m->stuffing_bits = 8*stuffing_count;
         if (stuffing_count) {
             if (put_bytes_left(&s->pb, 0) < stuffing_count + 50) {
@@ -2056,6 +2062,12 @@ vbv_retry:
             m->frame_bits  = put_bits_count(&s->pb);
         }

+        if (seq_end) {
+            put_bits32(&s->pb, 0x1B7); // sequence_end_code
+            flush_put_bits(&s->pb);
+            m->frame_bits = put_bits_count(&s->pb);
+        }
+
         /* update MPEG-1/2 vbv_delay for CBR */
         if (avctx->rc_max_rate                          &&
             avctx->rc_min_rate == avctx->rc_max_rate &&
diff --git a/libavcodec/mpegvideoenc.h b/libavcodec/mpegvideoenc.h
index 3943a284e8..c4275d2b01 100644
--- a/libavcodec/mpegvideoenc.h
+++ b/libavcodec/mpegvideoenc.h
@@ -209,6 +209,8 @@ typedef struct MPVMainEncContext {
     int input_picture_number;      ///< used to set pic->display_picture_number
     int coded_picture_number;      ///< used to set pic->coded_picture_number

+    int seq_end;                   ///< write sequence end code after the last picture
+
     MPVPicture *input_picture[MPVENC_MAX_B_FRAMES + 1]; ///< next pictures in display order
     MPVPicture *reordered_input_picture[MPVENC_MAX_B_FRAMES + 1]; ///< next pictures in coded order

diff --git a/tests/fate/ffmpeg.mak b/tests/fate/ffmpeg.mak
index a0d99340a4..e665b08bb9 100644
--- a/tests/fate/ffmpeg.mak
+++ b/tests/fate/ffmpeg.mak
@@ -502,6 +502,23 @@ fate-ffmpeg-loopback-decoding: CMD = transcode \
     "-map 0:v:0 -c:v mpeg2video -f null - -flags +bitexact -idct simple -threads $$threads -dec 0:0 -filter_complex '[0:v][dec:0]hstack[stack]' -map '[stack]' -c:v ffv1" ""
 FATE_FFMPEG-$(call ENCDEC2, MPEG2VIDEO, FFV1, NUT, HSTACK_FILTER PIPE_PROTOCOL FRAMECRC_MUXER) += fate-ffmpeg-loopback-decoding

+# Test sequence end with a partial B-frame chain and with queued B-frames.
+FATE_FFMPEG-$(call ENCMUX, MPEG2VIDEO, MPEG2VIDEO, TESTSRC2_FILTER FILE_PROTOCOL) += fate-mpeg2-seq-end-short fate-mpeg2-seq-end-bframes
+fate-mpeg2-seq-end-short: CMD = md5 -filter_complex testsrc2=s=64x64:r=25:d=0.08 -c:v mpeg2video -flags +bitexact -dct fastint -q:v 2 -bf 2 -seq_end 1 -f mpeg2video
+fate-mpeg2-seq-end-bframes: CMD = md5 -filter_complex testsrc2=s=64x64:r=25:d=0.12 -c:v mpeg2video -flags +bitexact -dct fastint -q:v 2 -bf 1 -seq_end 1 -f mpeg2video
+
+# Account for the end code before calculating CBR stuffing and vbv_delay.
+FATE_FFMPEG-$(call ENCMUX, MPEG2VIDEO, MPEG2VIDEO, COLOR_FILTER FILE_PROTOCOL) += fate-mpeg2-seq-end-cbr
+fate-mpeg2-seq-end-cbr: CMD = md5 -filter_complex color=s=64x64:r=25:d=0.08 -c:v mpeg2video -flags +bitexact -dct fastint -b:v 90000 -minrate 90000 -maxrate 90000 -bufsize 65536 -rc_init_occupancy 65536 -seq_end 1 -f mpeg2video
+
+# Skipping the last queued picture would leave no packet for the end code.
+FATE_FFMPEG-$(call ENCMUX, MPEG2VIDEO, MPEG2VIDEO, COLOR_FILTER PIPE_PROTOCOL) += fate-mpeg2-seq-end-skip-threshold fate-mpeg2-seq-end-skip-factor
+fate-mpeg2-seq-end-skip-threshold: SKIP_OPT = skip_threshold
+fate-mpeg2-seq-end-skip-factor: SKIP_OPT = skip_factor
+fate-mpeg2-seq-end-skip-threshold fate-mpeg2-seq-end-skip-factor: CMP = grep
+fate-mpeg2-seq-end-skip-threshold fate-mpeg2-seq-end-skip-factor: REF = Sequence end code is not supported with frame skipping
+fate-mpeg2-seq-end-skip-threshold fate-mpeg2-seq-end-skip-factor: CMD = ffmpeg -filter_complex color=s=64x64:r=25:d=0.08 -c:v mpeg2video -$(SKIP_OPT) 1 -seq_end 1 -f mpeg2video -; test $$? -ne 0
+
 # test matching by stream disposition
 fate-ffmpeg-spec-disposition: CMD = framecrc -i $(TARGET_SAMPLES)/mpegts/pmtchange.ts -map '0:disp:visual_impaired+descriptions:1' -c copy
 FATE_SAMPLES_FFMPEG-$(call FRAMECRC, MPEGTS,,) += fate-ffmpeg-spec-disposition
diff --git a/tests/ref/fate/mpeg2-seq-end-bframes b/tests/ref/fate/mpeg2-seq-end-bframes
new file mode 100644
index 0000000000..76323f5145
--- /dev/null
+++ b/tests/ref/fate/mpeg2-seq-end-bframes
@@ -0,0 +1 @@
+79f0eefaeaf99d10de679f2b7d640398
diff --git a/tests/ref/fate/mpeg2-seq-end-cbr b/tests/ref/fate/mpeg2-seq-end-cbr
new file mode 100644
index 0000000000..2e6dbf3f55
--- /dev/null
+++ b/tests/ref/fate/mpeg2-seq-end-cbr
@@ -0,0 +1 @@
+03f6dc6775f77b84966d16d464b8f292
diff --git a/tests/ref/fate/mpeg2-seq-end-short b/tests/ref/fate/mpeg2-seq-end-short
new file mode 100644
index 0000000000..c88f08f564
--- /dev/null
+++ b/tests/ref/fate/mpeg2-seq-end-short
@@ -0,0 +1 @@
+0df4fa71ba94fa23a72e853133febfd7