rtc: Track cyclic_refresh->map capacity on resize

In `av1_change_config()`, `realloc_segmentation_maps()` only runs when
the frame grows beyond `data_alloc_width`/`data_alloc_height` (or
superblock size changes), while the separate resize block freed and
shrunk `cpi->cyclic_refresh->map` and spatial-layer `lc->map` whenever
`aq_mode == CYCLIC_REFRESH_AQ`. Downscaling with `CYCLIC_REFRESH_AQ`,
disabling AQ, upscaling back within
`data_alloc_width`/`data_alloc_height`, and re-enabling
`CYCLIC_REFRESH_AQ` left `cyclic_refresh->map` undersized, causing
heap-buffer-overflow accesses in `cyclic_refresh_update_map()`.

Spatial SVC layer maps (`lc->map`) had the same issue and were never
grown when upscaling beyond initial dimensions while
`aq_mode != CYCLIC_REFRESH_AQ`, so a subsequent keyframe could swap an
undersized `lc->map` into `cpi->cyclic_refresh->map`.

Track the allocated capacity (`map_size`) on `CYCLIC_REFRESH` and
`LAYER_CONTEXT`:

- Add `get_cyclic_refresh_map_size()` and shared grow-or-clear helper
  `ensure_cyclic_refresh_map_size()` in `encoder_alloc.h` (respecting
  `frm_dim_cfg`, `data_alloc_width`/`height`, and
  `forced_max_frame_width`/`height`).
- In `av1_change_config()`, grow or clear `cpi->cyclic_refresh->map`
  and reset counters in place without shrinking, and delegate spatial
  SVC resize resets to `av1_svc_reset_cyclic_refresh_on_resize()`.
- In `svc_layercontext.c`, size and grow `lc->map` via
  `ensure_cyclic_refresh_map_size()` without shrinking, and replace
  `swap_ptr()` with a typed `swap_cyclic_refresh_map()` helper.
- Assert map non-null and capacity via
  `assert_cyclic_refresh_map_valid()` (and on `lc->map` restore) and
  clear `cr->map_size` elements in `cyclic_refresh_reset_resize()`.
- Add regression tests:
  - `EncodeAPI.CyclicRefreshMapResizeWithAqModeToggle`
  - `EncodeAPI.SvcCyclicRefreshMapResizeWithAqModeToggle`
  - `EncodeAPI.SvcCyclicRefreshMapKeyframeSwapAfterDownscale`

Bug: 588097961
Change-Id: I6c19026d9e0053e095c8a2e19c3ce68eeb79873f
diff --git a/av1/encoder/aq_cyclicrefresh.c b/av1/encoder/aq_cyclicrefresh.c
index b76fbf8..5620046 100644
--- a/av1/encoder/aq_cyclicrefresh.c
+++ b/av1/encoder/aq_cyclicrefresh.c
@@ -21,11 +21,22 @@
 #include "av1/encoder/tokenize.h"
 #include "aom_dsp/aom_dsp_common.h"
 
+static void assert_cyclic_refresh_map_valid(const CYCLIC_REFRESH *cr,
+                                            int mi_rows, int mi_cols) {
+  (void)cr;
+  (void)mi_rows;
+  (void)mi_cols;
+  assert(cr->map != NULL);
+  assert(cr->map_size >= (size_t)mi_rows * mi_cols);
+}
+
 CYCLIC_REFRESH *av1_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
+  assert(mi_rows >= 0 && mi_cols >= 0);
   CYCLIC_REFRESH *const cr = aom_calloc(1, sizeof(*cr));
   if (cr == NULL) return NULL;
 
-  cr->map = aom_calloc(mi_rows * mi_cols, sizeof(*cr->map));
+  const size_t map_size = (size_t)mi_rows * mi_cols;
+  cr->map = aom_calloc(map_size, sizeof(*cr->map));
   cr->counter_encode_maxq_scene_change = 0;
   cr->percent_refresh_adjustment = 5;
   cr->rate_ratio_qdelta_adjustment = 0.25;
@@ -33,6 +44,7 @@
     av1_cyclic_refresh_free(cr);
     return NULL;
   }
+  cr->map_size = map_size;
   return cr;
 }
 
@@ -169,6 +181,8 @@
     mbmi->segment_id =
         av1_get_spatial_seg_pred(cm, xd, &cdf_num, cr->skip_over4x4);
     if (prev_segment_id != mbmi->segment_id) {
+      assert_cyclic_refresh_map_valid(cr, cm->mi_params.mi_rows,
+                                      cm->mi_params.mi_cols);
       const int block_index = mi_row * cm->mi_params.mi_cols + mi_col;
       const int mi_stride = cm->mi_params.mi_cols;
       const uint8_t segment_id = mbmi->segment_id;
@@ -196,6 +210,8 @@
   MACROBLOCKD *const xd = &x->e_mbd;
   MB_MODE_INFO *const mbmi = xd->mi[0];
   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
+  assert_cyclic_refresh_map_valid(cr, cm->mi_params.mi_rows,
+                                  cm->mi_params.mi_cols);
   const int bw = mi_size_wide[bsize];
   const int bh = mi_size_high[bsize];
   const int xmis = AOMMIN(cm->mi_params.mi_cols - mi_col, bw);
@@ -304,6 +320,7 @@
   uint64_t thresh_sad = INT64_MAX;
   const int mi_rows = mi_params->mi_rows, mi_cols = mi_params->mi_cols;
   const int mi_stride = mi_cols;
+  assert_cyclic_refresh_map_valid(cr, mi_rows, mi_cols);
   // Don't set seg_map to 0 if active_maps is enabled. Active_maps will set
   // seg_map to either 7 or 0 (AM_SEGMENT_ID_INACTIVE/ACTIVE), and cyclic
   // refresh set below (segment 1 or 2) will only be set for ACTIVE blocks.
@@ -545,7 +562,9 @@
 static void cyclic_refresh_reset_resize(AV1_COMP *const cpi) {
   const AV1_COMMON *const cm = &cpi->common;
   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
-  memset(cr->map, 0, cm->mi_params.mi_rows * cm->mi_params.mi_cols);
+  assert_cyclic_refresh_map_valid(cr, cm->mi_params.mi_rows,
+                                  cm->mi_params.mi_cols);
+  memset(cr->map, 0, cr->map_size * sizeof(*cr->map));
   cr->sb_index = 0;
   cr->last_sb_index = 0;
   cpi->refresh_frame.golden_frame = true;
diff --git a/av1/encoder/aq_cyclicrefresh.h b/av1/encoder/aq_cyclicrefresh.h
index 7c71a69..5932e4d 100644
--- a/av1/encoder/aq_cyclicrefresh.h
+++ b/av1/encoder/aq_cyclicrefresh.h
@@ -12,6 +12,8 @@
 #ifndef AOM_AV1_ENCODER_AQ_CYCLICREFRESH_H_
 #define AOM_AV1_ENCODER_AQ_CYCLICREFRESH_H_
 
+#include <stddef.h>
+
 #include "av1/common/blockd.h"
 #include "av1/encoder/block.h"
 #include "av1/encoder/tokenize.h"
@@ -86,6 +88,10 @@
    */
   int8_t *map;
   /*!
+   * Allocated element count of `map`.
+   */
+  size_t map_size;
+  /*!
    * Threshold applied to the projected rate of the coding block,
    * when deciding whether block should be refreshed.
    */
diff --git a/av1/encoder/encoder.c b/av1/encoder/encoder.c
index b210ff6..5d1cee2 100644
--- a/av1/encoder/encoder.c
+++ b/av1/encoder/encoder.c
@@ -1094,36 +1094,23 @@
   }
   av1_update_frame_size(cpi);
 
-  if (cm->width != last_width || cm->height != last_height) {
-    if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
-      int mi_rows = cpi->common.mi_params.mi_rows;
-      int mi_cols = cpi->common.mi_params.mi_cols;
-      if (cpi->oxcf.frm_dim_cfg.forced_max_frame_width) {
-        mi_cols = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_width);
-      }
-      if (cpi->oxcf.frm_dim_cfg.forced_max_frame_height) {
-        mi_rows = size_in_mi(cpi->oxcf.frm_dim_cfg.forced_max_frame_height);
-      }
-      aom_free(cpi->cyclic_refresh->map);
-      CHECK_MEM_ERROR(
-          cm, cpi->cyclic_refresh->map,
-          aom_calloc(mi_rows * mi_cols, sizeof(*cpi->cyclic_refresh->map)));
-      if (cpi->svc.number_spatial_layers > 1) {
-        for (int sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
-          const int layer =
-              LAYER_IDS_TO_IDX(sl, 0, cpi->svc.number_temporal_layers);
-          LAYER_CONTEXT *const lc = &cpi->svc.layer_context[layer];
-          lc->sb_index = 0;
-          lc->actual_num_seg1_blocks = 0;
-          lc->actual_num_seg2_blocks = 0;
-          lc->counter_encode_maxq_scene_change = 0;
-          aom_free(lc->map);
-          CHECK_MEM_ERROR(cm, lc->map,
-                          aom_calloc(mi_rows * mi_cols, sizeof(*lc->map)));
-        }
-      }
+  const bool size_changed =
+      cm->width != last_width || cm->height != last_height;
+  if (cpi->cyclic_refresh != NULL) {
+    const size_t required_map_size = get_cyclic_refresh_map_size(cpi);
+    if (ensure_cyclic_refresh_map_size(cm, &cpi->cyclic_refresh->map,
+                                       &cpi->cyclic_refresh->map_size,
+                                       required_map_size, size_changed)) {
+      cpi->cyclic_refresh->sb_index = 0;
+      cpi->cyclic_refresh->last_sb_index = 0;
+      cpi->cyclic_refresh->actual_num_seg1_blocks = 0;
+      cpi->cyclic_refresh->actual_num_seg2_blocks = 0;
+      cpi->cyclic_refresh->counter_encode_maxq_scene_change = 0;
     }
   }
+  if (size_changed && cpi->ppi->use_svc) {
+    av1_svc_reset_cyclic_refresh_on_resize(cpi);
+  }
 
   // av1_reset_segment_features() turned segmentation off, so set the active
   // map up again if it was set for this frame size.
diff --git a/av1/encoder/encoder_alloc.h b/av1/encoder/encoder_alloc.h
index 7574ce8..68b6dcd 100644
--- a/av1/encoder/encoder_alloc.h
+++ b/av1/encoder/encoder_alloc.h
@@ -107,6 +107,41 @@
     alloc_context_buffers_ext(cm, &cpi->mbmi_ext_info);
 }
 
+static inline size_t get_cyclic_refresh_map_size(const AV1_COMP *cpi) {
+  const AV1_COMMON *const cm = &cpi->common;
+  const FrameDimensionCfg *const frm_dim_cfg = &cpi->oxcf.frm_dim_cfg;
+  const int max_width =
+      AOMMAX(AOMMAX(frm_dim_cfg->width, cpi->data_alloc_width),
+             frm_dim_cfg->forced_max_frame_width);
+  const int max_height =
+      AOMMAX(AOMMAX(frm_dim_cfg->height, cpi->data_alloc_height),
+             frm_dim_cfg->forced_max_frame_height);
+  const int max_mi_cols = AOMMAX(cm->mi_params.mi_cols, size_in_mi(max_width));
+  const int max_mi_rows = AOMMAX(cm->mi_params.mi_rows, size_in_mi(max_height));
+  return (size_t)max_mi_rows * max_mi_cols;
+}
+
+static inline bool ensure_cyclic_refresh_map_size(AV1_COMMON *cm, int8_t **map,
+                                                  size_t *map_size,
+                                                  size_t required_size,
+                                                  bool clear_if_valid) {
+  if (*map == NULL || *map_size < required_size) {
+    aom_free(*map);
+    *map = NULL;
+    *map_size = 0;
+    int8_t *new_map = NULL;
+    CHECK_MEM_ERROR(cm, new_map, aom_calloc(required_size, sizeof(*new_map)));
+    *map = new_map;
+    *map_size = required_size;
+    return true;
+  }
+  if (clear_if_valid) {
+    memset(*map, 0, *map_size * sizeof(**map));
+    return true;
+  }
+  return false;
+}
+
 static inline void realloc_segmentation_maps(AV1_COMP *cpi) {
   AV1_COMMON *const cm = &cpi->common;
   CommonModeInfoParams *const mi_params = &cm->mi_params;
diff --git a/av1/encoder/svc_layercontext.c b/av1/encoder/svc_layercontext.c
index 88d07e3..0f3d397 100644
--- a/av1/encoder/svc_layercontext.c
+++ b/av1/encoder/svc_layercontext.c
@@ -15,20 +15,52 @@
 #include "av1/encoder/encoder.h"
 #include "av1/encoder/encoder_alloc.h"
 
-static void swap_ptr(void *a, void *b) {
-  void **a_p = (void **)a;
-  void **b_p = (void **)b;
-  void *c = *a_p;
-  *a_p = *b_p;
-  *b_p = c;
+static void swap_cyclic_refresh_map(CYCLIC_REFRESH *cr, LAYER_CONTEXT *lc) {
+  int8_t *const temp_map = cr->map;
+  cr->map = lc->map;
+  lc->map = temp_map;
+  const size_t temp_size = cr->map_size;
+  cr->map_size = lc->map_size;
+  lc->map_size = temp_size;
+}
+
+static void reset_layer_cyclic_refresh_counters(LAYER_CONTEXT *lc) {
+  lc->sb_index = 0;
+  lc->actual_num_seg1_blocks = 0;
+  lc->actual_num_seg2_blocks = 0;
+  lc->counter_encode_maxq_scene_change = 0;
+}
+
+static void reset_layer_cyclic_refresh(AV1_COMP *cpi, LAYER_CONTEXT *lc,
+                                       size_t required_map_size) {
+  reset_layer_cyclic_refresh_counters(lc);
+  ensure_cyclic_refresh_map_size(&cpi->common, &lc->map, &lc->map_size,
+                                 required_map_size, true);
+}
+
+void av1_svc_reset_cyclic_refresh_on_resize(AV1_COMP *cpi) {
+  SVC *const svc = &cpi->svc;
+  if (svc->number_spatial_layers <= 1 || svc->layer_context == NULL) return;
+  const size_t required_map_size = get_cyclic_refresh_map_size(cpi);
+  for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
+    const int layer = LAYER_IDS_TO_IDX(sl, 0, svc->number_temporal_layers);
+    if (layer >= svc->num_allocated_layers) break;
+    LAYER_CONTEXT *const lc = &svc->layer_context[layer];
+    if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
+      reset_layer_cyclic_refresh(cpi, lc, required_map_size);
+    } else {
+      reset_layer_cyclic_refresh_counters(lc);
+      if (lc->map != NULL) {
+        memset(lc->map, 0, lc->map_size * sizeof(*lc->map));
+      }
+    }
+  }
 }
 
 void av1_init_layer_context(AV1_COMP *const cpi) {
-  AV1_COMMON *const cm = &cpi->common;
   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
   SVC *const svc = &cpi->svc;
-  int mi_rows = cpi->common.mi_params.mi_rows;
-  int mi_cols = cpi->common.mi_params.mi_cols;
+  const size_t required_map_size = get_cyclic_refresh_map_size(cpi);
   svc->base_framerate = 30.0;
   svc->current_superframe = 0;
   svc->source_half_valid = 0;
@@ -77,13 +109,7 @@
       // layer. Cyclic refresh is only applied on base temporal layer.
       if (svc->number_spatial_layers > 1 && tl == 0 &&
           cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ) {
-        lc->sb_index = 0;
-        lc->actual_num_seg1_blocks = 0;
-        lc->actual_num_seg2_blocks = 0;
-        lc->counter_encode_maxq_scene_change = 0;
-        aom_free(lc->map);
-        CHECK_MEM_ERROR(cm, lc->map,
-                        aom_calloc(mi_rows * mi_cols, sizeof(*lc->map)));
+        reset_layer_cyclic_refresh(cpi, lc, required_map_size);
       }
     }
     svc->downsample_filter_type[sl] = BILINEAR;
@@ -116,13 +142,11 @@
                                             const int64_t target_bandwidth) {
   const RATE_CONTROL *const rc = &cpi->rc;
   const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
-  AV1_COMMON *const cm = &cpi->common;
   SVC *const svc = &cpi->svc;
   int layer = 0;
   int64_t spatial_layer_target = 0;
   float bitrate_alloc = 1.0;
-  const int mi_rows = cm->mi_params.mi_rows;
-  const int mi_cols = cm->mi_params.mi_cols;
+  const size_t required_map_size = get_cyclic_refresh_map_size(cpi);
   for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
       layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
@@ -160,20 +184,14 @@
         lrc->worst_quality = rc->worst_quality;
         lrc->best_quality = rc->best_quality;
       }
-      // Reset the cyclic refresh parameters, if needed (map is NULL),
-      // or number of spatial layers has changed.
+      // Reset the cyclic refresh parameters, if needed (map is NULL or too
+      // small), or number of spatial layers has changed.
       // Cyclic refresh is only applied on base temporal layer.
       if (svc->number_spatial_layers > 1 && tl == 0 &&
           cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
-          (lc->map == NULL ||
+          (lc->map == NULL || lc->map_size < required_map_size ||
            svc->prev_number_spatial_layers != svc->number_spatial_layers)) {
-        lc->sb_index = 0;
-        lc->actual_num_seg1_blocks = 0;
-        lc->actual_num_seg2_blocks = 0;
-        lc->counter_encode_maxq_scene_change = 0;
-        aom_free(lc->map);
-        CHECK_MEM_ERROR(cm, lc->map,
-                        aom_calloc(mi_rows * mi_cols, sizeof(*lc->map)));
+        reset_layer_cyclic_refresh(cpi, lc, required_map_size);
       }
     }
   }
@@ -274,7 +292,10 @@
   if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
       svc->number_spatial_layers > 1 && svc->temporal_layer_id == 0) {
     CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
-    swap_ptr(&cr->map, &lc->map);
+    assert(lc->map != NULL);
+    assert(lc->map_size >=
+           (size_t)cm->mi_params.mi_rows * cm->mi_params.mi_cols);
+    swap_cyclic_refresh_map(cr, lc);
     cr->sb_index = lc->sb_index;
     cr->actual_num_seg1_blocks = lc->actual_num_seg1_blocks;
     cr->actual_num_seg2_blocks = lc->actual_num_seg2_blocks;
@@ -340,9 +361,7 @@
   if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
       cpi->svc.number_spatial_layers > 1 && svc->temporal_layer_id == 0) {
     CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
-    signed char *temp = lc->map;
-    lc->map = cr->map;
-    cr->map = temp;
+    swap_cyclic_refresh_map(cr, lc);
     lc->sb_index = cr->sb_index;
     lc->actual_num_seg1_blocks = cr->actual_num_seg1_blocks;
     lc->actual_num_seg2_blocks = cr->actual_num_seg2_blocks;
@@ -408,6 +427,7 @@
       aom_free(lc->map);
       lc->map = NULL;
     }
+    lc->map_size = 0;
   }
 }
 
diff --git a/av1/encoder/svc_layercontext.h b/av1/encoder/svc_layercontext.h
index 4425e76..6612824 100644
--- a/av1/encoder/svc_layercontext.h
+++ b/av1/encoder/svc_layercontext.h
@@ -12,6 +12,8 @@
 #ifndef AOM_AV1_ENCODER_SVC_LAYERCONTEXT_H_
 #define AOM_AV1_ENCODER_SVC_LAYERCONTEXT_H_
 
+#include <stddef.h>
+
 #include "aom_scale/yv12config.h"
 #include "av1/encoder/aq_cyclicrefresh.h"
 #include "av1/encoder/encoder.h"
@@ -51,6 +53,10 @@
    */
   int8_t *map;
   /*!
+   * Allocated element count of `map`.
+   */
+  size_t map_size;
+  /*!
    * Number of blocks on segment 1
    */
   int actual_num_seg1_blocks;
@@ -277,6 +283,16 @@
  */
 void av1_free_svc_cyclic_refresh(struct AV1_COMP *const cpi);
 
+/*!\brief Reset cyclic refresh maps and counters for spatial SVC on resize.
+ *
+ * \ingroup SVC
+ * \callgraph
+ * \callergraph
+ *
+ * \param[in]       cpi  Top level encoder structure
+ */
+void av1_svc_reset_cyclic_refresh_on_resize(struct AV1_COMP *cpi);
+
 /*!\brief Reset on key frame: reset counters, references and buffer updates.
  *
  * \ingroup SVC
diff --git a/test/encode_api_test.cc b/test/encode_api_test.cc
index 33bb20b..89fea87 100644
--- a/test/encode_api_test.cc
+++ b/test/encode_api_test.cc
@@ -102,8 +102,8 @@
 }
 
 static void EncodeOne(aom_codec_ctx_t *codec, aom_image_t *img,
-                      aom_codec_pts_t pts) {
-  ASSERT_EQ(aom_codec_encode(codec, img, pts, 1, 0), AOM_CODEC_OK);
+                      aom_codec_pts_t pts, aom_enc_frame_flags_t flags = 0) {
+  ASSERT_EQ(aom_codec_encode(codec, img, pts, 1, flags), AOM_CODEC_OK);
   aom_codec_iter_t iter = NULL;
   while (aom_codec_get_cx_data(codec, &iter) != NULL) {
   }
@@ -6955,6 +6955,246 @@
 #endif  // !CONFIG_REALTIME_ONLY
 #endif  // CONFIG_AV1_HIGHBITDEPTH
 
+static void InitRealtimeCbrCyclicRefreshEncoder(unsigned int width,
+                                                unsigned int height,
+                                                aom_codec_enc_cfg_t *cfg,
+                                                aom_codec_ctx_t *enc) {
+  aom_codec_iface_t *const iface = aom_codec_av1_cx();
+  ASSERT_EQ(aom_codec_enc_config_default(iface, cfg, AOM_USAGE_REALTIME),
+            AOM_CODEC_OK);
+  cfg->g_w = width;
+  cfg->g_h = height;
+  cfg->g_lag_in_frames = 0;
+  cfg->rc_end_usage = AOM_CBR;
+  cfg->rc_target_bitrate = 500;
+  cfg->rc_min_quantizer = 20;
+  cfg->rc_max_quantizer = 56;
+
+  ASSERT_EQ(aom_codec_enc_init(enc, iface, cfg, 0), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(enc, AOME_SET_CPUUSED, 10), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+}
+
+static void EncodeSuperframe(aom_codec_ctx_t *enc, aom_image_t *img,
+                             aom_codec_pts_t pts, int num_sl,
+                             aom_enc_frame_flags_t sl0_flags = 0) {
+  for (int sl = 0; sl < num_sl; ++sl) {
+    aom_svc_layer_id_t layer_id = {};
+    layer_id.spatial_layer_id = sl;
+    ASSERT_EQ(aom_codec_control(enc, AV1E_SET_SVC_LAYER_ID, &layer_id),
+              AOM_CODEC_OK);
+    ASSERT_NO_FATAL_FAILURE(EncodeOne(enc, img, pts, sl == 0 ? sl0_flags : 0));
+  }
+}
+
+// Reproduces b/588097961: heap buffer overflow on cyclic_refresh->map when
+// downscaling with CYCLIC_REFRESH_AQ enabled, disabling AQ, upscaling back
+// within the previously allocated dimensions, and re-enabling
+// CYCLIC_REFRESH_AQ.
+TEST(EncodeAPI, CyclicRefreshMapResizeWithAqModeToggle) {
+  constexpr unsigned int kLargeW = 640;
+  constexpr unsigned int kLargeH = 480;
+  constexpr unsigned int kSmallW = 320;
+  constexpr unsigned int kSmallH = 240;
+
+  aom_codec_enc_cfg_t cfg;
+  aom_codec_ctx_t enc;
+  ASSERT_NO_FATAL_FAILURE(
+      InitRealtimeCbrCyclicRefreshEncoder(kLargeW, kLargeH, &cfg, &enc));
+
+  aom_image_t *const large_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kLargeW, kLargeH, 1);
+  aom_image_t *const small_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kSmallW, kSmallH, 1);
+  ASSERT_NE(large_img, nullptr);
+  ASSERT_NE(small_img, nullptr);
+
+  int64_t pts = 0;
+  // Encode at initial large size with cyclic refresh enabled.
+  for (int i = 0; i < 3; ++i) {
+    FillImage(large_img, static_cast<uint8_t>(64 + i));
+    ASSERT_NO_FATAL_FAILURE(EncodeOne(&enc, large_img, pts++));
+  }
+
+  // Downscale while cyclic refresh is enabled.
+  cfg.g_w = kSmallW;
+  cfg.g_h = kSmallH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  for (int i = 0; i < 2; ++i) {
+    FillImage(small_img, static_cast<uint8_t>(80 + i));
+    ASSERT_NO_FATAL_FAILURE(EncodeOne(&enc, small_img, pts++));
+  }
+
+  // Disable AQ, upscale back to original size, then re-enable cyclic refresh.
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 0), AOM_CODEC_OK);
+  cfg.g_w = kLargeW;
+  cfg.g_h = kLargeH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+
+  // Encode enough frames at the larger resolution to run cyclic refresh across
+  // the entire frame.
+  for (int i = 0; i < 12; ++i) {
+    FillImage(large_img, static_cast<uint8_t>(96 + (i % 4)));
+    ASSERT_NO_FATAL_FAILURE(EncodeOne(&enc, large_img, pts++));
+  }
+
+  aom_img_free(small_img);
+  aom_img_free(large_img);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
+// Reproduces b/588097961 for spatial SVC: layer context cyclic refresh maps
+// (lc->map) must remain large enough when resizing with AV1E_SET_AQ_MODE
+// toggled off and back on, both when growing beyond initial dimensions and
+// when shrinking and growing back.
+TEST(EncodeAPI, SvcCyclicRefreshMapResizeWithAqModeToggle) {
+  constexpr unsigned int kSmallW = 320;
+  constexpr unsigned int kSmallH = 240;
+  constexpr unsigned int kLargeW = 640;
+  constexpr unsigned int kLargeH = 480;
+
+  aom_codec_enc_cfg_t cfg;
+  aom_codec_ctx_t enc;
+  ASSERT_NO_FATAL_FAILURE(
+      InitRealtimeCbrCyclicRefreshEncoder(kSmallW, kSmallH, &cfg, &enc));
+
+  const int num[] = { 1, 1 };
+  const int den[] = { 2, 1 };
+  const int bitrates[] = { 150, 350 };
+  ASSERT_NO_FATAL_FAILURE(SetSvc(&enc, 2, num, den, bitrates));
+
+  aom_image_t *const small_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kSmallW, kSmallH, 1);
+  aom_image_t *const large_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kLargeW, kLargeH, 1);
+  ASSERT_NE(small_img, nullptr);
+  ASSERT_NE(large_img, nullptr);
+
+  int64_t pts = 0;
+  // Start at 320x240 with cyclic refresh enabled.
+  for (int i = 0; i < 3; ++i) {
+    FillImage(small_img, static_cast<uint8_t>(64 + i));
+    ASSERT_NO_FATAL_FAILURE(EncodeSuperframe(&enc, small_img, pts++, 2));
+  }
+
+  // Disable AQ, grow beyond initial dimensions to 640x480, re-enable AQ.
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 0), AOM_CODEC_OK);
+  cfg.g_w = kLargeW;
+  cfg.g_h = kLargeH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+  for (int i = 0; i < 12; ++i) {
+    FillImage(large_img, static_cast<uint8_t>(80 + (i % 4)));
+    ASSERT_NO_FATAL_FAILURE(EncodeSuperframe(&enc, large_img, pts++, 2));
+  }
+
+  // Downscale while cyclic refresh is enabled, then disable AQ, upscale back
+  // to 640x480, and re-enable AQ.
+  cfg.g_w = kSmallW;
+  cfg.g_h = kSmallH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  for (int i = 0; i < 2; ++i) {
+    FillImage(small_img, static_cast<uint8_t>(96 + i));
+    ASSERT_NO_FATAL_FAILURE(EncodeSuperframe(&enc, small_img, pts++, 2));
+  }
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 0), AOM_CODEC_OK);
+  cfg.g_w = kLargeW;
+  cfg.g_h = kLargeH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+  for (int i = 0; i < 12; ++i) {
+    FillImage(large_img, static_cast<uint8_t>(112 + (i % 4)));
+    ASSERT_NO_FATAL_FAILURE(EncodeSuperframe(&enc, large_img, pts++, 2));
+  }
+
+  aom_img_free(large_img);
+  aom_img_free(small_img);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
+// Reproduces b/588097961: in spatial SVC, a keyframe after frame 0 swaps
+// cr->map and lc[0]->map three times (restore -> reset_temporal_layers restore
+// -> save). If lc[0]->map was sized smaller than data_alloc_width/height, that
+// exchange leaves cpi->cyclic_refresh->map undersized on a subsequent upscale
+// within data_alloc_width/height.
+TEST(EncodeAPI, SvcCyclicRefreshMapKeyframeSwapAfterDownscale) {
+  constexpr unsigned int kSmallW = 320;
+  constexpr unsigned int kSmallH = 240;
+  constexpr unsigned int kLargeW = 640;
+  constexpr unsigned int kLargeH = 480;
+
+  aom_codec_enc_cfg_t cfg;
+  aom_codec_ctx_t enc;
+  ASSERT_NO_FATAL_FAILURE(
+      InitRealtimeCbrCyclicRefreshEncoder(kSmallW, kSmallH, &cfg, &enc));
+
+  // Use 1:1 scaling for both spatial layers (quality layers) so lc[0] keeps
+  // 1/1 scaling after switching back to 1SL (ctrl_set_svc_params() only
+  // updates layer_context[] when spatial_layers > 1 || temporal_layers > 1).
+  const int num[] = { 1, 1 };
+  const int den[] = { 1, 1 };
+  const int bitrates[] = { 150, 350 };
+  ASSERT_NO_FATAL_FAILURE(SetSvc(&enc, 2, num, den, bitrates));
+
+  aom_image_t *const small_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kSmallW, kSmallH, 1);
+  aom_image_t *const large_img =
+      aom_img_alloc(nullptr, AOM_IMG_FMT_I420, kLargeW, kLargeH, 1);
+  ASSERT_NE(small_img, nullptr);
+  ASSERT_NE(large_img, nullptr);
+
+  int64_t pts = 0;
+  // Encode initial superframes at 320x240 so frame_number > 0.
+  for (int i = 0; i < 2; ++i) {
+    FillImage(small_img, static_cast<uint8_t>(64 + i));
+    ASSERT_NO_FATAL_FAILURE(EncodeSuperframe(&enc, small_img, pts++, 2));
+  }
+
+  // Disable AQ, grow data_alloc to 640x480, then downscale back to 320x240
+  // while AQ is still disabled.
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 0), AOM_CODEC_OK);
+  cfg.g_w = kLargeW;
+  cfg.g_h = kLargeH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  cfg.g_w = kSmallW;
+  cfg.g_h = kSmallH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+
+  // Re-enable AQ at 320x240 and force a keyframe (frame_number > 0) so
+  // av1_svc_reset_temporal_layers() swaps cr->map and lc[0]->map.
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+  FillImage(small_img, 80);
+  ASSERT_NO_FATAL_FAILURE(
+      EncodeSuperframe(&enc, small_img, pts++, 2, AOM_EFLAG_FORCE_KF));
+
+  // Disable AQ across the upscale back to 640x480 (within
+  // data_alloc_width/height), then re-enable AQ and switch back to 1SL so the
+  // test also reproduces an undersized cr->map overflow against main while
+  // exercising the keyframe swap path.
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 0), AOM_CODEC_OK);
+  cfg.g_w = kLargeW;
+  cfg.g_h = kLargeH;
+  ASSERT_EQ(aom_codec_enc_config_set(&enc, &cfg), AOM_CODEC_OK);
+  ASSERT_EQ(aom_codec_control(&enc, AV1E_SET_AQ_MODE, 3), AOM_CODEC_OK);
+  const int num1[] = { 1 };
+  const int den1[] = { 1 };
+  const int bitrates1[] = { 500 };
+  ASSERT_NO_FATAL_FAILURE(SetSvc(&enc, 1, num1, den1, bitrates1));
+  for (int i = 0; i < 12; ++i) {
+    FillImageRandom(large_img);
+    ASSERT_NO_FATAL_FAILURE(EncodeOne(&enc, large_img, pts++));
+    const aom_image_t *const preview = aom_codec_get_preview_frame(&enc);
+    ASSERT_NE(preview, nullptr);
+    ASSERT_EQ(preview->d_w, kLargeW);
+    ASSERT_EQ(preview->d_h, kLargeH);
+  }
+
+  aom_img_free(large_img);
+  aom_img_free(small_img);
+  ASSERT_EQ(aom_codec_destroy(&enc), AOM_CODEC_OK);
+}
+
 #if CONFIG_AV1_DECODER
 // Encodes a static screen in realtime mode, then fades a small flat area a
 // few levels per frame. Each frame changes less than one level per 64x64