Commit adf4e8ed2c for ffmpeg

commit adf4e8ed2c93557dfe6a3e710d8d3d7d09f2cfad
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Fri Nov 13 14:02:23 2026 -0800

    avcodec/h264dec: reset has_b_frames when a new SPS follows a flush

    Start from the caller's reorder depth when switching to an unseen SPS
    after a flush. For SPSs without a signalled limit, retain the maximum
    learned depth on replay and in-band switches to avoid dropping pictures.
    Once the SPS history overflows, treat unfamiliar SPSs as possible
    replays, which can delay output on a new stream.

    Fixes: #25321

    Signed-off-by: Baptiste Coudurier <baptiste.coudurier@gmail.com>
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/libavcodec/h264_ps.c b/libavcodec/h264_ps.c
index e72d39ea8d..a4afb969de 100644
--- a/libavcodec/h264_ps.c
+++ b/libavcodec/h264_ps.c
@@ -27,6 +27,7 @@

 #include <inttypes.h>

+#include "libavutil/crc.h"
 #include "libavutil/imgutils.h"
 #include "mathops.h"
 #include "avcodec.h"
@@ -286,6 +287,7 @@ int ff_h264_decode_seq_parameter_set(GetBitContext *gb, AVCodecContext *avctx,
 {
     int profile_idc, level_idc, constraint_set_flags = 0;
     unsigned int sps_id;
+    const unsigned data_offset = get_bits_count(gb) / 8;
     int i, log2_max_frame_num_minus4;
     SPS *sps;
     int ret;
@@ -575,6 +577,12 @@ int ff_h264_decode_seq_parameter_set(GetBitContext *gb, AVCodecContext *avctx,
                );
     }

+    /* Hash the payload only, as a nal_ref_idc change keeps the SPS:
+     * the normal reader has consumed the NAL header, the fallback
+     * reader starts at the payload. */
+    sps->payload_crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), 0,
+                              sps->data + data_offset, sps->data_size - data_offset);
+
     /* check if this is a repeat of an already parsed SPS, then keep the
      * original one.
      * otherwise drop all PPSes that depend on it */
diff --git a/libavcodec/h264_ps.h b/libavcodec/h264_ps.h
index f216e4989f..312c41bdd1 100644
--- a/libavcodec/h264_ps.h
+++ b/libavcodec/h264_ps.h
@@ -100,6 +100,7 @@ typedef struct SPS {
     int bit_depth_chroma;                 ///< bit_depth_chroma_minus8 + 8
     int residual_color_transform_flag;    ///< residual_colour_transform_flag
     int constraint_set_flags;             ///< constraint_set[0-3]_flag
+    uint32_t payload_crc;                 ///< CRC of the SPS data excluding the NAL header
     uint8_t data[4096];
     size_t data_size;
 } SPS;
diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
index 1e28f2bdfa..8e52c7e8ad 100644
--- a/libavcodec/h264_slice.c
+++ b/libavcodec/h264_slice.c
@@ -375,6 +375,8 @@ int ff_h264_update_thread_context(AVCodecContext *dst,
     av_refstruct_replace(&h->ps.pps, h1->ps.pps);
     h->ps.sps = h1->ps.sps;

+    h->sps_history = h1->sps_history;
+
     if (need_reinit || !inited) {
         h->width     = h1->width;
         h->height    = h1->height;
@@ -1081,6 +1083,41 @@ static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
     }
 }

+static void update_sps_depth(H264Context *h, const SPS *sps)
+{
+    const uint32_t crc = sps->payload_crc;
+    const int count = h->sps_history.count;
+    const int capacity = FF_ARRAY_ELEMS(h->sps_history.seen);
+    const int can_reset = h->sps_history.can_reset;
+    /* Once the list overflows, any SPS could be a replay. */
+    int known = count > capacity;
+    int depth = h->avctx->has_b_frames;
+
+    if (count && h->sps_history.active_crc == crc && !can_reset)
+        return;
+
+    h->sps_history.can_reset = 0;
+    if (count)
+        h->sps_history.max_depth = FFMAX(h->sps_history.max_depth, depth);
+    h->sps_history.active_crc = crc;
+
+    for (int i = 0; i < count && !known; i++)
+        known = h->sps_history.seen[i] == crc;
+    if (!known) {
+        if (count < capacity)
+            h->sps_history.seen[count] = crc;
+        h->sps_history.count++;
+    }
+
+    /* The output queue is empty until the first successful setup after a
+     * flush, so only then may the depth return to the caller's value. */
+    if (can_reset)
+        depth = h->has_b_frames_from_caller;
+    if (!sps->bitstream_restriction_flag && (known || !can_reset))
+        depth = FFMAX(depth, h->sps_history.max_depth);
+    h->avctx->has_b_frames = depth;
+}
+
 static int h264_init_ps(H264Context *h, const H264SliceContext *sl, int first_slice)
 {
     const SPS *sps;
@@ -1193,6 +1230,9 @@ static int h264_init_ps(H264Context *h, const H264SliceContext *sl, int first_sl
         }
     }

+    /* Do not change the depth history until the new setup succeeds. */
+    update_sps_depth(h, sps);
+
     return 0;
 }

diff --git a/libavcodec/h264dec.c b/libavcodec/h264dec.c
index b2ff1241c9..4261c6a146 100644
--- a/libavcodec/h264dec.c
+++ b/libavcodec/h264dec.c
@@ -291,8 +291,10 @@ static int h264_init_context(AVCodecContext *avctx, H264Context *h)
     h->avctx                 = avctx;
     h->cur_chroma_format_idc = -1;

-    h->width_from_caller     = avctx->width;
-    h->height_from_caller    = avctx->height;
+    h->width_from_caller        = avctx->width;
+    h->height_from_caller       = avctx->height;
+    h->has_b_frames_from_caller = avctx->has_b_frames;
+    h->sps_history.can_reset    = 1;

     h->workaround_bugs       = avctx->workaround_bugs;
     h->flags                 = avctx->flags;
@@ -491,6 +493,7 @@ static av_cold void h264_decode_flush(AVCodecContext *avctx)

     ff_h264_free_tables(h);
     h->context_initialized = 0;
+    h->sps_history.can_reset = 1;

     if (FF_HW_HAS_CB(avctx, flush))
         FF_HW_SIMPLE_CALL(avctx, flush);
diff --git a/libavcodec/h264dec.h b/libavcodec/h264dec.h
index 276ea1c4a0..d2ab34aa8b 100644
--- a/libavcodec/h264dec.h
+++ b/libavcodec/h264dec.h
@@ -571,6 +571,15 @@ typedef struct H264Context {
      * cropping */
     int width_from_caller;
     int height_from_caller;
+    int has_b_frames_from_caller;
+
+    struct {
+        uint32_t seen[MAX_SPS_COUNT + 1]; ///< includes the active SPS
+        int count;         ///< one past capacity once history is incomplete
+        int max_depth;     ///< highest depth saved over the decoder lifetime
+        int can_reset;     ///< no successful SPS setup since open or flush
+        uint32_t active_crc; ///< last successfully set up SPS payload
+    } sps_history;

     int enable_er;
     ERContext er;
diff --git a/tests/api/Makefile b/tests/api/Makefile
index db026e929c..56fdec1d92 100644
--- a/tests/api/Makefile
+++ b/tests/api/Makefile
@@ -4,6 +4,7 @@ APITESTPROGS-$(CONFIG_AMR_PARSER) += api-amr-parser
 APITESTPROGS-$(call ALLYES, LIBASTCENC_ENCODER LIBASTCENC_DECODER) += api-astc-profile
 APITESTPROGS-$(call ENCDEC, FLAC, FLAC) += api-flac
 APITESTPROGS-$(call DEMDEC, H264, H264) += api-h264
+APITESTPROGS-$(call DEMDEC, H264, H264, H264_PARSER) += api-h264-flush
 APITESTPROGS-$(call DEMDEC, H264, H264) += api-h264-slice
 APITESTPROGS-$(CONFIG_MOV_MUXER)        += api-movenc
 APITESTPROGS-$(CONFIG_MOVTEXT_ENCODER)  += api-movtext
diff --git a/tests/api/api-h264-flush-test.c b/tests/api/api-h264-flush-test.c
new file mode 100644
index 0000000000..e9045f9f34
--- /dev/null
+++ b/tests/api/api-h264-flush-test.c
@@ -0,0 +1,169 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "libavcodec/avcodec.h"
+#include "libavformat/avformat.h"
+#include "libavutil/adler32.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/mem.h"
+
+static void check(int ret)
+{
+    if (ret < 0) {
+        fprintf(stderr, "%s\n", av_err2str(ret));
+        exit(1);
+    }
+}
+
+enum DecodeReport {
+    REPORT_FRAMES = 1,
+    REPORT_TIMING = 2,
+};
+
+/* A limit ends the first input after that many packets. If there is a
+ * second input, continue with it without draining; otherwise stop. */
+static void decode(AVCodecContext *ctx, const char *path,
+                   const char *next_path, int limit, int report)
+{
+    AVFormatContext *fmt = NULL;
+    AVPacket *pkt = av_packet_alloc();
+    AVFrame *frame = av_frame_alloc();
+    AVAdler checksum = 1;
+    int packets = 0, frames = 0, first_packet = 0, eof = 0, ret;
+
+    if (!pkt || !frame)
+        exit(1);
+    check(avformat_open_input(&fmt, path, av_find_input_format("h264"), NULL));
+    while (!eof) {
+        const int at_limit = limit && packets == limit;
+
+        if (at_limit && !next_path)
+            break;
+        ret = at_limit ? AVERROR_EOF : av_read_frame(fmt, pkt);
+        if (ret == AVERROR_EOF) {
+            if (limit && !at_limit)
+                check(ret);
+            if (next_path) {
+                avformat_close_input(&fmt);
+                check(avformat_open_input(&fmt, next_path, av_find_input_format("h264"), NULL));
+                next_path = NULL;
+                limit = 0;
+                continue;
+            }
+            eof = 1;
+            check(avcodec_send_packet(ctx, NULL));
+        } else {
+            check(ret);
+            check(avcodec_send_packet(ctx, pkt));
+            av_packet_unref(pkt);
+            packets++;
+        }
+        while ((ret = avcodec_receive_frame(ctx, frame)) >= 0) {
+            int size;
+            uint8_t *data;
+
+            if (!report)
+                continue;
+            if (!frames++)
+                first_packet = packets + eof;
+            if (!(report & REPORT_FRAMES))
+                continue;
+            size = av_image_get_buffer_size(frame->format, frame->width,
+                                           frame->height, 1);
+            check(size);
+            data = av_malloc(size);
+            if (!data)
+                exit(1);
+            check(av_image_copy_to_buffer(data, size,
+                                         (const uint8_t *const *)frame->data,
+                                         frame->linesize, frame->format,
+                                         frame->width, frame->height, 1));
+            checksum = av_adler32_update(checksum, data, size);
+            av_free(data);
+        }
+        if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
+            check(ret);
+    }
+    if (report & REPORT_TIMING)
+        printf("first output after %d packet(s) plus thread delay\n",
+               first_packet - ctx->delay);
+    if (report & REPORT_FRAMES)
+        printf("%d frames, checksum %08" PRIx32 "\n", frames, checksum);
+    av_frame_free(&frame);
+    av_packet_free(&pkt);
+    avformat_close_input(&fmt);
+}
+
+static AVCodecContext *open_decoder(int threads)
+{
+    const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_H264);
+    AVCodecContext *ctx = avcodec_alloc_context3(codec);
+
+    if (!ctx)
+        exit(1);
+    ctx->thread_count = threads;
+    ctx->thread_type  = FF_THREAD_FRAME;
+    check(avcodec_open2(ctx, codec, NULL));
+    if (threads > 1 && !(ctx->active_thread_type & FF_THREAD_FRAME)) {
+        fprintf(stderr, "Could not activate frame threading\n");
+        exit(1);
+    }
+    return ctx;
+}
+
+int main(int argc, char **argv)
+{
+    AVCodecContext *ctx;
+    int threads;
+
+    if (argc != 5)
+        return 1;
+    av_log_set_level(AV_LOG_ERROR);
+
+    threads = atoi(argv[1]);
+    ctx = open_decoder(threads);
+
+    /* BA1 should output immediately after the flush. The following SPS
+     * needs the learned reorder depth to output every picture. */
+    decode(ctx, argv[2], NULL, 0, 0);
+    avcodec_flush_buffers(ctx);
+    decode(ctx, argv[3], argv[4], 0, REPORT_TIMING | REPORT_FRAMES);
+    avcodec_free_context(&ctx);
+
+    /* A one-packet BA1 prefix switches back to CAMACI3 on the next worker.
+     * Count both inputs because the prefix picture may still be queued. */
+    ctx = open_decoder(threads);
+    decode(ctx, argv[2], NULL, 0, 0);
+    avcodec_flush_buffers(ctx);
+    decode(ctx, argv[3], argv[2], 1, REPORT_FRAMES);
+    avcodec_free_context(&ctx);
+
+    /* Seek back to the active SPS before the prefix learns its depth. */
+    ctx = open_decoder(threads);
+    decode(ctx, argv[2], NULL, 0, 0);
+    avcodec_flush_buffers(ctx);
+    decode(ctx, argv[4], NULL, 8, 0);
+    avcodec_flush_buffers(ctx);
+    decode(ctx, argv[4], NULL, 0, REPORT_FRAMES);
+    avcodec_free_context(&ctx);
+    return 0;
+}
diff --git a/tests/fate/api.mak b/tests/fate/api.mak
index 69df95b90d..0ad93e749a 100644
--- a/tests/fate/api.mak
+++ b/tests/fate/api.mak
@@ -47,6 +47,13 @@ FATE_API_SAMPLES_LIBAVFORMAT-$(call DEMDEC, H264, H264, H264_PARSER) += fate-api
 fate-api-h264: $(APITESTSDIR)/api-h264-test$(EXESUF)
 fate-api-h264: CMD = run $(APITESTSDIR)/api-h264-test$(EXESUF) $(TARGET_SAMPLES)/h264-conformance/SVA_NL2_E.264

+FATE_API_SAMPLES_LIBAVFORMAT-$(call DEMDEC, H264, H264, H264_PARSER) += fate-api-h264-flush
+fate-api-h264-flush: $(APITESTSDIR)/api-h264-flush-test$(EXESUF)
+fate-api-h264-flush: CMD = run $(APITESTSDIR)/api-h264-flush-test$(EXESUF) $(if $(HAVE_THREADS),4,1) \
+                              $(TARGET_SAMPLES)/h264-conformance/CAMACI3_Sony_C.jsv \
+                              $(TARGET_SAMPLES)/h264-conformance/BA1_Sony_D.jsv \
+                              $(TARGET_SAMPLES)/h264/reference-b-reorder.h264
+
 FATE_API_SAMPLES_LIBAVFORMAT-$(call DEMDEC, H264, H264) += fate-api-h264-slice
 fate-api-h264-slice: $(APITESTSDIR)/api-h264-slice-test$(EXESUF)
 fate-api-h264-slice: CMD = run $(APITESTSDIR)/api-h264-slice-test$(EXESUF) 2 $(TARGET_SAMPLES)/h264/crew_cif.nal
diff --git a/tests/ref/fate/api-h264-flush b/tests/ref/fate/api-h264-flush
new file mode 100644
index 0000000000..892434c4c7
--- /dev/null
+++ b/tests/ref/fate/api-h264-flush
@@ -0,0 +1,4 @@
+first output after 1 packet(s) plus thread delay
+38 frames, checksum cda5b62d
+18 frames, checksum 298dea73
+21 frames, checksum b2004ca5