Commit 65552c1f17 for aom

commit 65552c1f172aa0e53b1f41d7e1ceb7e5ae8f855c
Author: Alejandro Pacheco <alepacheco99@gmail.com>
Date:   Wed Oct 14 11:22:45 2026 +0200

    firstpass, tpl: address each ref by its own stride

    The frame border, and so the stride, can change mid-stream:
    turning resize mode off with aom_codec_enc_config_set() shrinks
    the border of new frames while reference frames coded before the
    change keep the old one.

    The first pass located the block in LAST, LAST2, and GOLDEN with
    the current frame's offset and left LAST with the prior ref's
    stride on subsequent blocks, reading past the reference buffer.
    Set up each reference with av1_setup_pre_planes() before
    searching, and leave pre[0] unchanged before
    av1_enc_build_inter_predictor() so normal encodes stay bit-exact
    while buf, buf0, and stride match the same buffer.

    TPL assumes unscaled references matching the current frame size:
    - Skip references in init_gop_frames_for_tpl() whose dimensions
      differ from cm->width x cm->height so resized references cannot
      be read out of bounds after resize mode changes.
    - Use av1_get_search_site_config() in motion_estimation() so
      same-size references whose border/stride matches neither
      SS_CFG_SRC nor SS_CFG_LOOKAHEAD still get a valid search site
      config.

    TAG=agy
    CONV=74ece8ab-3f39-4cda-9df8-8325c945d9d9

    Bug: 573427857
    Change-Id: If1dcb9fc0a42be9acee161e42927f47f2f142a41

diff --git a/av1/encoder/firstpass.c b/av1/encoder/firstpass.c
index 093ae234ab..847ebb90ca 100644
--- a/av1/encoder/firstpass.c
+++ b/av1/encoder/firstpass.c
@@ -694,11 +694,6 @@ static void accumulate_mv_stats(const MV best_mv, const FULLPEL_MV mv,
 //   golden_frame: the frame buffer of the golden frame.
 //   unit_row: row index in the unit of first pass block size.
 //   unit_col: column index in the unit of first pass block size.
-//   recon_yoffset: the y offset of the reconstructed frame buffer,
-//                  indicating the starting point of the current block.
-//   recon_uvoffset: the u/v offset of the reconstructed frame buffer,
-//                   indicating the starting point of the current block.
-//   src_yoffset: the y offset of the source frame buffer.
 //   fp_block_size: first pass block size.
 //   this_intra_error: the intra prediction error of this block.
 //   raw_motion_err_counts: the count of raw motion vectors.
@@ -718,8 +713,7 @@ static int firstpass_inter_prediction(
     AV1_COMP *cpi, ThreadData *td, const YV12_BUFFER_CONFIG *const last_frame,
     const YV12_BUFFER_CONFIG *const golden_frame,
     const YV12_BUFFER_CONFIG *const last2_frame, const int unit_row,
-    const int unit_col, const int recon_yoffset, const int recon_uvoffset,
-    const int src_yoffset, const BLOCK_SIZE fp_block_size,
+    const int unit_col, const BLOCK_SIZE fp_block_size,
     const int this_intra_error, const int raw_motion_err_counts,
     int *raw_motion_err_list, const MV ref_mv, MV *best_mv,
     MV *last_non_zero_mv, FRAME_STATS *stats) {
@@ -738,9 +732,14 @@ static int firstpass_inter_prediction(
   const int unit_width = mi_size_wide[fp_block_size];
   const int unit_rows = get_unit_rows(fp_block_size, mi_params->mb_rows);
   const int unit_cols = get_unit_cols(fp_block_size, mi_params->mb_cols);
+  // The reference buffers may have a different border, and so a different
+  // stride, from the current frame (e.g. after the border size changed
+  // mid-stream), so locate the block in each of them from its own layout.
+  const int mi_row = unit_row * unit_scale;
+  const int mi_col = unit_col * unit_scale;
   // Assume 0,0 motion with no mv overhead.
   FULLPEL_MV mv = kZeroFullMv;
-  xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
+  av1_setup_pre_planes(xd, 0, last_frame, mi_row, mi_col, NULL, 1);
   // Set up limit values for motion vectors to prevent them extending
   // outside the UMV borders.
   av1_set_mv_col_limits(mi_params, &x->mv_limits, unit_col * unit_width,
@@ -757,9 +756,11 @@ static int firstpass_inter_prediction(
   // TODO(chiyotsai): The unscaled last source might be different dimension
   // as the current source. See BUG=aomedia:3413
   struct buf_2d unscaled_last_source_buf_2d;
-  unscaled_last_source_buf_2d.buf =
-      cpi->unscaled_last_source->y_buffer + src_yoffset;
   unscaled_last_source_buf_2d.stride = cpi->unscaled_last_source->y_stride;
+  unscaled_last_source_buf_2d.buf =
+      cpi->unscaled_last_source->y_buffer +
+      (ptrdiff_t)mi_row * MI_SIZE * unscaled_last_source_buf_2d.stride +
+      mi_col * MI_SIZE;
   const int raw_motion_error = get_prediction_error_bitdepth(
       is_high_bitdepth, bitdepth, bsize, &x->plane[0].src,
       &unscaled_last_source_buf_2d);
@@ -789,8 +790,7 @@ static int firstpass_inter_prediction(
   if ((current_frame->frame_number > 2) && last2_frame != NULL) {
     FULLPEL_MV tmp_mv = kZeroFullMv;
     // Assume 0,0 motion with no mv overhead.
-    av1_setup_pre_planes(xd, 0, last2_frame, 0, 0, NULL, 1);
-    xd->plane[0].pre[0].buf += recon_yoffset;
+    av1_setup_pre_planes(xd, 0, last2_frame, mi_row, mi_col, NULL, 1);
     last2_motion_error =
         get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
                                       &x->plane[0].src, &xd->plane[0].pre[0]);
@@ -803,8 +803,7 @@ static int firstpass_inter_prediction(
   if ((current_frame->frame_number > 1) && golden_frame != NULL) {
     FULLPEL_MV tmp_mv = kZeroFullMv;
     // Assume 0,0 motion with no mv overhead.
-    av1_setup_pre_planes(xd, 0, golden_frame, 0, 0, NULL, 1);
-    xd->plane[0].pre[0].buf += recon_yoffset;
+    av1_setup_pre_planes(xd, 0, golden_frame, mi_row, mi_col, NULL, 1);
     gf_motion_error =
         get_prediction_error_bitdepth(is_high_bitdepth, bitdepth, bsize,
                                       &x->plane[0].src, &xd->plane[0].pre[0]);
@@ -825,12 +824,11 @@ static int firstpass_inter_prediction(
     stats->sr_coded_error += motion_error;
   }

-  // Reset to last frame as reference buffer.
-  xd->plane[0].pre[0].buf = last_frame->y_buffer + recon_yoffset;
-  if (av1_num_planes(&cpi->common) > 1) {
-    xd->plane[1].pre[0].buf = last_frame->u_buffer + recon_uvoffset;
-    xd->plane[2].pre[0].buf = last_frame->v_buffer + recon_uvoffset;
-  }
+  // TODO(aomedia): Building the LAST_FRAME reconstruction below uses whichever
+  // reference was last set up above (golden_frame/last2_frame when present,
+  // else last_frame). Keep this pre-existing behavior to stay bit-exact while
+  // ensuring buf, buf0, and stride match the same buffer. The next block resets
+  // pre[0] to last_frame at entry via av1_setup_pre_planes().

   // Start by assuming that intra mode is best.
   *best_mv = kZeroMv;
@@ -859,8 +857,7 @@ static int firstpass_inter_prediction(
     xd->mi[0]->ref_frame[1] = NONE_FRAME;

     if (fp_sf->disable_recon == 0) {
-      av1_enc_build_inter_predictor(cm, xd, unit_row * unit_scale,
-                                    unit_col * unit_scale, NULL, bsize,
+      av1_enc_build_inter_predictor(cm, xd, mi_row, mi_col, NULL, bsize,
                                     AOM_PLANE_Y, AOM_PLANE_Y);
       av1_encode_sby_pass1(cpi, x, bsize);
     }
@@ -1220,7 +1217,6 @@ void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
     x->plane[i].dqcoeff = ctx->dqcoeff[i];
   }

-  const int src_y_stride = cpi->source->y_stride;
   const int recon_y_stride = this_frame->y_stride;
   const int recon_uv_stride = this_frame->uv_stride;
   const int uv_mb_width =
@@ -1235,8 +1231,6 @@ void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
   xd->up_available = (unit_row_in_tile != 0);
   int recon_yoffset = (unit_row * recon_y_stride * fp_block_size_height) +
                       (unit_col_start * fp_block_size_width);
-  int src_yoffset = (unit_row * src_y_stride * fp_block_size_height) +
-                    (unit_col_start * fp_block_size_width);
   int recon_uvoffset = (unit_row * recon_uv_stride * uv_mb_height) +
                        (unit_col_start * uv_mb_width);

@@ -1279,9 +1273,8 @@ void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
     if (!frame_is_intra_only(cm)) {
       const int this_inter_error = firstpass_inter_prediction(
           cpi, td, last_frame, golden_frame, last2_frame, unit_row, unit_col,
-          recon_yoffset, recon_uvoffset, src_yoffset, fp_block_size,
-          this_intra_error, raw_motion_err_counts, raw_motion_err_list,
-          best_ref_mv, &best_ref_mv, &last_mv, mb_stats);
+          fp_block_size, this_intra_error, raw_motion_err_counts,
+          raw_motion_err_list, best_ref_mv, &best_ref_mv, &last_mv, mb_stats);
       if (unit_col_in_tile == 0) {
         *first_top_mv = last_mv;
       }
@@ -1301,7 +1294,6 @@ void av1_first_pass_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data,
     }

     recon_yoffset += fp_block_size_width;
-    src_yoffset += fp_block_size_width;
     recon_uvoffset += uv_mb_width;
     mb_stats++;

diff --git a/av1/encoder/tpl_model.c b/av1/encoder/tpl_model.c
index c3715ba55e..7514cd1649 100644
--- a/av1/encoder/tpl_model.c
+++ b/av1/encoder/tpl_model.c
@@ -308,11 +308,11 @@ static uint32_t motion_estimation(AV1_COMP *cpi, MACROBLOCK *x,
   step_param = tpl_sf->reduce_first_step_size;
   step_param = AOMMIN(step_param, MAX_MVSEARCH_STEPS - 2);

+  // The reference may be a reconstructed frame whose stride matches neither
+  // the source nor the lookahead buffers, e.g. after the frame border size
+  // changed mid-stream.
   const search_site_config *search_site_cfg =
-      cpi->mv_search_params.search_site_cfg[SS_CFG_SRC];
-  if (search_site_cfg->stride != ref_stride)
-    search_site_cfg = cpi->mv_search_params.search_site_cfg[SS_CFG_LOOKAHEAD];
-  assert(search_site_cfg->stride == ref_stride);
+      av1_get_search_site_config(cpi, x, tpl_sf->search_method);

   FULLPEL_MOTION_SEARCH_PARAMS full_ms_params;
   av1_make_default_fullpel_ms_params(&full_ms_params, cpi, x, bsize, &center_mv,
@@ -1708,18 +1708,29 @@ static inline int init_gop_frames_for_tpl(
       tpl_data->tpl_frame[-i - 1].rec_picture = NULL;
       tpl_data->tpl_frame[-i - 1].frame_display_index = 0;
     } else {
-      if (cm->ref_frame_map[i]->display_order_hint ==
-          tpl_data->prev_gop_arf_disp_order) {
-        tpl_data->tpl_frame[-i - 1].gf_picture = &tpl_data->prev_gop_arf_src;
-        tpl_data->tpl_frame[-i - 1].rec_picture =
-            &tpl_data->prev_gop_arf_tpl_recon;
-        has_prev_arf = 1;
+      const YV12_BUFFER_CONFIG *gf_picture = &cm->ref_frame_map[i]->buf;
+      YV12_BUFFER_CONFIG *rec_picture = &cm->ref_frame_map[i]->buf;
+      const bool is_prev_arf = cm->ref_frame_map[i]->display_order_hint ==
+                               tpl_data->prev_gop_arf_disp_order;
+      if (is_prev_arf) {
+        gf_picture = &tpl_data->prev_gop_arf_src;
+        rec_picture = &tpl_data->prev_gop_arf_tpl_recon;
+      }
+      // TPL assumes unscaled references matching the current frame dimensions.
+      if (gf_picture->y_crop_width == cm->width &&
+          gf_picture->y_crop_height == cm->height &&
+          rec_picture->y_crop_width == cm->width &&
+          rec_picture->y_crop_height == cm->height) {
+        tpl_data->tpl_frame[-i - 1].gf_picture = gf_picture;
+        tpl_data->tpl_frame[-i - 1].rec_picture = rec_picture;
+        tpl_data->tpl_frame[-i - 1].frame_display_index =
+            cm->ref_frame_map[i]->display_order_hint;
+        if (is_prev_arf) has_prev_arf = 1;
       } else {
-        tpl_data->tpl_frame[-i - 1].gf_picture = &cm->ref_frame_map[i]->buf;
-        tpl_data->tpl_frame[-i - 1].rec_picture = &cm->ref_frame_map[i]->buf;
+        tpl_data->tpl_frame[-i - 1].gf_picture = NULL;
+        tpl_data->tpl_frame[-i - 1].rec_picture = NULL;
+        tpl_data->tpl_frame[-i - 1].frame_display_index = 0;
       }
-      tpl_data->tpl_frame[-i - 1].frame_display_index =
-          cm->ref_frame_map[i]->display_order_hint;
     }

     ref_picture_map[i] = -i - 1;
diff --git a/test/encode_api_test.cc b/test/encode_api_test.cc
index 89fea87a34..e17eed248e 100644
--- a/test/encode_api_test.cc
+++ b/test/encode_api_test.cc
@@ -3969,6 +3969,102 @@ TEST(EncodeAPI, Buganizer504317456) {
   aom_img_free(img);
   ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
 }
+
+// Turning resize mode off mid-stream shrinks the frame border, so the new
+// frames have a smaller stride than the reference frames coded before the
+// change. The first pass (LAP) must use each reference frame's own stride, and
+// TPL must skip references whose dimensions differ from the current frame and
+// handle same-size references whose border/stride changed mid-stream.
+TEST(EncodeAPI, ResizeModeOffMidStreamChangesBorder) {
+  auto run_resize_case = [](unsigned int width, unsigned int height,
+                            int cpu_used, unsigned int lag_in_frames,
+                            int num_frames, unsigned int init_resize_mode,
+                            int toggle_on_frame, int toggle_off_frame) {
+    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 = width;
+    cfg.g_h = height;
+    cfg.g_lag_in_frames = lag_in_frames;
+    cfg.g_threads = 1;
+    cfg.rc_end_usage = AOM_Q;
+    cfg.rc_resize_mode = init_resize_mode;
+    if (init_resize_mode != 0) {
+      cfg.rc_resize_denominator = 16;
+      cfg.rc_resize_kf_denominator = 16;
+    }
+    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, cpu_used),
+              AOM_CODEC_OK);
+    ASSERT_EQ(aom_codec_control(&enc, AOME_SET_CQ_LEVEL, 40), AOM_CODEC_OK);
+
+    std::vector<unsigned char> buf(cfg.g_w * cfg.g_h * 3 / 2);
+    aom_image_t img;
+    ASSERT_EQ(&img, aom_img_wrap(&img, AOM_IMG_FMT_I420, cfg.g_w, cfg.g_h, 1,
+                                 buf.data()));
+    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 f = 0; f < num_frames; ++f) {
+      aom_enc_frame_flags_t flags = 0;
+      if (f == toggle_on_frame) {
+        cfg.rc_resize_mode = 1;  // RESIZE_FIXED
+        cfg.rc_resize_denominator = 16;
+        cfg.rc_resize_kf_denominator = 8;
+        ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+        flags = AOM_EFLAG_FORCE_KF;
+      } else if (f == toggle_off_frame) {
+        cfg.rc_resize_mode = 0;  // RESIZE_NONE
+        ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+      }
+      // A moving pattern, so that the motion searches look around.
+      for (unsigned int y = 0; y < cfg.g_h; ++y) {
+        for (unsigned int x = 0; x < cfg.g_w; ++x) {
+          buf[y * cfg.g_w + x] =
+              static_cast<unsigned char>(((x + 2 * f) * 7) ^ ((y + f) * 13));
+        }
+      }
+      memset(buf.data() + cfg.g_w * cfg.g_h, 128,
+             buf.size() - cfg.g_w * cfg.g_h);
+      ASSERT_EQ(aom_codec_encode(&enc, &img, f, 1, flags), AOM_CODEC_OK);
+      drain_packets();
+    }
+    for (;;) {
+      ASSERT_EQ(aom_codec_encode(&enc, nullptr, 0, 0, 0), AOM_CODEC_OK);
+      const int prev = frames_out;
+      drain_packets();
+      if (frames_out == prev) break;
+    }
+    EXPECT_EQ(frames_out, num_frames);
+    ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+  };
+
+  // 1. Turning resize off mid-stream: tests first-pass per-ref stride handling.
+  run_resize_case(/*width=*/128, /*height=*/96, /*cpu_used=*/6,
+                  /*lag_in_frames=*/19, /*num_frames=*/45,
+                  /*init_resize_mode=*/1, /*toggle_on_frame=*/-1,
+                  /*toggle_off_frame=*/22);
+  // 2. Tall frame turning resize off: exercises TPL skipping half-resolution
+  // references where y_height + border < cm->height.
+  run_resize_case(/*width=*/16, /*height=*/2400, /*cpu_used=*/6,
+                  /*lag_in_frames=*/6, /*num_frames=*/20,
+                  /*init_resize_mode=*/1, /*toggle_on_frame=*/-1,
+                  /*toggle_off_frame=*/8);
+  // 3. Same-size border toggle (0 -> 1 with full-res KF -> 0): exercises TPL
+  // av1_get_search_site_config() when a same-size ref's stride matches neither
+  // SS_CFG_SRC nor SS_CFG_LOOKAHEAD.
+  run_resize_case(/*width=*/64, /*height=*/64, /*cpu_used=*/6,
+                  /*lag_in_frames=*/6, /*num_frames=*/24,
+                  /*init_resize_mode=*/0, /*toggle_on_frame=*/8,
+                  /*toggle_off_frame=*/16);
+}
 #endif  // !CONFIG_REALTIME_ONLY

 // With internal resizing the reference frames are smaller than the configured