Commit 93452663cd for aom

commit 93452663cd783636b07b30292310d62b1e30e1a9
Author: Cheng Chen <chengchen@google.com>
Date:   Tue Dec 1 10:35:36 2026 -0800

    Buffer handling and stats leak fix

    1. Fix update_firstpass_stats() buffer handling.
    2. Remove obsolete lap_lag_in_frames
    3. Fix visible-frame stats leak on external refresh flags.

    Unit tests are added to verify the fix.

    BUG=591907115

    Change-Id: Id3a1bd534228d1cdb711393ca262f6b63c3b1ef0

diff --git a/av1/av1_cx_iface.c b/av1/av1_cx_iface.c
index 8f88441a9f..4f7be5337a 100644
--- a/av1/av1_cx_iface.c
+++ b/av1/av1_cx_iface.c
@@ -3028,8 +3028,7 @@ aom_codec_err_t av1_create_context_and_bufferpool(AV1_PRIMARY *ppi,
                                                   AV1_COMP **p_cpi,
                                                   BufferPool **p_buffer_pool,
                                                   const AV1EncoderConfig *oxcf,
-                                                  COMPRESSOR_STAGE stage,
-                                                  int lap_lag_in_frames) {
+                                                  COMPRESSOR_STAGE stage) {
   aom_codec_err_t res = AOM_CODEC_OK;
   BufferPool *buffer_pool = *p_buffer_pool;

@@ -3056,8 +3055,7 @@ aom_codec_err_t av1_create_context_and_bufferpool(AV1_PRIMARY *ppi,
 #endif
     *p_buffer_pool = buffer_pool;
   }
-  *p_cpi =
-      av1_create_compressor(ppi, oxcf, buffer_pool, stage, lap_lag_in_frames);
+  *p_cpi = av1_create_compressor(ppi, oxcf, buffer_pool, stage);
   if (*p_cpi == NULL) res = AOM_CODEC_MEM_ERROR;

   return res;
@@ -3076,7 +3074,7 @@ static aom_codec_err_t ctrl_set_fp_mt(aom_codec_alg_priv_t *ctx, va_list args) {
       for (i = 1; i < num_fp_contexts; i++) {
         int res = av1_create_context_and_bufferpool(
             ctx->ppi, &ctx->ppi->parallel_cpi[i], &ctx->buffer_pool, &ctx->oxcf,
-            ENCODE_STAGE, -1);
+            ENCODE_STAGE);
         if (res != AOM_CODEC_OK) {
           return res;
         }
@@ -3143,7 +3141,6 @@ static aom_codec_err_t encoder_init(aom_codec_ctx_t *ctx) {

     if (res == AOM_CODEC_OK) {
       int *num_lap_buffers = &priv->num_lap_buffers;
-      int lap_lag_in_frames = 0;
       *num_lap_buffers = 0;
       priv->timestamp_ratio.den = priv->cfg.g_timebase.den;
       priv->timestamp_ratio.num =
@@ -3165,10 +3162,6 @@ static aom_codec_err_t encoder_init(aom_codec_ctx_t *ctx) {
             AOMMIN(lag_in_frames,
                    AOMMIN(MAX_LAP_BUFFERS, priv->oxcf.kf_cfg.key_freq_max +
                                                SCENE_CUT_KEY_TEST_INTERVAL));
-        if ((int)priv->cfg.g_lag_in_frames - (*num_lap_buffers) >=
-            LAP_LAG_IN_FRAMES) {
-          lap_lag_in_frames = LAP_LAG_IN_FRAMES;
-        }
       }
       priv->oxcf.use_highbitdepth =
           (ctx->init_flags & AOM_CODEC_USE_HIGHBITDEPTH) ? 1 : 0;
@@ -3195,7 +3188,7 @@ static aom_codec_err_t encoder_init(aom_codec_ctx_t *ctx) {
       assert(priv->ppi->num_fp_contexts >= 1);
       res = av1_create_context_and_bufferpool(
           priv->ppi, &priv->ppi->parallel_cpi[0], &priv->buffer_pool,
-          &priv->oxcf, ENCODE_STAGE, -1);
+          &priv->oxcf, ENCODE_STAGE);
       if (res != AOM_CODEC_OK) {
         priv->base.err_detail = "av1_create_context_and_bufferpool() failed";
         return res;
@@ -3208,9 +3201,9 @@ static aom_codec_err_t encoder_init(aom_codec_ctx_t *ctx) {

       // Create another compressor if look ahead is enabled
       if (res == AOM_CODEC_OK && *num_lap_buffers) {
-        res = av1_create_context_and_bufferpool(
-            priv->ppi, &priv->ppi->cpi_lap, &priv->buffer_pool_lap, &priv->oxcf,
-            LAP_STAGE, clamp(lap_lag_in_frames, 0, MAX_LAG_BUFFERS));
+        res = av1_create_context_and_bufferpool(priv->ppi, &priv->ppi->cpi_lap,
+                                                &priv->buffer_pool_lap,
+                                                &priv->oxcf, LAP_STAGE);
       }
     }
   }
diff --git a/av1/av1_cx_iface.h b/av1/av1_cx_iface.h
index 92baf20d2c..dcb57eb6ae 100644
--- a/av1/av1_cx_iface.h
+++ b/av1/av1_cx_iface.h
@@ -24,8 +24,7 @@ aom_codec_err_t av1_create_context_and_bufferpool(AV1_PRIMARY *ppi,
                                                   AV1_COMP **p_cpi,
                                                   BufferPool **p_buffer_pool,
                                                   const AV1EncoderConfig *oxcf,
-                                                  COMPRESSOR_STAGE stage,
-                                                  int lap_lag_in_frames);
+                                                  COMPRESSOR_STAGE stage);

 void av1_destroy_context_and_bufferpool(AV1_COMP *cpi,
                                         BufferPool **p_buffer_pool);
diff --git a/av1/encoder/encoder.c b/av1/encoder/encoder.c
index 91782344d6..b210ff68a1 100644
--- a/av1/encoder/encoder.c
+++ b/av1/encoder/encoder.c
@@ -909,15 +909,12 @@ void av1_change_config(struct AV1_COMP *cpi, const AV1EncoderConfig *oxcf,
   FeatureFlags *const features = &cm->features;
   const int is_highbitdepth = seq_params->use_highbitdepth;

-  // in case of LAP, lag in frames is set according to number of lap buffers
-  // calculated at init time. This stores and restores LAP's lag in frames to
-  // prevent override by new cfg.
-  int lap_lag_in_frames = -1;
-  if (cpi->ppi->lap_enabled && cpi->compressor_stage == LAP_STAGE) {
-    lap_lag_in_frames = cpi->oxcf.gf_cfg.lag_in_frames;
-  }
-
   cpi->oxcf = *oxcf;
+  if (cpi->compressor_stage == LAP_STAGE) {
+    // LAP_STAGE generates firstpass stats frame by frame without lookahead lag
+    // of its own; num_lap_buffers provides the lookahead for ENCODE_STAGE.
+    cpi->oxcf.gf_cfg.lag_in_frames = 0;
+  }

 #if !CONFIG_REALTIME_ONLY
   av1_update_film_grain_parameters(cpi, oxcf);
@@ -1147,11 +1144,6 @@ void av1_change_config(struct AV1_COMP *cpi, const AV1EncoderConfig *oxcf,

   check_reset_rc_flag(cpi);

-  // restore the value of lag_in_frame for LAP stage.
-  if (lap_lag_in_frames != -1) {
-    cpi->oxcf.gf_cfg.lag_in_frames = lap_lag_in_frames;
-  }
-
 #if CONFIG_REALTIME_ONLY
   assert(!oxcf->tool_cfg.enable_global_motion);
   cpi->alloc_pyramid = false;
@@ -1530,8 +1522,8 @@ AV1_PRIMARY *av1_create_primary_compressor(
 }

 AV1_COMP *av1_create_compressor(AV1_PRIMARY *ppi, const AV1EncoderConfig *oxcf,
-                                BufferPool *const pool, COMPRESSOR_STAGE stage,
-                                int lap_lag_in_frames) {
+                                BufferPool *const pool,
+                                COMPRESSOR_STAGE stage) {
   AV1_COMP *volatile const cpi = aom_memalign(32, sizeof(AV1_COMP));

   if (!cpi) return NULL;
@@ -1584,9 +1576,6 @@ AV1_COMP *av1_create_compressor(AV1_PRIMARY *ppi, const AV1EncoderConfig *oxcf,
   cpi->common.buffer_pool = pool;

   init_config(cpi, oxcf);
-  if (cpi->compressor_stage == LAP_STAGE) {
-    cpi->oxcf.gf_cfg.lag_in_frames = lap_lag_in_frames;
-  }

   RATE_CONTROL *const rc = &cpi->rc;
   av1_rc_init(&cpi->oxcf, rc);
diff --git a/av1/encoder/encoder.h b/av1/encoder/encoder.h
index 36c75e0cb7..9d4f7c0572 100644
--- a/av1/encoder/encoder.h
+++ b/av1/encoder/encoder.h
@@ -3894,8 +3894,7 @@ void av1_initialize_enc(unsigned int usage, enum aom_rc_mode end_usage);
 struct AV1_COMP *av1_create_compressor(struct AV1_PRIMARY *ppi,
                                        const AV1EncoderConfig *oxcf,
                                        struct BufferPool *const pool,
-                                       COMPRESSOR_STAGE stage,
-                                       int lap_lag_in_frames);
+                                       COMPRESSOR_STAGE stage);

 struct AV1_PRIMARY *av1_create_primary_compressor(
     struct aom_codec_pkt_list *pkt_list_head, int num_lap_buffers,
diff --git a/av1/encoder/firstpass.c b/av1/encoder/firstpass.c
index bbd5b2d796..093ae234ab 100644
--- a/av1/encoder/firstpass.c
+++ b/av1/encoder/firstpass.c
@@ -922,9 +922,10 @@ static void update_firstpass_stats(AV1_COMP *cpi,
                                    const int64_t ts_duration,
                                    const BLOCK_SIZE fp_block_size) {
   TWO_PASS *twopass = &cpi->ppi->twopass;
+  STATS_BUFFER_CTX *const stats_buf_ctx = twopass->stats_buf_ctx;
   AV1_COMMON *const cm = &cpi->common;
   const CommonModeInfoParams *const mi_params = &cm->mi_params;
-  FIRSTPASS_STATS *this_frame_stats = twopass->stats_buf_ctx->stats_in_end;
+  FIRSTPASS_STATS *this_frame_stats = stats_buf_ctx->stats_in_end;
   FIRSTPASS_STATS fps;
   // The minimum error here insures some bit allocation to frames even
   // in static regions. The allocation per MB declines for larger formats
@@ -1004,30 +1005,29 @@ static void update_firstpass_stats(AV1_COMP *cpi,
   if (cpi->ppi->twopass.stats_buf_ctx->total_stats != NULL) {
     av1_accumulate_stats(cpi->ppi->twopass.stats_buf_ctx->total_stats, &fps);
   }
-  twopass->stats_buf_ctx->stats_in_end++;
+  stats_buf_ctx->stats_in_end++;
   // When ducky encode is on, we always use linear buffer for stats_buf_ctx.
   if (cpi->use_ducky_encode == 0) {
     // TODO(angiebird): Figure out why first pass uses circular buffer.
     /* In the case of two pass, first pass uses it as a circular buffer,
      * when LAP is enabled it is used as a linear buffer*/
     if ((cpi->oxcf.pass == AOM_RC_FIRST_PASS) &&
-        (twopass->stats_buf_ctx->stats_in_end >=
-         twopass->stats_buf_ctx->stats_in_buf_end)) {
-      twopass->stats_buf_ctx->stats_in_end =
-          twopass->stats_buf_ctx->stats_in_start;
-    } else if (cpi->ppi->lap_enabled &&
-               (twopass->stats_buf_ctx->stats_in_end >=
-                twopass->stats_buf_ctx->stats_in_buf_end)) {
-      const int num_valid = (int)(twopass->stats_buf_ctx->stats_in_end -
-                                  cpi->twopass_frame.stats_in);
-      if (num_valid > 0) {
-        memmove(twopass->stats_buf_ctx->stats_in_start,
-                cpi->twopass_frame.stats_in,
-                num_valid * sizeof(FIRSTPASS_STATS));
+        (stats_buf_ctx->stats_in_end >= stats_buf_ctx->stats_in_buf_end)) {
+      stats_buf_ctx->stats_in_end = stats_buf_ctx->stats_in_start;
+    } else if (cpi->ppi->lap_enabled && (stats_buf_ctx->stats_in_end >=
+                                         stats_buf_ctx->stats_in_buf_end)) {
+      // Shift out the oldest stats entry so stats_in_end remains strictly
+      // before stats_in_buf_end, while preserving the last slot for callers
+      // that read this_frame_stats.
+      const int buf_size = (int)(stats_buf_ctx->stats_in_buf_end -
+                                 stats_buf_ctx->stats_in_start);
+      assert(buf_size > 0);
+      if (buf_size > 1) {
+        memmove(stats_buf_ctx->stats_in_start,
+                stats_buf_ctx->stats_in_start + 1,
+                (size_t)(buf_size - 1) * sizeof(FIRSTPASS_STATS));
       }
-      cpi->twopass_frame.stats_in = twopass->stats_buf_ctx->stats_in_start;
-      twopass->stats_buf_ctx->stats_in_end =
-          twopass->stats_buf_ctx->stats_in_start + num_valid;
+      stats_buf_ctx->stats_in_end = stats_buf_ctx->stats_in_buf_end - 1;
     }
   }
 }
diff --git a/av1/encoder/lookahead.h b/av1/encoder/lookahead.h
index f6a3224f5e..31dcc84746 100644
--- a/av1/encoder/lookahead.h
+++ b/av1/encoder/lookahead.h
@@ -28,7 +28,6 @@ extern "C" {
 #define MAX_LAG_BUFFERS 48
 #define MAX_LAP_BUFFERS 48
 #define MAX_TOTAL_BUFFERS (MAX_LAG_BUFFERS + MAX_LAP_BUFFERS)
-#define LAP_LAG_IN_FRAMES 17

 struct lookahead_entry {
   YV12_BUFFER_CONFIG img;
diff --git a/av1/encoder/pass2_strategy.c b/av1/encoder/pass2_strategy.c
index a28ce8eb02..b3a7ccf432 100644
--- a/av1/encoder/pass2_strategy.c
+++ b/av1/encoder/pass2_strategy.c
@@ -4462,8 +4462,7 @@ void av1_twopass_postencode_update(AV1_COMP *cpi) {
                                      DUCKY_ENCODE_GOP_MODE_RCL) &&
       (cpi->gf_frame_index < cpi->ppi->gf_group.size ||
        rc->frames_to_key == 0)) {
-    const int update_type = cpi->ppi->gf_group.update_type[cpi->gf_frame_index];
-    if (update_type != ARF_UPDATE && update_type != INTNL_ARF_UPDATE) {
+    if (cpi->common.show_frame) {
       FIRSTPASS_STATS this_frame;
       assert(cpi->twopass_frame.stats_in >
              twopass->stats_buf_ctx->stats_in_start);
diff --git a/test/encode_api_test.cc b/test/encode_api_test.cc
index 5ce821287e..85a055c64a 100644
--- a/test/encode_api_test.cc
+++ b/test/encode_api_test.cc
@@ -7246,6 +7246,140 @@ TEST(EncodeAPI, ScreenContentForceIntegerMvTemporalFilter) {
   EXPECT_EQ(encoded_frames, kFrames);
   ASSERT_EQ(aom_codec_destroy(enc.release()), AOM_CODEC_OK);
 }
-#endif  // !CONFIG_REALTIME_ONLY

+// Regression test for b/591907115: one-pass good-quality encoding with small
+// kf_max_dist and large g_lag_in_frames used to trigger the LAP stats buffer
+// full path in update_firstpass_stats(), which subtracted the LAP stage's NULL
+// twopass_frame.stats_in pointer and either segfaulted or returned
+// AOM_CODEC_MEM_ERROR.
+TEST(EncodeAPI, LapStatsBufferFull) {
+  struct Config {
+    unsigned int kf_max_dist;
+    unsigned int lag_in_frames;  // 0 means keep default (35).
+    int num_frames;
+    int speed;  // -1 means keep default.
+  };
+  const Config configs[] = {
+    { /*kf_max_dist=*/0, /*lag_in_frames=*/0, /*num_frames=*/40, /*speed=*/-1 },
+    { /*kf_max_dist=*/1, /*lag_in_frames=*/0, /*num_frames=*/40, /*speed=*/6 },
+    { /*kf_max_dist=*/2, /*lag_in_frames=*/0, /*num_frames=*/40, /*speed=*/6 },
+    { /*kf_max_dist=*/15, /*lag_in_frames=*/48, /*num_frames=*/55,
+      /*speed=*/6 },
+  };
+
+  for (const auto &c : configs) {
+    SCOPED_TRACE(testing::Message() << "kf_max_dist=" << c.kf_max_dist
+                                    << " lag_in_frames=" << c.lag_in_frames);
+    aom_codec_iface_t *iface = aom_codec_av1_cx();
+    aom_codec_enc_cfg_t cfg;
+    ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_GOOD_QUALITY),
+              AOM_CODEC_OK);
+    cfg.g_w = 64;
+    cfg.g_h = 64;
+    cfg.kf_max_dist = c.kf_max_dist;
+    if (c.lag_in_frames > 0) {
+      cfg.g_lag_in_frames = c.lag_in_frames;
+    }
+
+    aom_codec_ctx_t enc;
+    ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+    if (c.speed >= 0) {
+      ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, c.speed),
+                AOM_CODEC_OK);
+    }
+
+    aom_image_t *image =
+        aom_img_alloc(nullptr, AOM_IMG_FMT_I420, cfg.g_w, cfg.g_h, 1);
+    ASSERT_NE(image, nullptr);
+    FillImage(image, 128);
+
+    int frames_out = 0;
+    auto drain_packets = [&]() {
+      aom_codec_iter_t iter = nullptr;
+      const aom_codec_cx_pkt_t *pkt;
+      while ((pkt = aom_codec_get_cx_data(&enc, &iter)) != nullptr) {
+        if (pkt->kind == AOM_CODEC_CX_FRAME_PKT) {
+          ++frames_out;
+        }
+      }
+    };
+
+    for (int i = 0; i < c.num_frames; ++i) {
+      SCOPED_TRACE(i);
+      ASSERT_EQ(aom_codec_encode(&enc, image, i, 1, 0), AOM_CODEC_OK)
+          << aom_codec_error_detail(&enc);
+      drain_packets();
+    }
+
+    // Flush remaining frames.
+    for (;;) {
+      ASSERT_EQ(aom_codec_encode(&enc, nullptr, 0, 1, 0), AOM_CODEC_OK)
+          << aom_codec_error_detail(&enc);
+      const int prev = frames_out;
+      drain_packets();
+      if (frames_out == prev) break;
+    }
+    EXPECT_EQ(frames_out, c.num_frames);
+
+    aom_img_free(image);
+    ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  }
+}
+
+// External refresh flags (AOM_EFLAG_NO_UPD_LAST | AOM_EFLAG_NO_UPD_GF)
+// overwrite gf_group->update_type on visible frames. In LAP mode,
+// av1_twopass_postencode_update() must still consume the frame's first-pass
+// stats entry so repeated frames do not leak and overflow the stats buffer.
+TEST(EncodeAPI, LapNoUpdateFlagsStatsLeak) {
+  aom_codec_iface_t *iface = aom_codec_av1_cx();
+  aom_codec_enc_cfg_t cfg;
+  ASSERT_EQ(aom_codec_enc_config_default(iface, &cfg, AOM_USAGE_GOOD_QUALITY),
+            AOM_CODEC_OK);
+  cfg.g_w = 64;
+  cfg.g_h = 64;
+  cfg.g_lag_in_frames = 1;
+  cfg.g_error_resilient = 0;
+
+  aom_codec_ctx_t enc;
+  ASSERT_EQ(aom_codec_enc_init(&enc, iface, &cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CPUUSED, 6), AOM_CODEC_OK);
+
+  aom_image_t *image =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, cfg.g_w, cfg.g_h, 1);
+  ASSERT_NE(image, nullptr);
+  FillImage(image, 128);
+
+  constexpr int kNumFrames = 25;
+  int frames_out = 0;
+  auto drain_packets = [&]() {
+    aom_codec_iter_t iter = nullptr;
+    const aom_codec_cx_pkt_t *pkt;
+    while ((pkt = aom_codec_get_cx_data(&enc, &iter)) != nullptr) {
+      if (pkt->kind == AOM_CODEC_CX_FRAME_PKT) {
+        ++frames_out;
+      }
+    }
+  };
+
+  for (int i = 0; i < kNumFrames; ++i) {
+    SCOPED_TRACE(i);
+    const aom_enc_frame_flags_t flags =
+        (i == 0) ? 0 : (AOM_EFLAG_NO_UPD_LAST | AOM_EFLAG_NO_UPD_GF);
+    ASSERT_EQ(aom_codec_encode(&enc, image, i, 1, flags), AOM_CODEC_OK)
+        << aom_codec_error_detail(&enc);
+    drain_packets();
+  }
+  for (;;) {
+    ASSERT_EQ(aom_codec_encode(&enc, nullptr, 0, 1, 0), AOM_CODEC_OK)
+        << aom_codec_error_detail(&enc);
+    const int prev = frames_out;
+    drain_packets();
+    if (frames_out == prev) break;
+  }
+  EXPECT_EQ(frames_out, kNumFrames);
+
+  aom_img_free(image);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+#endif  // !CONFIG_REALTIME_ONLY
 }  // namespace