Commit 511fca3cc5 for aom

commit 511fca3cc5cdf636348dd44a5a97d25447abe63a
Author: Frank Galligan <fgalligan@google.com>
Date:   Tue Nov 24 15:24:04 2026 -0800

    intra_mode_search: optimize HoG, CfL & RDO

    Optimize intra mode search, CfL alpha search, color counting, and
    blockd helpers in portable C:
    - Hoist Y/UV-mode RDO invariants, add INTRA_RD_VAR_THRESH(speed) > 0
      and reduce_model_rd_idx_mask pruning, streamline
      intra_mode_info_cost_y/uv, unroll top-K directional pruning, optimize
      cached 32-bin HoG with 2-bank accumulation, a zero-HoG shortcut
      (kZeroHogScores), and a 2^24-safe float32 fallback (LBD/HBD), and
      outline rd_pick_filter_intra_sby (updating ctx->tx_type_map
      directly) behind != 2 caller guard.
    - Add fast LBD CfL alpha search (cfl_pick_plane_parameter_lbd) reading
      the uniform DC value from *dst (cfl_predict_lbd_c, cfl.h), outline
      cfl_rd_pick_alpha / cfl_rd_pick_alpha_multi, and pack UV mode tests.
    - Optimize av1_count_colors_with_threshold with a local counter and
      ptrdiff_t row stepping while keeping rows <= 0 || cols <= 0 parity.
    - Add av1_copy_tx_type_map and optimize av1_get_tx_type,
      update_txk_array, av1_reset_entropy_context, and
      av1_fill_entropy_ctx_pow2 in blockd.h / blockd.c.
    - Add unit tests in test/intra_hog_test.cc and test/cfl_test.cc, and
      define AOM_NOINLINE:= in libs.doxy_template for Doxygen.

    Speedup (AMD EPYC 7B13, Clang 21, measured vs d91e90d7; rebased onto
          653af86d52 and verified bit-exact incl. sby_cfl):
      -7.34% 1T / -0.98% 8T allintra, -1.78% 1T 720p good; bit-exact across
      tested 8-bit/10-bit/monochrome/SIMD masks (incl. 10-bit --rt
      --cpu-used=10 --kf-max-dist=16).
    Binary size (x86_64 -O3): libaom.a .text -0.3 KiB (-0.00%),
      .rodata -1.9 KiB (-0.19%), stripped aomenc +0.0 KiB (+0.00%).
    Memory (peak RSS, THP off): 1T +16 KiB (+0.04%) allintra,
      -32 KiB (-0.01%) good 1T, -32 KiB (-0.08%) rt 1T.

    TAG=agy
    CONV=4b696004-0036-42b2-b3fa-d1c7d63a973c
    Change-Id: I761b69c9d96195a77b549523d87c6f426260b794

diff --git a/av1/common/blockd.c b/av1/common/blockd.c
index ed75531439..1c1fb01106 100644
--- a/av1/common/blockd.c
+++ b/av1/common/blockd.c
@@ -9,6 +9,7 @@
  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
  */

+#include <assert.h>
 #include <math.h>

 #include "av1/common/av1_common_int.h"
@@ -29,15 +30,21 @@ PREDICTION_MODE av1_above_block_mode(const MB_MODE_INFO *above_mi) {
 void av1_reset_entropy_context(MACROBLOCKD *xd, BLOCK_SIZE bsize,
                                const int num_planes) {
   assert(bsize < BLOCK_SIZES_ALL);
-  const int nplanes = 1 + (num_planes - 1) * xd->is_chroma_ref;
-  for (int i = 0; i < nplanes; i++) {
-    struct macroblockd_plane *const pd = &xd->plane[i];
+  assert(num_planes == 1 || num_planes == MAX_MB_PLANE);
+  av1_fill_entropy_ctx_pow2(xd->plane[0].above_entropy_context, 0,
+                            mi_size_wide[bsize]);
+  av1_fill_entropy_ctx_pow2(xd->plane[0].left_entropy_context, 0,
+                            mi_size_high[bsize]);
+  if (xd->is_chroma_ref && num_planes > 1) {
+    const struct macroblockd_plane *const pd1 = &xd->plane[1];
     const BLOCK_SIZE plane_bsize =
-        get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
+        get_plane_block_size(bsize, pd1->subsampling_x, pd1->subsampling_y);
     const int txs_wide = mi_size_wide[plane_bsize];
     const int txs_high = mi_size_high[plane_bsize];
-    av1_fill_entropy_ctx_pow2(pd->above_entropy_context, 0, txs_wide);
-    av1_fill_entropy_ctx_pow2(pd->left_entropy_context, 0, txs_high);
+    av1_fill_entropy_ctx_pow2(pd1->above_entropy_context, 0, txs_wide);
+    av1_fill_entropy_ctx_pow2(xd->plane[2].above_entropy_context, 0, txs_wide);
+    av1_fill_entropy_ctx_pow2(pd1->left_entropy_context, 0, txs_high);
+    av1_fill_entropy_ctx_pow2(xd->plane[2].left_entropy_context, 0, txs_high);
   }
 }

diff --git a/av1/common/blockd.h b/av1/common/blockd.h
index 9bd0756278..66ab86fadc 100644
--- a/av1/common/blockd.h
+++ b/av1/common/blockd.h
@@ -12,6 +12,9 @@
 #ifndef AOM_AV1_COMMON_BLOCKD_H_
 #define AOM_AV1_COMMON_BLOCKD_H_

+#include <assert.h>
+#include <string.h>
+
 #include "config/aom_config.h"

 #include "aom_dsp/aom_dsp_common.h"
@@ -1291,14 +1294,13 @@ static inline void update_txk_array(MACROBLOCKD *const xd, int blk_row,
   const int stride = xd->tx_type_map_stride;
   xd->tx_type_map[blk_row * stride + blk_col] = tx_type;

-  const int txw = tx_size_wide_unit[tx_size];
-  const int txh = tx_size_high_unit[tx_size];
   // The 16x16 unit is due to the constraint from tx_64x64 which sets the
   // maximum tx size for chroma as 32x32. Coupled with 4x1 transform block
   // size, the constraint takes effect in 32x16 / 16x32 size too. To solve
   // the intricacy, cover all the 16x16 units inside a 64 level transform.
-  if (txw == tx_size_wide_unit[TX_64X64] ||
-      txh == tx_size_high_unit[TX_64X64]) {
+  if (txsize_sqr_up_map[tx_size] == TX_64X64) {
+    const int txw = tx_size_wide_unit[tx_size];
+    const int txh = tx_size_high_unit[tx_size];
     const int tx_unit = tx_size_wide_unit[TX_16X16];
     for (int idy = 0; idy < txh; idy += tx_unit) {
       for (int idx = 0; idx < txw; idx += tx_unit) {
@@ -1313,32 +1315,49 @@ static inline TX_TYPE av1_get_tx_type(const MACROBLOCKD *xd,
                                       int blk_col, TX_SIZE tx_size,
                                       int reduced_tx_set) {
   const MB_MODE_INFO *const mbmi = xd->mi[0];
-  if (xd->lossless[mbmi->segment_id] || txsize_sqr_up_map[tx_size] > TX_32X32) {
+  const TX_SIZE tx_size_sqr_up = txsize_sqr_up_map[tx_size];
+  if (xd->lossless[mbmi->segment_id] || tx_size_sqr_up > TX_32X32) {
     return DCT_DCT;
   }

-  TX_TYPE tx_type;
   if (plane_type == PLANE_TYPE_Y) {
-    tx_type = xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
-  } else {
-    if (is_inter_block(mbmi)) {
-      // scale back to y plane's coordinate
-      const struct macroblockd_plane *const pd = &xd->plane[plane_type];
-      blk_row <<= pd->subsampling_y;
-      blk_col <<= pd->subsampling_x;
-      tx_type = xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
-    } else {
-      // In intra mode, uv planes don't share the same prediction mode as y
-      // plane, so the tx_type should not be shared
-      tx_type = intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV);
-    }
-    const TxSetType tx_set_type =
-        av1_get_ext_tx_set_type(tx_size, is_inter_block(mbmi), reduced_tx_set);
-    if (!av1_ext_tx_used[tx_set_type][tx_type]) tx_type = DCT_DCT;
+    const TX_TYPE tx_type =
+        xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
+    assert(tx_type < TX_TYPES);
+    assert(av1_ext_tx_used[av1_get_ext_tx_set_type(
+        tx_size, is_inter_block(mbmi), reduced_tx_set)][tx_type]);
+    return tx_type;
   }
+
+  if (!is_inter_block(mbmi)) {
+    // In intra mode, uv planes don't share the same prediction mode as y
+    // plane, so the tx_type should not be shared. Intra tx sets for
+    // tx_size_sqr_up <= TX_16X16 always include {DCT, ADST}^2, and
+    // TX_32X32 is DCT_DCT-only (enforced by the asserts below).
+    const TX_TYPE tx_type = (tx_size_sqr_up == TX_32X32)
+                                ? (TX_TYPE)DCT_DCT
+                                : intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV);
+    assert(tx_type < TX_TYPES);
+    assert(av1_ext_tx_used[av1_get_ext_tx_set_type(tx_size, 0, reduced_tx_set)]
+                          [tx_type]);
+    return tx_type;
+  }
+
+  // scale back to y plane's coordinate
+  const struct macroblockd_plane *const pd = &xd->plane[plane_type];
+  blk_row <<= pd->subsampling_y;
+  blk_col <<= pd->subsampling_x;
+  TX_TYPE tx_type = xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
   assert(tx_type < TX_TYPES);
-  assert(av1_ext_tx_used[av1_get_ext_tx_set_type(tx_size, is_inter_block(mbmi),
-                                                 reduced_tx_set)][tx_type]);
+  if (tx_type != DCT_DCT) {
+    const TxSetType tx_set_type =
+        av1_get_ext_tx_set_type(tx_size, 1, reduced_tx_set);
+    if (!(av1_ext_tx_used_flag[tx_set_type] & (1U << tx_type))) {
+      tx_type = DCT_DCT;
+    }
+  }
+  assert(av1_ext_tx_used[av1_get_ext_tx_set_type(tx_size, 1, reduced_tx_set)]
+                        [tx_type]);
   return tx_type;
 }

@@ -1459,27 +1478,53 @@ static inline int max_block_high(const MACROBLOCKD *xd, BLOCK_SIZE bsize,
   return max_blocks_high >> MI_SIZE_LOG2;
 }

+// Copies n tx_type_map entries. n must be a power of two in [1, 1024].
+static inline void av1_copy_tx_type_map(uint8_t *dst, const uint8_t *src,
+                                        int n) {
+  assert(n >= 1 && (n & (n - 1)) == 0);
+  if (n <= 2) {
+    dst[0] = src[0];
+    dst[n - 1] = src[n - 1];
+  } else if (n <= 8) {
+    uint32_t v0, v1;
+    memcpy(&v0, src, 4);
+    memcpy(&v1, src + (n - 4), 4);
+    memcpy(dst, &v0, 4);
+    memcpy(dst + (n - 4), &v1, 4);
+  } else if (n <= 32) {
+    uint8_t lo[16], hi[16];
+    memcpy(lo, src, 16);
+    memcpy(hi, src + (n - 16), 16);
+    memcpy(dst, lo, 16);
+    memcpy(dst + (n - 16), hi, 16);
+  } else {
+    memcpy(dst, src, (size_t)n);
+  }
+}
+
 // Fast power-of-two specialization for filling n ENTROPY_CONTEXT bytes with val
 // using fixed-width scalar stores instead of a runtime memset call.
+// n must be a power of two in [1, 32].
 static inline void av1_fill_entropy_ctx_pow2(ENTROPY_CONTEXT *dst, uint8_t val,
                                              int n) {
-  if (n == 1) {
+  static_assert(sizeof(ENTROPY_CONTEXT) == 1, "");
+  assert(n == 1 || n == 2 || n == 4 || n == 8 || n == 16 || n == 32);
+  if (n <= 2) {
     dst[0] = val;
-  } else if (n == 2) {
-    const uint16_t v2 = (uint16_t)val * 0x0101u;
-    memcpy(dst, &v2, 2);
+    dst[n - 1] = val;
   } else if (n == 4) {
     const uint32_t v4 = (uint32_t)val * 0x01010101u;
     memcpy(dst, &v4, 4);
-  } else if (n == 8) {
+  } else if (n <= 16) {
     const uint64_t v8 = (uint64_t)val * 0x0101010101010101ULL;
     memcpy(dst, &v8, 8);
-  } else if (n == 16) {
+    memcpy(dst + (n - 8), &v8, 8);
+  } else {
     const uint64_t v8 = (uint64_t)val * 0x0101010101010101ULL;
     memcpy(dst, &v8, 8);
     memcpy(dst + 8, &v8, 8);
-  } else {
-    memset(dst, val, sizeof(*dst) * n);
+    memcpy(dst + 16, &v8, 8);
+    memcpy(dst + 24, &v8, 8);
   }
 }

diff --git a/av1/common/cfl.c b/av1/common/cfl.c
index 25d557d3f9..198c76fbe5 100644
--- a/av1/common/cfl.c
+++ b/av1/common/cfl.c
@@ -239,9 +239,10 @@ static inline int cfl_idx_to_alpha(uint8_t alpha_idx, int8_t joint_sign,
 static inline void cfl_predict_lbd_c(const int16_t *ac_buf_q3, uint8_t *dst,
                                      int dst_stride, int alpha_q3, int width,
                                      int height) {
+  const uint8_t dc = *dst;
   for (int j = 0; j < height; j++) {
     for (int i = 0; i < width; i++) {
-      dst[i] = clip_pixel(get_scaled_luma_q0(alpha_q3, ac_buf_q3[i]) + dst[i]);
+      dst[i] = clip_pixel(get_scaled_luma_q0(alpha_q3, ac_buf_q3[i]) + dc);
     }
     dst += dst_stride;
     ac_buf_q3 += CFL_BUF_LINE;
diff --git a/av1/common/cfl.h b/av1/common/cfl.h
index 73c060b101..f78975bafb 100644
--- a/av1/common/cfl.h
+++ b/av1/common/cfl.h
@@ -224,6 +224,8 @@ void cfl_load_dc_pred(MACROBLOCKD *const xd, uint8_t *dst, int dst_stride,
     return sub_avg[tx_size % TX_SIZES_ALL];                               \
   }

+// All cfl_predict_lbd implementations read the uniform DC prediction value from
+// *dst (dst[0]) and overwrite the width x height block in-place.
 #define CFL_PREDICT_lbd(arch, width, height)                                   \
   void cfl_predict_lbd_##width##x##height##_##arch(                            \
       const int16_t *pred_buf_q3, uint8_t *dst, int dst_stride, int alpha_q3); \
diff --git a/av1/encoder/intra_mode_search.c b/av1/encoder/intra_mode_search.c
index d0e0afceaf..8257129178 100644
--- a/av1/encoder/intra_mode_search.c
+++ b/av1/encoder/intra_mode_search.c
@@ -16,6 +16,8 @@
 #include <stdint.h>
 #include <string.h>

+#include "config/aom_config.h"
+
 #include "aom_dsp/aom_dsp_common.h"
 #include "av1/common/av1_common_int.h"
 #include "av1/common/cfl.h"
@@ -216,18 +218,16 @@ static double intra_rd_variance_factor(const AV1_COMP *cpi, MACROBLOCK *x,
  * \ingroup intra_mode_search
  * \callergraph
  * This function loops through all filter_intra modes to find the best one.
+ * Outlined with AOM_NOINLINE to keep the filter-intra loop out of hot callers.
  *
  * \return Returns 1 if a new filter_intra mode is selected; 0 otherwise.
  */
-static int rd_pick_filter_intra_sby(const AV1_COMP *const cpi, MACROBLOCK *x,
-                                    int *rate, int *rate_tokenonly,
-                                    int64_t *distortion, uint8_t *skippable,
-                                    BLOCK_SIZE bsize, int mode_cost,
-                                    PREDICTION_MODE best_mode_so_far,
-                                    int64_t *best_rd, int64_t *best_model_rd,
-                                    PICK_MODE_CONTEXT *ctx) {
-  // Skip the evaluation of filter intra modes.
-  if (cpi->sf.intra_sf.prune_filter_intra_level == 2) return 0;
+static AOM_NOINLINE int rd_pick_filter_intra_sby(
+    const AV1_COMP *const cpi, MACROBLOCK *x, int *rate, int *rate_tokenonly,
+    int64_t *distortion, uint8_t *skippable, BLOCK_SIZE bsize, int mode_cost,
+    PREDICTION_MODE best_mode_so_far, int64_t *best_rd, int64_t *best_model_rd,
+    PICK_MODE_CONTEXT *ctx) {
+  assert(cpi->sf.intra_sf.prune_filter_intra_level != 2);

   MACROBLOCKD *const xd = &x->e_mbd;
   MB_MODE_INFO *mbmi = xd->mi[0];
@@ -235,7 +235,6 @@ static int rd_pick_filter_intra_sby(const AV1_COMP *const cpi, MACROBLOCK *x,
   FILTER_INTRA_MODE mode;
   TX_SIZE best_tx_size = TX_8X8;
   FILTER_INTRA_MODE_INFO filter_intra_mode_info;
-  uint8_t best_tx_type_map[MAX_MIB_SIZE * MAX_MIB_SIZE];
   av1_zero(filter_intra_mode_info);
   mbmi->filter_intra_mode_info.use_filter_intra = 1;
   mbmi->mode = DC_PRED;
@@ -275,7 +274,8 @@ static int rd_pick_filter_intra_sby(const AV1_COMP *const cpi, MACROBLOCK *x,
     this_rd = RDCOST(x->rdmult, this_rate, tokenonly_rd_stats.dist);

     // Visual quality adjustment based on recon vs source variance.
-    if ((cpi->oxcf.mode == ALLINTRA) && (this_rd != INT64_MAX)) {
+    if ((cpi->oxcf.mode == ALLINTRA) &&
+        (INTRA_RD_VAR_THRESH(cpi->oxcf.speed) > 0) && (this_rd != INT64_MAX)) {
       this_rd = (int64_t)(this_rd * intra_rd_variance_factor(cpi, x, bsize));
     }

@@ -288,7 +288,7 @@ static int rd_pick_filter_intra_sby(const AV1_COMP *const cpi, MACROBLOCK *x,
       *best_rd = this_rd;
       best_tx_size = mbmi->tx_size;
       filter_intra_mode_info = mbmi->filter_intra_mode_info;
-      av1_copy_array(best_tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
+      av1_copy_tx_type_map(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
       *rate = this_rate;
       *rate_tokenonly = tokenonly_rd_stats.rate;
       *distortion = tokenonly_rd_stats.dist;
@@ -301,7 +301,6 @@ static int rd_pick_filter_intra_sby(const AV1_COMP *const cpi, MACROBLOCK *x,
     mbmi->mode = DC_PRED;
     mbmi->tx_size = best_tx_size;
     mbmi->filter_intra_mode_info = filter_intra_mode_info;
-    av1_copy_array(ctx->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
     return 1;
   } else {
     return 0;
@@ -390,22 +389,26 @@ void av1_count_colors_highbd(const uint8_t *src8, int stride, int rows,
 bool av1_count_colors_with_threshold(const uint8_t *src, int stride, int rows,
                                      int cols, int num_colors_threshold,
                                      int *num_colors) {
-  bool has_color[1 << 8] = { false };
-  *num_colors = 0;
-
+  if (rows <= 0 || cols <= 0) {
+    *num_colors = 0;
+    return true;
+  }
+  uint8_t has_color[1 << 8] = { 0 };
+  int count = 0;
   for (int r = 0; r < rows; ++r) {
+    const uint8_t *const row = src + (ptrdiff_t)r * stride;
     for (int c = 0; c < cols; ++c) {
-      const int this_val = src[r * stride + c];
+      const uint8_t this_val = row[c];
       if (!has_color[this_val]) {
-        has_color[this_val] = true;
-        (*num_colors)++;
-        if (*num_colors > num_colors_threshold) {
-          // We're over the threshold, so we can exit early
+        has_color[this_val] = 1;
+        if (++count > num_colors_threshold) {
+          *num_colors = count;
           return false;
         }
       }
     }
   }
+  *num_colors = count;
   return true;
 }

@@ -458,13 +461,24 @@ static inline int prune_intra_y_mode(int64_t this_model_rd,
                                      int64_t top_intra_model_rd[],
                                      int max_model_cnt_allowed,
                                      int model_rd_index_for_pruning) {
-  for (int i = 0; i < max_model_cnt_allowed; i++) {
-    if (this_model_rd < top_intra_model_rd[i]) {
-      for (int j = max_model_cnt_allowed - 1; j > i; j--) {
-        top_intra_model_rd[j] = top_intra_model_rd[j - 1];
+  static_assert(TOP_INTRA_MODEL_COUNT == 4, "");
+  assert(max_model_cnt_allowed > 0 &&
+         max_model_cnt_allowed <= TOP_INTRA_MODEL_COUNT);
+  if (this_model_rd < top_intra_model_rd[max_model_cnt_allowed - 1]) {
+    for (int i = 0; i < max_model_cnt_allowed; i++) {
+      if (this_model_rd < top_intra_model_rd[i]) {
+        if (i <= 2 && max_model_cnt_allowed >= 4) {
+          top_intra_model_rd[3] = top_intra_model_rd[2];
+        }
+        if (i <= 1 && max_model_cnt_allowed >= 3) {
+          top_intra_model_rd[2] = top_intra_model_rd[1];
+        }
+        if (i == 0 && max_model_cnt_allowed >= 2) {
+          top_intra_model_rd[1] = top_intra_model_rd[0];
+        }
+        top_intra_model_rd[i] = this_model_rd;
+        break;
       }
-      top_intra_model_rd[i] = this_model_rd;
-      break;
     }
   }
   if (this_model_rd > top_intra_model_rd[model_rd_index_for_pruning]) return 1;
@@ -583,11 +597,9 @@ static void cfl_idx_to_sign_and_alpha(int cfl_idx, CFL_SIGN_TYPE *cfl_sign,
   }
 }

-static int64_t cfl_compute_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
-                              int plane, TX_SIZE tx_size,
-                              BLOCK_SIZE plane_bsize, int cfl_idx,
-                              int fast_mode, RD_STATS *rd_stats) {
-  assert(IMPLIES(fast_mode, rd_stats == NULL));
+static int64_t cfl_compute_rd_fast(const AV1_COMP *const cpi, MACROBLOCK *x,
+                                   int plane, TX_SIZE tx_size,
+                                   BLOCK_SIZE plane_bsize, int cfl_idx) {
   const AV1_COMMON *const cm = &cpi->common;
   MACROBLOCKD *const xd = &x->e_mbd;
   MB_MODE_INFO *const mbmi = xd->mi[0];
@@ -595,24 +607,16 @@ static int64_t cfl_compute_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
   CFL_SIGN_TYPE cfl_sign;
   int cfl_alpha;
   cfl_idx_to_sign_and_alpha(cfl_idx, &cfl_sign, &cfl_alpha);
-  // We conly build CFL for a given plane, the other plane's sign is dummy
+  // We only build CFL for a given plane, the other plane's sign is dummy.
   int dummy_sign = CFL_SIGN_NEG;
   const int8_t orig_cfl_alpha_signs = mbmi->cfl_alpha_signs;
   const uint8_t orig_cfl_alpha_idx = mbmi->cfl_alpha_idx;
   mbmi->cfl_alpha_signs =
       PLANE_SIGN_TO_JOINT_SIGN(cfl_plane, cfl_sign, dummy_sign);
   mbmi->cfl_alpha_idx = (cfl_alpha << CFL_ALPHABET_SIZE_LOG2) + cfl_alpha;
-  int64_t cfl_cost;
-  if (fast_mode) {
-    cfl_cost = intra_model_rd(cm, x, plane, plane_bsize, tx_size,
-                              /*use_hadamard=*/0, cpi->do_border_pad);
-  } else {
-    av1_init_rd_stats(rd_stats);
-    av1_txfm_rd_in_plane(x, cpi, rd_stats, INT64_MAX, 0, plane, plane_bsize,
-                         tx_size, FTXS_NONE);
-    av1_rd_cost_update(x->rdmult, rd_stats);
-    cfl_cost = rd_stats->rdcost;
-  }
+  const int64_t cfl_cost =
+      intra_model_rd(cm, x, plane, plane_bsize, tx_size, /*use_hadamard=*/0,
+                     cpi->do_border_pad);
   mbmi->cfl_alpha_signs = orig_cfl_alpha_signs;
   mbmi->cfl_alpha_idx = orig_cfl_alpha_idx;
   return cfl_cost;
@@ -620,34 +624,86 @@ static int64_t cfl_compute_rd(const AV1_COMP *const cpi, MACROBLOCK *x,

 static const int cfl_dir_ls[2] = { 1, -1 };

+// cfl_get_predict_lbd_fn() is generated by RTCD only when
+// !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER.
+#if !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER
+static int cfl_pick_plane_parameter_lbd(const AV1_COMP *const cpi,
+                                        MACROBLOCK *x, int plane,
+                                        cfl_predict_lbd_fn predict_lbd,
+                                        TxfmParam *txfm_param) {
+  assert(plane == AOM_PLANE_U || plane == AOM_PLANE_V);
+  MACROBLOCKD *const xd = &x->e_mbd;
+  MB_MODE_INFO *const mbmi = xd->mi[0];
+  assert(mbmi->uv_mode == UV_CFL_PRED && xd->bd == 8);
+  const TX_SIZE tx_size = txfm_param->tx_size;
+  struct macroblock_plane *const p = &x->plane[plane];
+  uint8_t *const dst = xd->plane[plane].dst.buf;
+  const int dst_stride = xd->plane[plane].dst.stride;
+  const uint8_t *const src = p->src.buf;
+  const int src_stride = p->src.stride;
+  const int txbw = tx_size_wide[tx_size];
+  const int txbh = tx_size_high[tx_size];
+  const int n_coeffs = tx_size_2d[tx_size];
+  const int8_t orig_cfl_alpha_signs = mbmi->cfl_alpha_signs;
+  const uint8_t orig_cfl_alpha_idx = mbmi->cfl_alpha_idx;
+  mbmi->cfl_alpha_signs = PLANE_SIGN_TO_JOINT_SIGN(get_cfl_pred_type(plane),
+                                                   CFL_SIGN_ZERO, CFL_SIGN_NEG);
+  mbmi->cfl_alpha_idx = 0;
+  av1_predict_intra_block_facade(&cpi->common, xd, plane, 0, 0, tx_size);
+  const uint8_t dc_val = dst[0];
+  mbmi->cfl_alpha_signs = orig_cfl_alpha_signs;
+  mbmi->cfl_alpha_idx = orig_cfl_alpha_idx;
+  aom_subtract_block(txbh, txbw, p->src_diff, txbw, src, src_stride, dst,
+                     dst_stride);
+  av1_lowbd_fwd_txfm(p->src_diff, p->coeff, txbw, txfm_param);
+  int64_t best_cfl_cost = aom_satd(p->coeff, n_coeffs);
+  int est_best_cfl_idx = CFL_INDEX_ZERO;
+  assert(xd->cfl.are_parameters_computed);
+  for (int si = 0; si < 2; ++si) {
+    const int dir = cfl_dir_ls[si];
+    for (int i = 1; i <= CFL_INDEX_ZERO; ++i) {
+      const int alpha_q3 = dir * i;
+      // Contract: all cfl_predict_lbd implementations broadcast *dst.
+      dst[0] = dc_val;
+      predict_lbd(xd->cfl.ac_buf_q3, dst, dst_stride, alpha_q3);
+      aom_subtract_block(txbh, txbw, p->src_diff, txbw, src, src_stride, dst,
+                         dst_stride);
+      av1_lowbd_fwd_txfm(p->src_diff, p->coeff, txbw, txfm_param);
+      const int64_t cfl_cost = aom_satd(p->coeff, n_coeffs);
+      if (cfl_cost < best_cfl_cost) {
+        best_cfl_cost = cfl_cost;
+        est_best_cfl_idx = CFL_INDEX_ZERO + alpha_q3;
+      } else {
+        break;
+      }
+    }
+  }
+  return est_best_cfl_idx;
+}
+#endif  // !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER
+
 // If cfl_search_range is CFL_MAGS_SIZE, return zero. Otherwise return the index
 // of the best alpha found using intra_model_rd().
 static int cfl_pick_plane_parameter(const AV1_COMP *const cpi, MACROBLOCK *x,
                                     int plane, TX_SIZE tx_size,
+                                    BLOCK_SIZE plane_bsize,
                                     int cfl_search_range) {
   assert(cfl_search_range >= 1 && cfl_search_range <= CFL_MAGS_SIZE);
+  assert(x->e_mbd.mi[0]->uv_mode == UV_CFL_PRED);

   if (cfl_search_range == CFL_MAGS_SIZE) return CFL_INDEX_ZERO;

-  const MACROBLOCKD *const xd = &x->e_mbd;
-  const MB_MODE_INFO *const mbmi = xd->mi[0];
-  assert(mbmi->uv_mode == UV_CFL_PRED);
-  const MACROBLOCKD_PLANE *pd = &xd->plane[plane];
-  const BLOCK_SIZE plane_bsize =
-      get_plane_block_size(mbmi->bsize, pd->subsampling_x, pd->subsampling_y);
-
   int est_best_cfl_idx = CFL_INDEX_ZERO;
-  int fast_mode = 1;
   int start_cfl_idx = CFL_INDEX_ZERO;
-  int64_t best_cfl_cost = cfl_compute_rd(cpi, x, plane, tx_size, plane_bsize,
-                                         start_cfl_idx, fast_mode, NULL);
+  int64_t best_cfl_cost =
+      cfl_compute_rd_fast(cpi, x, plane, tx_size, plane_bsize, start_cfl_idx);
   for (int si = 0; si < 2; ++si) {
     const int dir = cfl_dir_ls[si];
     for (int i = 1; i < CFL_MAGS_SIZE; ++i) {
       int cfl_idx = start_cfl_idx + dir * i;
       if (cfl_idx < 0 || cfl_idx >= CFL_MAGS_SIZE) break;
-      int64_t cfl_cost = cfl_compute_rd(cpi, x, plane, tx_size, plane_bsize,
-                                        cfl_idx, fast_mode, NULL);
+      int64_t cfl_cost =
+          cfl_compute_rd_fast(cpi, x, plane, tx_size, plane_bsize, cfl_idx);
       if (cfl_cost < best_cfl_cost) {
         best_cfl_cost = cfl_cost;
         est_best_cfl_idx = cfl_idx;
@@ -665,11 +721,32 @@ static inline void set_invalid_cfl_parameters(uint8_t *best_cfl_alpha_idx,
   *best_cfl_alpha_signs = 0;
 }

+static void cfl_eval_plane_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
+                              int plane, TX_SIZE tx_size,
+                              BLOCK_SIZE plane_bsize, int cfl_idx,
+                              RD_STATS *rd_stats) {
+  MB_MODE_INFO *const mbmi = x->e_mbd.mi[0];
+  const int cfl_plane = get_cfl_pred_type(plane);
+  CFL_SIGN_TYPE cfl_sign;
+  int cfl_alpha;
+  cfl_idx_to_sign_and_alpha(cfl_idx, &cfl_sign, &cfl_alpha);
+  const int8_t orig_cfl_alpha_signs = mbmi->cfl_alpha_signs;
+  const uint8_t orig_cfl_alpha_idx = mbmi->cfl_alpha_idx;
+  mbmi->cfl_alpha_signs =
+      PLANE_SIGN_TO_JOINT_SIGN(cfl_plane, cfl_sign, CFL_SIGN_NEG);
+  mbmi->cfl_alpha_idx = (cfl_alpha << CFL_ALPHABET_SIZE_LOG2) + cfl_alpha;
+  av1_init_rd_stats(rd_stats);
+  av1_txfm_rd_in_plane(x, cpi, rd_stats, INT64_MAX, 0, plane, plane_bsize,
+                       tx_size, FTXS_NONE);
+  mbmi->cfl_alpha_signs = orig_cfl_alpha_signs;
+  mbmi->cfl_alpha_idx = orig_cfl_alpha_idx;
+}
+
 static void cfl_pick_plane_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
                               int plane, TX_SIZE tx_size, int cfl_search_range,
                               RD_STATS cfl_rd_arr[CFL_MAGS_SIZE],
-                              int est_best_cfl_idx) {
-  assert(cfl_search_range >= 1 && cfl_search_range <= CFL_MAGS_SIZE);
+                              int est_best_cfl_idx, int *idx_lo, int *idx_hi) {
+  assert(cfl_search_range >= 2 && cfl_search_range <= CFL_MAGS_SIZE);
   const MACROBLOCKD *const xd = &x->e_mbd;
   const MB_MODE_INFO *const mbmi = xd->mi[0];
   assert(mbmi->uv_mode == UV_CFL_PRED);
@@ -677,26 +754,79 @@ static void cfl_pick_plane_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
   const BLOCK_SIZE plane_bsize =
       get_plane_block_size(mbmi->bsize, pd->subsampling_x, pd->subsampling_y);

-  for (int cfl_idx = 0; cfl_idx < CFL_MAGS_SIZE; ++cfl_idx) {
-    av1_invalid_rd_stats(&cfl_rd_arr[cfl_idx]);
-  }
-
-  int fast_mode = 0;
-  int start_cfl_idx = est_best_cfl_idx;
-  cfl_compute_rd(cpi, x, plane, tx_size, plane_bsize, start_cfl_idx, fast_mode,
-                 &cfl_rd_arr[start_cfl_idx]);
-
-  if (cfl_search_range == 1) return;
+  const int start_cfl_idx = est_best_cfl_idx;
+  *idx_lo = AOMMAX(0, start_cfl_idx - (cfl_search_range - 1));
+  *idx_hi = AOMMIN(CFL_MAGS_SIZE - 1, start_cfl_idx + (cfl_search_range - 1));
+  cfl_eval_plane_rd(cpi, x, plane, tx_size, plane_bsize, start_cfl_idx,
+                    &cfl_rd_arr[start_cfl_idx]);

   for (int si = 0; si < 2; ++si) {
     const int dir = cfl_dir_ls[si];
     for (int i = 1; i < cfl_search_range; ++i) {
       int cfl_idx = start_cfl_idx + dir * i;
       if (cfl_idx < 0 || cfl_idx >= CFL_MAGS_SIZE) break;
-      cfl_compute_rd(cpi, x, plane, tx_size, plane_bsize, cfl_idx, fast_mode,
-                     &cfl_rd_arr[cfl_idx]);
+      cfl_eval_plane_rd(cpi, x, plane, tx_size, plane_bsize, cfl_idx,
+                        &cfl_rd_arr[cfl_idx]);
+    }
+  }
+}
+
+// Outlined with AOM_NOINLINE so cfl_rd_pick_alpha keeps a small stack frame
+// and code footprint on the cfl_search_range == 1 fast path.
+static AOM_NOINLINE int cfl_rd_pick_alpha_multi(
+    MACROBLOCK *const x, const AV1_COMP *const cpi, TX_SIZE tx_size,
+    int64_t ref_best_rd, int cfl_search_range, int est_best_cfl_idx_u,
+    int est_best_cfl_idx_v, RD_STATS *best_rd_stats,
+    uint8_t *best_cfl_alpha_idx, int8_t *best_cfl_alpha_signs) {
+  const ModeCosts *mode_costs = &x->mode_costs;
+  RD_STATS cfl_rd_arr_u[CFL_MAGS_SIZE];
+  RD_STATS cfl_rd_arr_v[CFL_MAGS_SIZE];
+  MACROBLOCKD *const xd = &x->e_mbd;
+  int u_lo, u_hi, v_lo, v_hi;
+  cfl_pick_plane_rd(cpi, x, 1, tx_size, cfl_search_range, cfl_rd_arr_u,
+                    est_best_cfl_idx_u, &u_lo, &u_hi);
+  cfl_pick_plane_rd(cpi, x, 2, tx_size, cfl_search_range, cfl_rd_arr_v,
+                    est_best_cfl_idx_v, &v_lo, &v_hi);
+
+  clear_cfl_dc_pred_cache_flags(&xd->cfl);
+
+  for (int ui = u_lo; ui <= u_hi; ++ui) {
+    if (cfl_rd_arr_u[ui].rate == INT_MAX) continue;
+    int cfl_alpha_u;
+    CFL_SIGN_TYPE cfl_sign_u;
+    cfl_idx_to_sign_and_alpha(ui, &cfl_sign_u, &cfl_alpha_u);
+    for (int vi = v_lo; vi <= v_hi; ++vi) {
+      if (cfl_rd_arr_v[vi].rate == INT_MAX) continue;
+      int cfl_alpha_v;
+      CFL_SIGN_TYPE cfl_sign_v;
+      cfl_idx_to_sign_and_alpha(vi, &cfl_sign_v, &cfl_alpha_v);
+      // cfl_sign_u == CFL_SIGN_ZERO && cfl_sign_v == CFL_SIGN_ZERO is not a
+      // valid parameter for CFL
+      if (cfl_sign_u == CFL_SIGN_ZERO && cfl_sign_v == CFL_SIGN_ZERO) continue;
+      int joint_sign = cfl_sign_u * CFL_SIGNS + cfl_sign_v - 1;
+      RD_STATS rd_stats = cfl_rd_arr_u[ui];
+      av1_merge_rd_stats(&rd_stats, &cfl_rd_arr_v[vi]);
+      if (rd_stats.rate != INT_MAX) {
+        rd_stats.rate +=
+            mode_costs->cfl_cost[joint_sign][CFL_PRED_U][cfl_alpha_u];
+        rd_stats.rate +=
+            mode_costs->cfl_cost[joint_sign][CFL_PRED_V][cfl_alpha_v];
+      }
+      av1_rd_cost_update(x->rdmult, &rd_stats);
+      if (rd_stats.rdcost < best_rd_stats->rdcost) {
+        *best_rd_stats = rd_stats;
+        *best_cfl_alpha_idx =
+            (cfl_alpha_u << CFL_ALPHABET_SIZE_LOG2) + cfl_alpha_v;
+        *best_cfl_alpha_signs = joint_sign;
+      }
     }
   }
+  if (best_rd_stats->rdcost >= ref_best_rd) {
+    av1_invalid_rd_stats(best_rd_stats);
+    set_invalid_cfl_parameters(best_cfl_alpha_idx, best_cfl_alpha_signs);
+    return 0;
+  }
+  return 1;
 }

 /*!\brief Pick the optimal parameters for Chroma to Luma (CFL) component
@@ -726,17 +856,18 @@ static void cfl_pick_plane_rd(const AV1_COMP *const cpi, MACROBLOCK *x,
  * \param[out]   best_cfl_alpha_idx     Best CFL alpha index
  * \param[out]   best_cfl_alpha_signs   Best CFL joint signs
  *
+ * Outlined with AOM_NOINLINE to prevent code bloat in chroma mode search.
  */
-static int cfl_rd_pick_alpha(MACROBLOCK *const x, const AV1_COMP *const cpi,
-                             TX_SIZE tx_size, int64_t ref_best_rd,
-                             int cfl_search_range, RD_STATS *best_rd_stats,
-                             uint8_t *best_cfl_alpha_idx,
-                             int8_t *best_cfl_alpha_signs) {
+static AOM_NOINLINE int cfl_rd_pick_alpha(
+    MACROBLOCK *const x, const AV1_COMP *const cpi, TX_SIZE tx_size,
+    int64_t ref_best_rd, int cfl_search_range, RD_STATS *best_rd_stats,
+    uint8_t *best_cfl_alpha_idx, int8_t *best_cfl_alpha_signs) {
   assert(cfl_search_range >= 1 && cfl_search_range <= CFL_MAGS_SIZE);
   const ModeCosts *mode_costs = &x->mode_costs;
-  RD_STATS cfl_rd_arr_u[CFL_MAGS_SIZE];
-  RD_STATS cfl_rd_arr_v[CFL_MAGS_SIZE];
   MACROBLOCKD *const xd = &x->e_mbd;
+  MB_MODE_INFO *const mbmi = xd->mi[0];
+  const BLOCK_SIZE plane_bsize = get_plane_block_size(
+      mbmi->bsize, xd->plane[1].subsampling_x, xd->plane[1].subsampling_y);
   int est_best_cfl_idx_u, est_best_cfl_idx_v;

   av1_invalid_rd_stats(best_rd_stats);
@@ -746,10 +877,39 @@ static int cfl_rd_pick_alpha(MACROBLOCK *const x, const AV1_COMP *const cpi,
   // returning to avoid the unintentional usage of cached dc pred data.
   xd->cfl.use_dc_pred_cache = true;
   // Evaluate alpha parameter of each chroma plane.
-  est_best_cfl_idx_u =
-      cfl_pick_plane_parameter(cpi, x, 1, tx_size, cfl_search_range);
-  est_best_cfl_idx_v =
-      cfl_pick_plane_parameter(cpi, x, 2, tx_size, cfl_search_range);
+  // cfl_get_predict_lbd_fn() is generated by RTCD only when
+  // !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER.
+#if !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER
+  cfl_predict_lbd_fn predict_lbd = NULL;
+  if (cfl_search_range < CFL_MAGS_SIZE && !is_cur_buf_hbd(xd) &&
+      !xd->lossless[mbmi->segment_id] &&
+      plane_bsize == txsize_to_bsize[tx_size] &&
+      !mbmi->palette_mode_info.palette_size[1] && xd->mb_to_bottom_edge >= 0 &&
+      xd->mb_to_right_edge >= 0 &&
+      (!cpi->do_border_pad ||
+       (x->pix_to_bottom_edge >= 0 && x->pix_to_right_edge >= 0))) {
+    predict_lbd = cfl_get_predict_lbd_fn(tx_size);
+  }
+  if (predict_lbd != NULL) {
+    TxfmParam txfm_param;
+    txfm_param.tx_type = DCT_DCT;
+    txfm_param.tx_size = tx_size;
+    txfm_param.lossless = 0;
+    txfm_param.bd = 8;
+    txfm_param.is_hbd = 0;
+    txfm_param.tx_set_type = EXT_TX_SET_ALL16;
+    est_best_cfl_idx_u =
+        cfl_pick_plane_parameter_lbd(cpi, x, 1, predict_lbd, &txfm_param);
+    est_best_cfl_idx_v =
+        cfl_pick_plane_parameter_lbd(cpi, x, 2, predict_lbd, &txfm_param);
+  } else
+#endif  // !CONFIG_REALTIME_ONLY || CONFIG_AV1_DECODER
+  {
+    est_best_cfl_idx_u = cfl_pick_plane_parameter(
+        cpi, x, 1, tx_size, plane_bsize, cfl_search_range);
+    est_best_cfl_idx_v = cfl_pick_plane_parameter(
+        cpi, x, 2, tx_size, plane_bsize, cfl_search_range);
+  }

   if (cfl_search_range == 1) {
     // For cfl_search_range=1, further refinement of alpha is not enabled. Hence
@@ -763,14 +923,15 @@ static int cfl_rd_pick_alpha(MACROBLOCK *const x, const AV1_COMP *const cpi,

     int cfl_alpha_u, cfl_alpha_v;
     CFL_SIGN_TYPE cfl_sign_u, cfl_sign_v;
-    const MB_MODE_INFO *mbmi = xd->mi[0];
     cfl_idx_to_sign_and_alpha(est_best_cfl_idx_u, &cfl_sign_u, &cfl_alpha_u);
     cfl_idx_to_sign_and_alpha(est_best_cfl_idx_v, &cfl_sign_v, &cfl_alpha_v);
     const int joint_sign = cfl_sign_u * CFL_SIGNS + cfl_sign_v - 1;
     // Compute alpha and mode signaling rate.
-    const int rate_overhead =
+    const int cfl_rate =
         mode_costs->cfl_cost[joint_sign][CFL_PRED_U][cfl_alpha_u] +
-        mode_costs->cfl_cost[joint_sign][CFL_PRED_V][cfl_alpha_v] +
+        mode_costs->cfl_cost[joint_sign][CFL_PRED_V][cfl_alpha_v];
+    const int rate_overhead =
+        cfl_rate +
         mode_costs
             ->intra_uv_mode_cost[is_cfl_allowed(xd)][mbmi->mode][UV_CFL_PRED];
     // Skip the CfL mode evaluation if the RD cost derived using the rate needed
@@ -780,56 +941,42 @@ static int cfl_rd_pick_alpha(MACROBLOCK *const x, const AV1_COMP *const cpi,
       clear_cfl_dc_pred_cache_flags(&xd->cfl);
       return 0;
     }
-  }
-
-  // Compute the rd cost of each chroma plane using the alpha parameters which
-  // were already evaluated.
-  cfl_pick_plane_rd(cpi, x, 1, tx_size, cfl_search_range, cfl_rd_arr_u,
-                    est_best_cfl_idx_u);
-  cfl_pick_plane_rd(cpi, x, 2, tx_size, cfl_search_range, cfl_rd_arr_v,
-                    est_best_cfl_idx_v);
-
-  clear_cfl_dc_pred_cache_flags(&xd->cfl);
-
-  for (int ui = 0; ui < CFL_MAGS_SIZE; ++ui) {
-    if (cfl_rd_arr_u[ui].rate == INT_MAX) continue;
-    int cfl_alpha_u;
-    CFL_SIGN_TYPE cfl_sign_u;
-    cfl_idx_to_sign_and_alpha(ui, &cfl_sign_u, &cfl_alpha_u);
-    for (int vi = 0; vi < CFL_MAGS_SIZE; ++vi) {
-      if (cfl_rd_arr_v[vi].rate == INT_MAX) continue;
-      int cfl_alpha_v;
-      CFL_SIGN_TYPE cfl_sign_v;
-      cfl_idx_to_sign_and_alpha(vi, &cfl_sign_v, &cfl_alpha_v);
-      // cfl_sign_u == CFL_SIGN_ZERO && cfl_sign_v == CFL_SIGN_ZERO is not a
-      // valid parameter for CFL
-      if (cfl_sign_u == CFL_SIGN_ZERO && cfl_sign_v == CFL_SIGN_ZERO) continue;
-      int joint_sign = cfl_sign_u * CFL_SIGNS + cfl_sign_v - 1;
-      RD_STATS rd_stats = cfl_rd_arr_u[ui];
-      av1_merge_rd_stats(&rd_stats, &cfl_rd_arr_v[vi]);
-      if (rd_stats.rate != INT_MAX) {
-        rd_stats.rate +=
-            mode_costs->cfl_cost[joint_sign][CFL_PRED_U][cfl_alpha_u];
-        rd_stats.rate +=
-            mode_costs->cfl_cost[joint_sign][CFL_PRED_V][cfl_alpha_v];
+    const int8_t orig_cfl_alpha_signs = mbmi->cfl_alpha_signs;
+    const uint8_t orig_cfl_alpha_idx = mbmi->cfl_alpha_idx;
+    mbmi->cfl_alpha_signs = joint_sign;
+    mbmi->cfl_alpha_idx = (cfl_alpha_u << CFL_ALPHABET_SIZE_LOG2) + cfl_alpha_v;
+    RD_STATS rd_u, rd_v;
+    av1_init_rd_stats(&rd_u);
+    av1_txfm_rd_in_plane(x, cpi, &rd_u, INT64_MAX, 0, 1, plane_bsize, tx_size,
+                         FTXS_NONE);
+    av1_init_rd_stats(&rd_v);
+    av1_txfm_rd_in_plane(x, cpi, &rd_v, INT64_MAX, 0, 2, plane_bsize, tx_size,
+                         FTXS_NONE);
+    clear_cfl_dc_pred_cache_flags(&xd->cfl);
+    mbmi->cfl_alpha_signs = orig_cfl_alpha_signs;
+    mbmi->cfl_alpha_idx = orig_cfl_alpha_idx;
+    if (rd_u.rate != INT_MAX && rd_v.rate != INT_MAX) {
+      av1_merge_rd_stats(&rd_u, &rd_v);
+      if (rd_u.rate != INT_MAX) {
+        rd_u.rate += cfl_rate;
       }
-      av1_rd_cost_update(x->rdmult, &rd_stats);
-      if (rd_stats.rdcost < best_rd_stats->rdcost) {
-        *best_rd_stats = rd_stats;
+      av1_rd_cost_update(x->rdmult, &rd_u);
+      if (rd_u.rdcost < ref_best_rd) {
+        *best_rd_stats = rd_u;
         *best_cfl_alpha_idx =
             (cfl_alpha_u << CFL_ALPHABET_SIZE_LOG2) + cfl_alpha_v;
         *best_cfl_alpha_signs = joint_sign;
+        return 1;
       }
     }
-  }
-  if (best_rd_stats->rdcost >= ref_best_rd) {
-    av1_invalid_rd_stats(best_rd_stats);
-    // Set invalid CFL parameters here since the rdcost is not better than
-    // ref_best_rd.
     set_invalid_cfl_parameters(best_cfl_alpha_idx, best_cfl_alpha_signs);
     return 0;
   }
-  return 1;
+
+  return cfl_rd_pick_alpha_multi(x, cpi, tx_size, ref_best_rd, cfl_search_range,
+                                 est_best_cfl_idx_u, est_best_cfl_idx_v,
+                                 best_rd_stats, best_cfl_alpha_idx,
+                                 best_cfl_alpha_signs);
 }

 static bool should_prune_chroma_smooth_pred_based_on_source_variance(
@@ -954,54 +1101,61 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
     xd->cfl.store_y = 0;
   }
 #endif  // !CONFIG_REALTIME_ONLY
-  IntraModeSearchState intra_search_state;
-  init_intra_mode_search_state(&intra_search_state);
+  uint8_t directional_mode_skip_mask[UV_INTRA_MODES] = { 0 };
+  bool dir_mode_skip_mask_ready = false;
   const CFL_ALLOWED_TYPE cfl_allowed = is_cfl_allowed(xd);
+  const SPEED_FEATURES *const sf = &cpi->sf;
+  const int *const uv_mode_cost =
+      mode_costs->intra_uv_mode_cost[cfl_allowed][mbmi->mode];
+
+  assert(mbmi->mode < INTRA_MODES);
+  uint32_t allowed_uv_mask =
+      sf->intra_sf.intra_uv_mode_mask[txsize_sqr_up_map[max_tx_size]];
+  if (sf->intra_sf.prune_chroma_modes_using_luma_winner) {
+    allowed_uv_mask &= av1_derived_chroma_intra_mode_used_flag[mbmi->mode];
+  }
+  if (!intra_mode_cfg->enable_diagonal_intra) {
+    allowed_uv_mask &=
+        ~((1U << UV_D45_PRED) | (1U << UV_D135_PRED) | (1U << UV_D113_PRED) |
+          (1U << UV_D157_PRED) | (1U << UV_D203_PRED) | (1U << UV_D67_PRED));
+  }
+  if (!intra_mode_cfg->enable_directional_intra) {
+    allowed_uv_mask &=
+        ~((1U << UV_V_PRED) | (1U << UV_H_PRED) | (1U << UV_D45_PRED) |
+          (1U << UV_D135_PRED) | (1U << UV_D113_PRED) | (1U << UV_D157_PRED) |
+          (1U << UV_D203_PRED) | (1U << UV_D67_PRED));
+  }
+  if (!intra_mode_cfg->enable_smooth_intra) {
+    allowed_uv_mask &= ~((1U << UV_SMOOTH_PRED) | (1U << UV_SMOOTH_V_PRED) |
+                         (1U << UV_SMOOTH_H_PRED));
+  }
+  if (!intra_mode_cfg->enable_paeth_intra) {
+    allowed_uv_mask &= ~(1U << UV_PAETH_PRED);
+  }
+  if (!cfl_allowed || !intra_mode_cfg->enable_cfl_intra) {
+    allowed_uv_mask &= ~(1U << UV_CFL_PRED);
+  }
+  const int use_angle_delta =
+      av1_use_angle_delta(mbmi->bsize) && intra_mode_cfg->enable_angle_delta;

   // Search through all non-palette modes.
   for (int mode_idx = 0; mode_idx < UV_INTRA_MODES; ++mode_idx) {
-    int this_rate;
-    RD_STATS tokenonly_rd_stats;
-    UV_PREDICTION_MODE uv_mode = uv_rd_search_mode_order[mode_idx];
+    const UV_PREDICTION_MODE uv_mode = uv_rd_search_mode_order[mode_idx];
+    if (!(allowed_uv_mask & (1U << uv_mode))) continue;

     // Skip the current mode evaluation if the RD cost derived using the mode
     // signaling rate exceeds the best_rd so far.
-    const int mode_rate =
-        mode_costs->intra_uv_mode_cost[cfl_allowed][mbmi->mode][uv_mode];
+    const int mode_rate = uv_mode_cost[uv_mode];
     if (RDCOST(x->rdmult, mode_rate, 0) > best_rd) continue;

-    PREDICTION_MODE intra_mode = get_uv_mode(uv_mode);
-    const int is_diagonal_mode = av1_is_diagonal_mode(intra_mode);
+    int this_rate;
+    RD_STATS tokenonly_rd_stats;
+    const PREDICTION_MODE intra_mode = get_uv_mode(uv_mode);
     const int is_directional_mode = av1_is_directional_mode(intra_mode);

-    if (is_diagonal_mode && !cpi->oxcf.intra_mode_cfg.enable_diagonal_intra)
-      continue;
-    if (is_directional_mode &&
-        !cpi->oxcf.intra_mode_cfg.enable_directional_intra)
-      continue;
-
-    if (!(cpi->sf.intra_sf.intra_uv_mode_mask[txsize_sqr_up_map[max_tx_size]] &
-          (1 << uv_mode)))
-      continue;
-    if (!intra_mode_cfg->enable_smooth_intra && uv_mode >= UV_SMOOTH_PRED &&
-        uv_mode <= UV_SMOOTH_H_PRED)
-      continue;
-
-    if (!intra_mode_cfg->enable_paeth_intra && uv_mode == UV_PAETH_PRED)
-      continue;
-
-    assert(mbmi->mode < INTRA_MODES);
-    if (cpi->sf.intra_sf.prune_chroma_modes_using_luma_winner &&
-        !(av1_derived_chroma_intra_mode_used_flag[mbmi->mode] & (1 << uv_mode)))
-      continue;
-
     mbmi->uv_mode = uv_mode;
-
-    // Init variables for cfl and angle delta
-    const SPEED_FEATURES *sf = &cpi->sf;
     mbmi->angle_delta[PLANE_TYPE_UV] = 0;
     if (uv_mode == UV_CFL_PRED) {
-      if (!cfl_allowed || !intra_mode_cfg->enable_cfl_intra) continue;
       assert(!is_directional_mode);
 #if !CONFIG_REALTIME_ONLY
       if (defer_cfl_y) {
@@ -1015,10 +1169,9 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
                              &mbmi->cfl_alpha_idx, &mbmi->cfl_alpha_signs)) {
         continue;
       }
-    } else if (is_directional_mode && av1_use_angle_delta(mbmi->bsize) &&
-               intra_mode_cfg->enable_angle_delta) {
+    } else if (is_directional_mode && use_angle_delta) {
       if (sf->intra_sf.chroma_intra_pruning_with_hog &&
-          !intra_search_state.dir_mode_skip_mask_ready) {
+          !dir_mode_skip_mask_ready) {
         static const float thresh[2][4] = {
           { -1.2f, 0.0f, 0.0f, 1.2f },    // Interframe
           { -1.2f, -1.2f, -0.6f, 0.4f },  // Intraframe
@@ -1029,17 +1182,15 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
             x, bsize, cm->seq_params->sb_size,
             thresh[is_intra_frame]
                   [sf->intra_sf.chroma_intra_pruning_with_hog - 1],
-            intra_search_state.directional_mode_skip_mask, is_chroma);
-        intra_search_state.dir_mode_skip_mask_ready = 1;
+            directional_mode_skip_mask, is_chroma);
+        dir_mode_skip_mask_ready = true;
       }
-      if (intra_search_state.directional_mode_skip_mask[uv_mode]) {
+      if (directional_mode_skip_mask[uv_mode]) {
         continue;
       }

       // Search through angle delta
-      const int rate_overhead =
-          mode_costs->intra_uv_mode_cost[cfl_allowed][mbmi->mode][uv_mode];
-      if (!rd_pick_intra_angle_sbuv(cpi, x, bsize, rate_overhead, best_rd,
+      if (!rd_pick_intra_angle_sbuv(cpi, x, bsize, mode_rate, best_rd,
                                     &this_rate, &tokenonly_rd_stats))
         continue;
     } else {
@@ -1053,10 +1204,8 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
         continue;
       }
     }
-    const int mode_cost =
-        mode_costs->intra_uv_mode_cost[cfl_allowed][mbmi->mode][uv_mode];
     this_rate = tokenonly_rd_stats.rate +
-                intra_mode_info_cost_uv(cpi, x, mbmi, bsize, mode_cost);
+                intra_mode_info_cost_uv(cpi, x, mbmi, bsize, mode_rate);
     this_rd = RDCOST(x->rdmult, this_rate, tokenonly_rd_stats.dist);

 #if CONFIG_AV1_HIGHBITDEPTH
@@ -1144,7 +1293,7 @@ int av1_search_palette_mode(IntraModeSearchState *intra_search_state,
     return skippable;
   }

-  av1_copy_array(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
+  av1_copy_tx_type_map(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
   memcpy(color_map, best_palette_color_map,
          rows * cols * sizeof(best_palette_color_map[0]));

@@ -1229,7 +1378,7 @@ void av1_search_palette_mode_luma(const AV1_COMP *cpi, MACROBLOCK *x,
     return;
   }

-  av1_copy_array(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
+  av1_copy_tx_type_map(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
   memcpy(color_map, best_palette_color_map,
          rows * cols * sizeof(best_palette_color_map[0]));

@@ -1291,7 +1440,7 @@ static inline int intra_block_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
     *rate_tokenonly = this_rate_tokenonly;
     *distortion = rd_stats.dist;
     *skippable = rd_stats.skip_txfm;
-    av1_copy_array(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
+    av1_copy_tx_type_map(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
     return 1;
   }
   return 0;
@@ -1321,7 +1470,7 @@ static inline void handle_filter_intra_mode(const AV1_COMP *cpi, MACROBLOCK *x,
   TX_SIZE best_tx_size = mbmi->tx_size;
   FILTER_INTRA_MODE best_fi_mode = FILTER_DC_PRED;
   uint8_t best_tx_type_map[MAX_MIB_SIZE * MAX_MIB_SIZE];
-  av1_copy_array(best_tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
+  av1_copy_tx_type_map(best_tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
   mbmi->filter_intra_mode_info.use_filter_intra = 1;
   for (FILTER_INTRA_MODE fi_mode = FILTER_DC_PRED; fi_mode < FILTER_INTRA_MODES;
        ++fi_mode) {
@@ -1339,7 +1488,7 @@ static inline void handle_filter_intra_mode(const AV1_COMP *cpi, MACROBLOCK *x,
     }
     if (this_rd_tmp < best_rd_so_far) {
       best_tx_size = mbmi->tx_size;
-      av1_copy_array(best_tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
+      av1_copy_tx_type_map(best_tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
       best_fi_mode = fi_mode;
       *rd_stats_y = rd_stats_y_fi;
       filter_intra_selected_flag = 1;
@@ -1348,7 +1497,7 @@ static inline void handle_filter_intra_mode(const AV1_COMP *cpi, MACROBLOCK *x,
   }

   mbmi->tx_size = best_tx_size;
-  av1_copy_array(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);
+  av1_copy_tx_type_map(xd->tx_type_map, best_tx_type_map, ctx->num_4x4_blk);

   if (filter_intra_selected_flag) {
     mbmi->filter_intra_mode_info.use_filter_intra = 1;
@@ -1644,10 +1793,53 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
     }
   }

+  const TX_SIZE tx_size = AOMMIN(TX_32X32, max_txsize_lookup[bsize]);
+  const int reorder_delta_angle =
+      intra_sf->prune_luma_odd_delta_angles_in_intra != 0;
+  const int base_model_rd_idx = intra_sf->top_intra_model_count_allowed - 1;
+  static_assert(INTRA_MODES <= 16, "");
+  assert(mbmi->bsize == bsize && !mbmi->use_intrabc);
+  uint16_t reduce_model_rd_idx_mask = 0;
+  if (intra_sf->adapt_top_model_rd_count_using_neighbors &&
+      base_model_rd_idx > 0) {
+    // Precomputes get_model_rd_index_for_pruning() per mode: OR neighbor
+    // mismatches when qindex <= 127, AND above; 0xFFFF marks inter neighbors.
+    const uint16_t left_mismatch_mask =
+        xd->left_available ? (xd->left_mbmi->mode < INTRA_MODES
+                                  ? (uint16_t)~(1u << xd->left_mbmi->mode)
+                                  : 0xFFFFu)
+                           : 0;
+    const uint16_t above_mismatch_mask =
+        xd->up_available ? (xd->above_mbmi->mode < INTRA_MODES
+                                ? (uint16_t)~(1u << xd->above_mbmi->mode)
+                                : 0xFFFFu)
+                         : 0;
+    reduce_model_rd_idx_mask = (x->qindex <= 127)
+                                   ? (left_mismatch_mask | above_mismatch_mask)
+                                   : (left_mismatch_mask & above_mismatch_mask);
+  }
+  const int base_non_dc_cost =
+      av1_allow_intrabc(&cpi->common) ? x->mode_costs.intrabc_cost[0] : 0;
+  int dc_extra_cost = base_non_dc_cost;
+  if (av1_allow_palette(cpi->common.features.allow_screen_content_tools,
+                        bsize)) {
+    dc_extra_cost +=
+        x->mode_costs.palette_y_mode_cost[av1_get_palette_bsize_ctx(bsize)]
+                                         [av1_get_palette_mode_ctx(xd)][0];
+  }
+  if (av1_filter_intra_allowed_bsize(&cpi->common, bsize)) {
+    dc_extra_cost += x->mode_costs.filter_intra_cost[bsize][0];
+  }
+  const int use_angle_delta_bsize = av1_use_angle_delta(bsize);
+  const int use_var_factor = (cpi->oxcf.mode == ALLINTRA) &&
+                             (INTRA_RD_VAR_THRESH(cpi->oxcf.speed) > 0);
+
   for (int mode_idx = INTRA_MODE_START; mode_idx < max_mode_idx; ++mode_idx) {
-    set_y_mode_and_delta_angle(mode_idx, mbmi,
-                               intra_sf->prune_luma_odd_delta_angles_in_intra);
-    if (!(allowed_mode_mask & (1 << mbmi->mode))) continue;
+    // Update mbmi for every mode_idx (do not skip disabled angle groups) so
+    // mbmi->angle_delta[PLANE_TYPE_Y] at loop exit matches max_mode_idx - 1.
+    set_y_mode_and_delta_angle(mode_idx, mbmi, reorder_delta_angle);
+    const PREDICTION_MODE mode = mbmi->mode;
+    if (!(allowed_mode_mask & (1 << mode))) continue;

     RD_STATS this_rd_stats;
     int this_rate, this_rate_tokenonly, s;
@@ -1656,17 +1848,15 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,

     if ((luma_delta_angle & 1) &&
         prune_luma_odd_delta_angles_using_rd_cost(
-            mbmi, intra_modes_rd_cost[mbmi->mode], best_rd,
-            intra_sf->prune_luma_odd_delta_angles_in_intra))
+            mbmi, intra_modes_rd_cost[mode], best_rd, reorder_delta_angle))
       continue;

-    const TX_SIZE tx_size = AOMMIN(TX_32X32, max_txsize_lookup[bsize]);
     const int64_t this_model_rd =
         intra_model_rd(&cpi->common, x, 0, bsize, tx_size, /*use_hadamard=*/1,
                        cpi->do_border_pad);

     const int model_rd_index_for_pruning =
-        get_model_rd_index_for_pruning(x, intra_sf);
+        base_model_rd_idx - ((reduce_model_rd_idx_mask >> mode) & 1);

     if (prune_intra_y_mode(this_model_rd, &best_model_rd, top_intra_model_rd,
                            intra_sf->top_intra_model_count_allowed,
@@ -1684,18 +1874,28 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,

     if (this_rate_tokenonly == INT_MAX) continue;

-    this_rate =
-        this_rd_stats.rate +
-        intra_mode_info_cost_y(cpi, x, mbmi, bsize, bmode_costs[mbmi->mode], 0);
+    int mode_info_cost = bmode_costs[mode];
+    if (mode == DC_PRED) {
+      mode_info_cost += dc_extra_cost;
+    } else {
+      mode_info_cost += base_non_dc_cost;
+      if (use_angle_delta_bsize && av1_is_directional_mode(mode)) {
+        mode_info_cost +=
+            x->mode_costs.angle_delta_cost[mode - V_PRED]
+                                          [MAX_ANGLE_DELTA + luma_delta_angle];
+      }
+    }
+    assert(mode_info_cost ==
+           intra_mode_info_cost_y(cpi, x, mbmi, bsize, bmode_costs[mode], 0));
+    this_rate = this_rd_stats.rate + mode_info_cost;
     this_rd = RDCOST(x->rdmult, this_rate, this_distortion);

     // Visual quality adjustment based on recon vs source variance.
-    if ((cpi->oxcf.mode == ALLINTRA) && (this_rd != INT64_MAX)) {
+    if (use_var_factor && (this_rd != INT64_MAX)) {
       this_rd = (int64_t)(this_rd * intra_rd_variance_factor(cpi, x, bsize));
     }

-    intra_modes_rd_cost[mbmi->mode][luma_delta_angle + MAX_ANGLE_DELTA + 1] =
-        this_rd;
+    intra_modes_rd_cost[mode][luma_delta_angle + MAX_ANGLE_DELTA + 1] = this_rd;

     // Collect mode stats for multiwinner mode processing
     const int txfm_search_done = 1;
@@ -1716,7 +1916,7 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
       *rate_tokenonly = this_rate_tokenonly;
       *distortion = this_distortion;
       *skippable = s;
-      av1_copy_array(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
+      av1_copy_tx_type_map(ctx->tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
     }
   }

@@ -1728,8 +1928,10 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
                                   &beat_best_rd, ctx, ctx->tx_type_map);
   }

-  // Searches filter_intra
-  if (beat_best_rd && av1_filter_intra_allowed_bsize(&cpi->common, bsize)) {
+  // Searches filter_intra. The caller-side prune_filter_intra_level != 2 guard
+  // avoids calling out-of-line rd_pick_filter_intra_sby() when disabled.
+  if (beat_best_rd && cpi->sf.intra_sf.prune_filter_intra_level != 2 &&
+      av1_filter_intra_allowed_bsize(&cpi->common, bsize)) {
     if (rd_pick_filter_intra_sby(cpi, x, rate, rate_tokenonly, distortion,
                                  skippable, bsize, bmode_costs[DC_PRED],
                                  best_mbmi.mode, &best_rd, &best_model_rd,
@@ -1826,7 +2028,7 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
     }
   }
   *mbmi = best_mbmi;
-  av1_copy_array(xd->tx_type_map, ctx->tx_type_map, ctx->num_4x4_blk);
+  av1_copy_tx_type_map(xd->tx_type_map, ctx->tx_type_map, ctx->num_4x4_blk);
   return best_rd;
 }

diff --git a/av1/encoder/intra_mode_search_utils.h b/av1/encoder/intra_mode_search_utils.h
index 68059e9e79..b444b5d365 100644
--- a/av1/encoder/intra_mode_search_utils.h
+++ b/av1/encoder/intra_mode_search_utils.h
@@ -21,6 +21,7 @@
 #include <stdbool.h>
 #include <stddef.h>
 #include <stdint.h>
+#include <string.h>

 #include "config/aom_config.h"
 #include "config/aom_dsp_rtcd.h"
@@ -424,13 +425,13 @@ static inline void produce_gradients_for_sb(AV1_COMP *cpi, MACROBLOCK *x,
 }

 // Reuses the pixel level gradient data generated at superblock level for block
-// level histogram computation.
-static inline void generate_hog_using_gradient_cache(const MACROBLOCK *x,
+// level histogram computation. Returns false if all gradients in the block are
+// zero.
+static inline bool generate_hog_using_gradient_cache(const MACROBLOCK *x,
                                                      int rows, int cols,
                                                      BLOCK_SIZE sb_size,
                                                      PLANE_TYPE plane,
                                                      float *hist) {
-  float total = 0.1f;
   const int ss_x = x->e_mbd.plane[plane].subsampling_x;
   const int ss_y = x->e_mbd.plane[plane].subsampling_y;
   const int sb_width = block_size_wide[sb_size] >> ss_x;
@@ -446,31 +447,68 @@ static inline void generate_hog_using_gradient_cache(const MACROBLOCK *x,
                                                 plane * MAX_SB_SQUARE +
                                                 block_offset_in_grad_cache;

-  // Accumulate cached gradients in integers first, using bin HOG_BINS as a
-  // sentinel bucket for dx == 0 so the inner loop is branchless.
-  uint32_t int_hist[HOG_BINS + 1] = { 0 };
+  const int num_cols = cols - 2;
+  if (rows <= 2 || num_cols <= 0) return false;
+  // Accumulate cached gradients across two separate 132-byte banks (staying
+  // below Clang's 256-byte inline-memset threshold) to break read-modify-write
+  // dependencies, using bin HOG_BINS as a sentinel bucket for dx == 0 so the
+  // inner loop is branchless.
+  uint32_t int_hist0[HOG_BINS + 1] = { 0 };
+  uint32_t int_hist1[HOG_BINS + 1] = { 0 };
+  const int even_cols = num_cols & ~1;
   for (int r = 1; r < rows - 1; ++r) {
-    const PixelLevelGradientInfo *const row_info = grad_info_blk + r * sb_width;
-    for (int c = 1; c < cols - 1; ++c) {
-      const uint16_t abs_dx_abs_dy_sum = row_info[c].abs_dx_abs_dy_sum;
-      if (!abs_dx_abs_dy_sum) continue;
-      total += abs_dx_abs_dy_sum;
-      const uint8_t idx = (uint8_t)row_info[c].hist_bin_idx;
-      assert(idx <= HOG_BINS);
-      int_hist[idx] += abs_dx_abs_dy_sum;
+    const PixelLevelGradientInfo *p = grad_info_blk + r * sb_width + 1;
+    const PixelLevelGradientInfo *const p_end = p + even_cols;
+    while (p < p_end) {
+      const uint8_t b0 = (uint8_t)p[0].hist_bin_idx;
+      const uint8_t b1 = (uint8_t)p[1].hist_bin_idx;
+      assert(b0 <= HOG_BINS && b1 <= HOG_BINS);
+      int_hist0[b0] += p[0].abs_dx_abs_dy_sum;
+      int_hist1[b1] += p[1].abs_dx_abs_dy_sum;
+      p += 2;
+    }
+    if (num_cols & 1) {
+      const uint8_t b0 = (uint8_t)p[0].hist_bin_idx;
+      assert(b0 <= HOG_BINS);
+      int_hist0[b0] += p[0].abs_dx_abs_dy_sum;
     }
   }

-  const uint32_t dx_zero_half = int_hist[HOG_BINS] >> 1;
-  int_hist[0] += dx_zero_half;
-  int_hist[HOG_BINS - 1] += dx_zero_half;
+  const uint32_t dx_zero = int_hist0[HOG_BINS] + int_hist1[HOG_BINS];
+  uint32_t int_total = dx_zero;
   for (int b = 0; b < HOG_BINS; ++b) {
-    hist[b] = (float)int_hist[b];
+    const uint32_t v = int_hist0[b] + int_hist1[b];
+    int_hist0[b] = v;
+    int_total += v;
+  }
+  if (int_total == 0) return false;
+  float total;
+  if (UNLIKELY(int_total >= (1u << 24))) {
+    // Above 2^24 (binary32 exact integer limit), fall back to sequential
+    // row-by-row float32 accumulation (0.1f + ...) for both LBD and HBD.
+    total = 0.1f;
+    for (int r = 1; r < rows - 1; ++r) {
+      const PixelLevelGradientInfo *const row_info =
+          grad_info_blk + r * sb_width;
+      for (int c = 1; c < cols - 1; ++c) {
+        const uint16_t abs_dx_abs_dy_sum = row_info[c].abs_dx_abs_dy_sum;
+        if (abs_dx_abs_dy_sum) total += abs_dx_abs_dy_sum;
+      }
+    }
+  } else {
+    total = 0.1f + (float)int_total;
+  }
+  const uint32_t dx_zero_half = dx_zero >> 1;
+  int_hist0[0] += dx_zero_half;
+  int_hist0[HOG_BINS - 1] += dx_zero_half;
+  for (int b = 0; b < HOG_BINS; ++b) {
+    hist[b] = (float)int_hist0[b];
   }
   normalize_hog(total, hist);
+  return true;
 }

-static inline void collect_hog_data(const MACROBLOCK *x, BLOCK_SIZE bsize,
+static inline bool collect_hog_data(const MACROBLOCK *x, BLOCK_SIZE bsize,
                                     BLOCK_SIZE sb_size, int plane, float *hog) {
   const MACROBLOCKD *xd = &x->e_mbd;
   const struct macroblockd_plane *const pd = &xd->plane[plane];
@@ -484,12 +522,15 @@ static inline void collect_hog_data(const MACROBLOCK *x, BLOCK_SIZE bsize,
   const int cols =
       ((xd->mb_to_right_edge >= 0) ? bw : (xd->mb_to_right_edge >> 3) + bw) >>
       ss_x;
+  if (rows <= 2 || cols <= 2) return false;

   // If gradient data is already generated at SB level, reuse the cached data.
   // Otherwise, compute the data.
   if (x->is_sb_gradient_cached[plane]) {
-    generate_hog_using_gradient_cache(x, rows, cols, sb_size, plane, hog);
+    if (!generate_hog_using_gradient_cache(x, rows, cols, sb_size, plane, hog))
+      return false;
   } else {
+    memset(hog, 0, sizeof(*hog) * HOG_BINS);
     const uint8_t *src = x->plane[plane].src.buf;
     const int src_stride = x->plane[plane].src.stride;
     generate_hog(src, src_stride, rows, cols, hog, is_cur_buf_hbd(xd));
@@ -502,17 +543,32 @@ static inline void collect_hog_data(const MACROBLOCK *x, BLOCK_SIZE bsize,
       hog[b] *= scale;
     }
   }
+  return true;
 }

 static inline void prune_intra_mode_with_hog(
     const MACROBLOCK *x, BLOCK_SIZE bsize, BLOCK_SIZE sb_size, float th,
     uint8_t *directional_mode_skip_mask, int is_chroma) {
   const int plane = is_chroma ? AOM_PLANE_U : AOM_PLANE_Y;
-  float hist[HOG_BINS] = { 0.0f };
-  collect_hog_data(x, bsize, sb_size, plane, hist);
+  float hist[HOG_BINS];
+  if (!collect_hog_data(x, bsize, sb_size, plane, hist)) {
+    // Precomputed from av1_nn_output_prec_reduce(av1_intra_hog_model_bias, 8)
+    // for the all-zero HoG input vector; keep in sync with the model bias.
+    static const float kZeroHogScores[DIRECTIONAL_MODES] = {
+      231.0f / 512.0f,  356.0f / 512.0f,  -367.0f / 512.0f, -327.0f / 512.0f,
+      -307.0f / 512.0f, -231.0f / 512.0f, 29.0f / 512.0f,   -237.0f / 512.0f,
+    };
+    for (UV_PREDICTION_MODE uv_mode = UV_V_PRED; uv_mode <= UV_D67_PRED;
+         uv_mode++) {
+      if (kZeroHogScores[uv_mode - UV_V_PRED] <= th) {
+        directional_mode_skip_mask[uv_mode] = 1;
+      }
+    }
+    return;
+  }

   // Make prediction for each of the mode
-  float scores[DIRECTIONAL_MODES] = { 0.0f };
+  float scores[DIRECTIONAL_MODES];
   av1_nn_predict(hist, &av1_intra_hog_model_nnconfig, 1, scores);
   for (UV_PREDICTION_MODE uv_mode = UV_V_PRED; uv_mode <= UV_D67_PRED;
        uv_mode++) {
@@ -583,51 +639,51 @@ static inline int intra_mode_info_cost_y(const AV1_COMP *cpi,
   // Can only activate one mode.
   assert(((mbmi->mode != DC_PRED) + use_palette + use_intrabc +
           use_filter_intra) <= 1);
-  const int try_palette = av1_allow_palette(
-      cpi->common.features.allow_screen_content_tools, mbmi->bsize);
-  if (try_palette && mbmi->mode == DC_PRED) {
-    const MACROBLOCKD *xd = &x->e_mbd;
-    const int bsize_ctx = av1_get_palette_bsize_ctx(bsize);
-    const int mode_ctx = av1_get_palette_mode_ctx(xd);
-    total_rate +=
-        mode_costs->palette_y_mode_cost[bsize_ctx][mode_ctx][use_palette];
-    if (use_palette) {
-      const uint8_t *const color_map = xd->plane[0].color_index_map;
-      int block_width, block_height, rows, cols;
-      av1_get_block_dimensions(bsize, 0, xd, &block_width, &block_height, &rows,
-                               &cols);
-      const int plt_size = mbmi->palette_mode_info.palette_size[0];
-      int palette_mode_cost =
-          mode_costs
-              ->palette_y_size_cost[bsize_ctx][plt_size - PALETTE_MIN_SIZE] +
-          write_uniform_cost(plt_size, color_map[0]);
-      uint16_t color_cache[2 * PALETTE_MAX_SIZE];
-      const int n_cache = av1_get_palette_cache(xd, 0, color_cache);
-      palette_mode_cost +=
-          av1_palette_color_cost_y(&mbmi->palette_mode_info, color_cache,
-                                   n_cache, cpi->common.seq_params->bit_depth);
-      if (!discount_color_cost)
-        palette_mode_cost +=
-            av1_cost_color_map(x, 0, bsize, mbmi->tx_size, PALETTE_MAP);
-
-      total_rate += palette_mode_cost;
-    }
-  }
-  if (av1_filter_intra_allowed(&cpi->common, mbmi)) {
-    total_rate += mode_costs->filter_intra_cost[mbmi->bsize][use_filter_intra];
-    if (use_filter_intra) {
+  if (mbmi->mode == DC_PRED) {
+    if (av1_allow_palette(cpi->common.features.allow_screen_content_tools,
+                          mbmi->bsize)) {
+      const MACROBLOCKD *xd = &x->e_mbd;
+      const int bsize_ctx = av1_get_palette_bsize_ctx(bsize);
+      const int mode_ctx = av1_get_palette_mode_ctx(xd);
       total_rate +=
-          mode_costs->filter_intra_mode_cost[mbmi->filter_intra_mode_info
-                                                 .filter_intra_mode];
+          mode_costs->palette_y_mode_cost[bsize_ctx][mode_ctx][use_palette];
+      if (use_palette) {
+        const uint8_t *const color_map = xd->plane[0].color_index_map;
+        int block_width, block_height, rows, cols;
+        av1_get_block_dimensions(bsize, 0, xd, &block_width, &block_height,
+                                 &rows, &cols);
+        const int plt_size = mbmi->palette_mode_info.palette_size[0];
+        int palette_mode_cost =
+            mode_costs
+                ->palette_y_size_cost[bsize_ctx][plt_size - PALETTE_MIN_SIZE] +
+            write_uniform_cost(plt_size, color_map[0]);
+        uint16_t color_cache[2 * PALETTE_MAX_SIZE];
+        const int n_cache = av1_get_palette_cache(xd, 0, color_cache);
+        palette_mode_cost += av1_palette_color_cost_y(
+            &mbmi->palette_mode_info, color_cache, n_cache,
+            cpi->common.seq_params->bit_depth);
+        if (!discount_color_cost)
+          palette_mode_cost +=
+              av1_cost_color_map(x, 0, bsize, mbmi->tx_size, PALETTE_MAP);
+
+        total_rate += palette_mode_cost;
+      }
     }
-  }
-  if (av1_is_directional_mode(mbmi->mode)) {
-    if (av1_use_angle_delta(bsize)) {
+    if (!use_palette &&
+        av1_filter_intra_allowed_bsize(&cpi->common, mbmi->bsize)) {
       total_rate +=
-          mode_costs->angle_delta_cost[mbmi->mode - V_PRED]
-                                      [MAX_ANGLE_DELTA +
-                                       mbmi->angle_delta[PLANE_TYPE_Y]];
+          mode_costs->filter_intra_cost[mbmi->bsize][use_filter_intra];
+      if (use_filter_intra) {
+        total_rate +=
+            mode_costs->filter_intra_mode_cost[mbmi->filter_intra_mode_info
+                                                   .filter_intra_mode];
+      }
     }
+  } else if (av1_is_directional_mode(mbmi->mode) &&
+             av1_use_angle_delta(bsize)) {
+    total_rate += mode_costs->angle_delta_cost[mbmi->mode - V_PRED]
+                                              [MAX_ANGLE_DELTA +
+                                               mbmi->angle_delta[PLANE_TYPE_Y]];
   }
   if (av1_allow_intrabc(&cpi->common))
     total_rate += mode_costs->intrabc_cost[use_intrabc];
@@ -649,33 +705,34 @@ static inline int intra_mode_info_cost_uv(const AV1_COMP *cpi,
   // Can only activate one mode.
   assert(((uv_mode != UV_DC_PRED) + use_palette + mbmi->use_intrabc) <= 1);

-  const int try_palette = av1_allow_palette(
-      cpi->common.features.allow_screen_content_tools, mbmi->bsize);
-  if (try_palette && uv_mode == UV_DC_PRED) {
-    const PALETTE_MODE_INFO *pmi = &mbmi->palette_mode_info;
-    total_rate +=
-        mode_costs->palette_uv_mode_cost[pmi->palette_size[0] > 0][use_palette];
-    if (use_palette) {
-      const int bsize_ctx = av1_get_palette_bsize_ctx(bsize);
-      const int plt_size = pmi->palette_size[1];
-      const MACROBLOCKD *xd = &x->e_mbd;
-      const uint8_t *const color_map = xd->plane[1].color_index_map;
-      int palette_mode_cost =
+  if (uv_mode == UV_DC_PRED) {
+    if (av1_allow_palette(cpi->common.features.allow_screen_content_tools,
+                          mbmi->bsize)) {
+      const PALETTE_MODE_INFO *pmi = &mbmi->palette_mode_info;
+      total_rate +=
           mode_costs
-              ->palette_uv_size_cost[bsize_ctx][plt_size - PALETTE_MIN_SIZE] +
-          write_uniform_cost(plt_size, color_map[0]);
-      uint16_t color_cache[2 * PALETTE_MAX_SIZE];
-      const int n_cache = av1_get_palette_cache(xd, 1, color_cache);
-      palette_mode_cost += av1_palette_color_cost_uv(
-          pmi, color_cache, n_cache, cpi->common.seq_params->bit_depth);
-      palette_mode_cost +=
-          av1_cost_color_map(x, 1, bsize, mbmi->tx_size, PALETTE_MAP);
-      total_rate += palette_mode_cost;
+              ->palette_uv_mode_cost[pmi->palette_size[0] > 0][use_palette];
+      if (use_palette) {
+        const int bsize_ctx = av1_get_palette_bsize_ctx(bsize);
+        const int plt_size = pmi->palette_size[1];
+        const MACROBLOCKD *xd = &x->e_mbd;
+        const uint8_t *const color_map = xd->plane[1].color_index_map;
+        int palette_mode_cost =
+            mode_costs
+                ->palette_uv_size_cost[bsize_ctx][plt_size - PALETTE_MIN_SIZE] +
+            write_uniform_cost(plt_size, color_map[0]);
+        uint16_t color_cache[2 * PALETTE_MAX_SIZE];
+        const int n_cache = av1_get_palette_cache(xd, 1, color_cache);
+        palette_mode_cost += av1_palette_color_cost_uv(
+            pmi, color_cache, n_cache, cpi->common.seq_params->bit_depth);
+        palette_mode_cost +=
+            av1_cost_color_map(x, 1, bsize, mbmi->tx_size, PALETTE_MAP);
+        total_rate += palette_mode_cost;
+      }
     }
-  }
-  const PREDICTION_MODE intra_mode = get_uv_mode(uv_mode);
-  if (av1_is_directional_mode(intra_mode)) {
-    if (av1_use_angle_delta(bsize)) {
+  } else {
+    const PREDICTION_MODE intra_mode = get_uv_mode(uv_mode);
+    if (av1_is_directional_mode(intra_mode) && av1_use_angle_delta(bsize)) {
       total_rate +=
           mode_costs->angle_delta_cost[intra_mode - V_PRED]
                                       [mbmi->angle_delta[PLANE_TYPE_UV] +
@@ -792,7 +849,10 @@ static int64_t intra_model_rd(const AV1_COMMON *cm, MACROBLOCK *const x,
 static inline int model_intra_yrd_and_prune(const AV1_COMP *const cpi,
                                             MACROBLOCK *x, BLOCK_SIZE bsize,
                                             int64_t *best_model_rd) {
-  const TX_SIZE tx_size = AOMMIN(TX_32X32, max_txsize_lookup[bsize]);
+  // Explicit cast avoids GCC -Wextra warning between TX_SIZE enum and uint8_t
+  // array element in the conditional expression.
+  const TX_SIZE tx_size =
+      (TX_SIZE)AOMMIN((int)TX_32X32, (int)max_txsize_lookup[bsize]);
   const int plane = 0;
   const AV1_COMMON *cm = &cpi->common;
   const int64_t this_model_rd = intra_model_rd(
diff --git a/libs.doxy_template b/libs.doxy_template
index 34216b8535..697fc6b928 100644
--- a/libs.doxy_template
+++ b/libs.doxy_template
@@ -2036,7 +2036,7 @@ INCLUDE_FILE_PATTERNS  = *.h
 # In builds where CONFIG_REALTIME_ONLY is set some functions are #ifdefed out
 # which causes reference failures. Hence for doxygen we set it to 0 here.

-PREDEFINED             = CONFIG_REALTIME_ONLY=0
+PREDEFINED             = CONFIG_REALTIME_ONLY=0 AOM_NOINLINE:=

 # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
 # tag can be used to specify a list of macro names that should be expanded. The
diff --git a/test/cfl_test.cc b/test/cfl_test.cc
index 6002fd8162..fa3228a344 100644
--- a/test/cfl_test.cc
+++ b/test/cfl_test.cc
@@ -395,6 +395,70 @@ TEST_P(CFLPredictTest, PredictTest) {
     assert_eq<uint8_t>(chroma_pels, chroma_pels_ref, width, height);
   }
 }
+
+TEST_P(CFLPredictTest, PredictReadsOnlyFirstDcPixelTest) {
+  for (int it = 0; it < NUM_ITERATIONS; it++) {
+    randData(8);
+    if (it == 0) {
+      dc = 0x12;
+      for (int j = 0; j < height; j++) {
+        for (int i = 0; i < width; i++) {
+          chroma_pels_ref[j * CFL_BUF_LINE + i] = dc;
+        }
+      }
+    }
+    predict_ref(sub_luma_pels_ref, chroma_pels_ref, CFL_BUF_LINE, alpha_q3);
+
+    for (int j = 0; j < height; j++) {
+      for (int i = 0; i < width; i++) {
+        chroma_pels[j * CFL_BUF_LINE + i] = 0xA5;
+      }
+    }
+    chroma_pels[0] = dc;
+    predict(sub_luma_pels, chroma_pels, CFL_BUF_LINE, alpha_q3);
+    assert_eq<uint8_t>(chroma_pels, chroma_pels_ref, width, height);
+
+    for (int j = 0; j < height; j++) {
+      for (int i = 0; i < width; i++) {
+        chroma_pels[j * CFL_BUF_LINE + i] = 0xA5;
+      }
+    }
+    chroma_pels[0] = dc;
+    predict_ref(sub_luma_pels, chroma_pels, CFL_BUF_LINE, alpha_q3);
+    assert_eq<uint8_t>(chroma_pels, chroma_pels_ref, width, height);
+  }
+}
+
+TEST(CFLPredictCTest, PredictReadsOnlyFirstDcPixelTest) {
+  static constexpr TX_SIZE kCflTxSizes[] = {
+    TX_4X4,  TX_4X8,  TX_4X16,  TX_8X4,   TX_8X8,  TX_8X16,  TX_8X32,
+    TX_16X4, TX_16X8, TX_16X16, TX_16X32, TX_32X8, TX_32X16, TX_32X32,
+  };
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  uint8_t ref_buf[CFL_BUF_SQUARE] = { 0 };
+  uint8_t tst_buf[CFL_BUF_SQUARE] = { 0 };
+  int16_t ac_buf[CFL_BUF_SQUARE] = { 0 };
+  for (TX_SIZE tx_size : kCflTxSizes) {
+    const int width = tx_size_wide[tx_size];
+    const int height = tx_size_high[tx_size];
+    const cfl_predict_lbd_fn predict_c = cfl_get_predict_lbd_fn_c(tx_size);
+    const int alpha_q3 = rnd(33) - 16;
+    const uint8_t dc = 0x12;
+    for (int j = 0; j < height; j++) {
+      for (int i = 0; i < width; i++) {
+        ac_buf[j * CFL_BUF_LINE + i] =
+            static_cast<int16_t>((rnd.Rand16() % 4081) - 2040);
+        ref_buf[j * CFL_BUF_LINE + i] = dc;
+        tst_buf[j * CFL_BUF_LINE + i] = 0xA5;
+      }
+    }
+    tst_buf[0] = dc;
+    predict_c(ac_buf, ref_buf, CFL_BUF_LINE, alpha_q3);
+    predict_c(ac_buf, tst_buf, CFL_BUF_LINE, alpha_q3);
+    assert_eq<uint8_t>(tst_buf, ref_buf, width, height);
+  }
+}
+
 TEST_P(CFLPredictTest, DISABLED_PredictSpeedTest) {
   aom_usec_timer ref_timer;
   aom_usec_timer timer;
diff --git a/test/intra_hog_test.cc b/test/intra_hog_test.cc
index ea82e15817..558ff8e8fc 100644
--- a/test/intra_hog_test.cc
+++ b/test/intra_hog_test.cc
@@ -24,7 +24,10 @@
 #include "config/av1_rtcd.h"

 #include "aom_mem/aom_mem.h"
+#include "av1/common/blockd.h"
 #include "av1/encoder/block.h"
+#include "av1/encoder/intra_mode_search.h"
+#include "av1/encoder/intra_mode_search_utils.h"
 #include "test/acm_random.h"
 #include "test/register_state_check.h"
 #include "test/util.h"
@@ -509,4 +512,258 @@ INSTANTIATE_TEST_SUITE_P(
 #endif  // HAVE_NEON
 #endif  // CONFIG_AV1_HIGHBITDEPTH

+TEST(IntraModeSearchHelpersTest, ZeroHogScoresMatchNnPredict) {
+  float zero_hist[HOG_BINS] = { 0.0f };
+  float nn_scores[DIRECTIONAL_MODES] = { 0.0f };
+  av1_nn_predict(zero_hist, &av1_intra_hog_model_nnconfig, 1, nn_scores);
+
+  auto x = std::make_unique<MACROBLOCK>();
+  memset(x.get(), 0, sizeof(*x));
+  // Trigger the rows <= 2 zero-HoG fast path inside prune_intra_mode_with_hog.
+  x->e_mbd.mb_to_bottom_edge = -16;
+  x->e_mbd.mb_to_right_edge = 0;
+
+  for (int i = 0; i < DIRECTIONAL_MODES; ++i) {
+    const float s = nn_scores[i];
+    uint8_t skip_eq[UV_INTRA_MODES] = { 0 };
+    prune_intra_mode_with_hog(x.get(), BLOCK_4X4, BLOCK_64X64, s, skip_eq,
+                              /*is_chroma=*/0);
+    EXPECT_EQ(skip_eq[UV_V_PRED + i], 1) << "mode=" << i << " score=" << s;
+
+    uint8_t skip_below[UV_INTRA_MODES] = { 0 };
+    prune_intra_mode_with_hog(x.get(), BLOCK_4X4, BLOCK_64X64, s - 1e-4f,
+                              skip_below, /*is_chroma=*/0);
+    EXPECT_EQ(skip_below[UV_V_PRED + i], 0) << "mode=" << i << " score=" << s;
+  }
+}
+
+TEST(IntraModeSearchHelpersTest, CachedHogMatchesRefLbdAndHbd) {
+  ACMRandom rnd(ACMRandom::DeterministicSeed());
+  std::vector<PixelLevelGradientInfo> grad_buf(PLANE_TYPES * MAX_SB_SQUARE);
+  auto x = std::make_unique<MACROBLOCK>();
+  memset(x.get(), 0, sizeof(*x));
+  YV12_BUFFER_CONFIG yv12;
+  memset(&yv12, 0, sizeof(yv12));
+  x->pixel_gradient_info = grad_buf.data();
+  x->is_sb_gradient_cached[0] = 1;
+  x->e_mbd.bd = 8;
+  x->e_mbd.cur_buf = &yv12;
+
+  auto compute_ref_cached_hog = [&](int dim, float *hist_ref) {
+    uint32_t int_hist[HOG_BINS + 1] = { 0 };
+    float total = 0.1f;
+    for (int r = 1; r < dim - 1; ++r) {
+      for (int c = 1; c < dim - 1; ++c) {
+        const PixelLevelGradientInfo info = grad_buf[r * dim + c];
+        const uint16_t amp = info.abs_dx_abs_dy_sum;
+        if (amp == 0) continue;
+        total += amp;
+        int_hist[static_cast<uint8_t>(info.hist_bin_idx)] += amp;
+      }
+    }
+    const uint32_t dx_zero_half = int_hist[HOG_BINS] >> 1;
+    int_hist[0] += dx_zero_half;
+    int_hist[HOG_BINS - 1] += dx_zero_half;
+    for (int b = 0; b < HOG_BINS; ++b) {
+      hist_ref[b] = static_cast<float>(int_hist[b]) / total;
+    }
+  };
+
+  // 8-bit 64x64 and 128x128 random blocks plus a 128x128 [0, 0, 255, 255]
+  // max-gradient stripe pattern; cached path must match reference
+  // bit-for-bit.
+  for (const BLOCK_SIZE sb_size : { BLOCK_64X64, BLOCK_128X128 }) {
+    const int dim = block_size_wide[sb_size];
+    std::vector<uint8_t> src(dim * dim);
+    for (int pattern_idx = 0; pattern_idx < (sb_size == BLOCK_128X128 ? 2 : 1);
+         ++pattern_idx) {
+      if (pattern_idx == 0) {
+        for (int i = 0; i < dim * dim; ++i) src[i] = rnd.Rand8();
+      } else {
+        for (int r = 0; r < dim; ++r) {
+          for (int c = 0; c < dim; ++c) {
+            src[r * dim + c] = (c & 2) ? 255 : 0;
+          }
+        }
+      }
+      x->plane[PLANE_TYPE_Y].src.buf = src.data();
+      x->plane[PLANE_TYPE_Y].src.stride = dim;
+      av1_lowbd_compute_gradient_info_sb(x.get(), sb_size, PLANE_TYPE_Y);
+      float hist_cached[HOG_BINS] = { 0.0f };
+      float hist_ref_cache[HOG_BINS] = { 0.0f };
+      EXPECT_TRUE(generate_hog_using_gradient_cache(x.get(), dim, dim, sb_size,
+                                                    PLANE_TYPE_Y, hist_cached));
+      compute_ref_cached_hog(dim, hist_ref_cache);
+      EXPECT_EQ(std::memcmp(hist_cached, hist_ref_cache, sizeof(hist_cached)),
+                0)
+          << "dim=" << dim << " pattern=" << pattern_idx;
+      for (int b = 0; b < HOG_BINS; ++b) {
+        EXPECT_EQ(hist_cached[b], hist_ref_cache[b])
+            << "dim=" << dim << " pattern=" << pattern_idx << " bin=" << b;
+      }
+    }
+  }
+
+  // Exercise the 8-bit LBD int_total >= 2^24 sequential fallback directly
+  // using max 8-bit Sobel gradient magnitudes (1530 / 1529 => total > 2^24).
+  {
+    const int dim = 128;
+    std::fill(grad_buf.begin(), grad_buf.end(),
+              PixelLevelGradientInfo{ 0, 0, 0 });
+    for (int r = 1; r < dim - 1; ++r) {
+      for (int c = 1; c < dim - 1; ++c) {
+        grad_buf[r * dim + c].abs_dx_abs_dy_sum =
+            static_cast<uint16_t>(1530 - ((r + c) & 1));
+        grad_buf[r * dim + c].hist_bin_idx =
+            static_cast<int8_t>((r * 7 + c) % (HOG_BINS + 1));
+      }
+    }
+    float hist_cached[HOG_BINS] = { 0.0f };
+    float hist_ref_cache[HOG_BINS] = { 0.0f };
+    EXPECT_TRUE(generate_hog_using_gradient_cache(
+        x.get(), dim, dim, BLOCK_128X128, PLANE_TYPE_Y, hist_cached));
+    compute_ref_cached_hog(dim, hist_ref_cache);
+    EXPECT_EQ(std::memcmp(hist_cached, hist_ref_cache, sizeof(hist_cached)), 0);
+    for (int b = 0; b < HOG_BINS; ++b) {
+      EXPECT_EQ(hist_cached[b], hist_ref_cache[b]) << "lbd_2p24 bin=" << b;
+    }
+
+    // All-zero gradients return false.
+    std::fill(grad_buf.begin(), grad_buf.end(),
+              PixelLevelGradientInfo{ 0, 0, 0 });
+    EXPECT_FALSE(generate_hog_using_gradient_cache(
+        x.get(), dim, dim, BLOCK_128X128, PLANE_TYPE_Y, hist_cached));
+  }
+
+#if CONFIG_AV1_HIGHBITDEPTH
+  // 10-bit 64x64 (< 2^24) and 128x128 / 12-bit high-gradient blocks (where
+  // int_total >= 2^24): cached path must match reference bit-for-bit.
+  for (const int bd : { 10, 12 }) {
+    for (const BLOCK_SIZE sb_size : { BLOCK_64X64, BLOCK_128X128 }) {
+      const int dim = block_size_wide[sb_size];
+      const uint16_t max_val = static_cast<uint16_t>((1 << bd) - 1);
+      std::vector<uint16_t> src(dim * dim);
+      for (int r = 0; r < dim; ++r) {
+        for (int c = 0; c < dim; ++c) {
+          if (sb_size == BLOCK_64X64) {
+            src[r * dim + c] = static_cast<uint16_t>(rnd.Rand16() & max_val);
+          } else {
+            // High-contrast vertical stripes + diagonal modulation so Sobel
+            // sums exceed 2^24 on both 10-bit and 12-bit 128x128 blocks.
+            src[r * dim + c] = static_cast<uint16_t>(
+                (((c >> 1) + (r >> 2)) & 1) ? max_val : 0);
+          }
+        }
+      }
+      yv12.flags = YV12_FLAG_HIGHBITDEPTH;
+      x->e_mbd.bd = bd;
+      x->plane[PLANE_TYPE_Y].src.buf = CONVERT_TO_BYTEPTR(src.data());
+      x->plane[PLANE_TYPE_Y].src.stride = dim;
+      av1_highbd_compute_gradient_info_sb(x.get(), sb_size, PLANE_TYPE_Y);
+      float hist_cached[HOG_BINS] = { 0.0f };
+      float hist_ref_cache[HOG_BINS] = { 0.0f };
+      EXPECT_TRUE(generate_hog_using_gradient_cache(x.get(), dim, dim, sb_size,
+                                                    PLANE_TYPE_Y, hist_cached));
+      compute_ref_cached_hog(dim, hist_ref_cache);
+      EXPECT_EQ(std::memcmp(hist_cached, hist_ref_cache, sizeof(hist_cached)),
+                0)
+          << "bd=" << bd << " dim=" << dim;
+      for (int b = 0; b < HOG_BINS; ++b) {
+        EXPECT_EQ(hist_cached[b], hist_ref_cache[b])
+            << "bd=" << bd << " dim=" << dim << " bin=" << b;
+      }
+    }
+  }
+#endif  // CONFIG_AV1_HIGHBITDEPTH
+}
+
+TEST(IntraModeSearchHelpersTest, CountColorsWithThreshold) {
+  int num_colors = -1;
+  uint8_t dummy[1] = { 0 };
+  EXPECT_TRUE(av1_count_colors_with_threshold(dummy, 1, 0, 8, 0, &num_colors));
+  EXPECT_EQ(num_colors, 0);
+  EXPECT_TRUE(av1_count_colors_with_threshold(dummy, 1, 0, 8, -1, &num_colors));
+  EXPECT_EQ(num_colors, 0);
+  EXPECT_TRUE(av1_count_colors_with_threshold(dummy, 1, 8, 0, -1, &num_colors));
+  EXPECT_EQ(num_colors, 0);
+  EXPECT_FALSE(
+      av1_count_colors_with_threshold(dummy, 1, 1, 1, -1, &num_colors));
+  EXPECT_EQ(num_colors, 1);
+
+  // All 256 values across uint8_t has_color[256] with odd width and stride >
+  // cols, exercising threshold ==, threshold - 1, 256, and INT_MAX.
+  constexpr int kRows = 16;
+  constexpr int kCols = 17;
+  constexpr int kStride = 23;
+  std::vector<uint8_t> buf(kRows * kStride, 0);
+  int val = 0;
+  for (int r = 0; r < kRows; ++r) {
+    for (int c = 0; c < kCols; ++c) {
+      buf[r * kStride + c] = static_cast<uint8_t>(val & 255);
+      ++val;
+    }
+    for (int c = kCols; c < kStride; ++c) {
+      buf[r * kStride + c] = 0xAA;
+    }
+  }
+  EXPECT_TRUE(av1_count_colors_with_threshold(buf.data(), kStride, kRows, kCols,
+                                              256, &num_colors));
+  EXPECT_EQ(num_colors, 256);
+  EXPECT_TRUE(av1_count_colors_with_threshold(buf.data(), kStride, kRows, kCols,
+                                              INT_MAX, &num_colors));
+  EXPECT_EQ(num_colors, 256);
+  EXPECT_FALSE(av1_count_colors_with_threshold(buf.data(), kStride, kRows,
+                                               kCols, 255, &num_colors));
+  EXPECT_EQ(num_colors, 256);
+
+  // Subset with exact threshold boundary (5 distinct spread values: 0, 63,
+  // 64, 191, 255).
+  const uint8_t kFive[5] = { 0, 63, 64, 191, 255 };
+  for (int r = 0; r < 7; ++r) {
+    for (int c = 0; c < 9; ++c) {
+      buf[r * kStride + c] = kFive[(r * 3 + c) % 5];
+    }
+  }
+  EXPECT_TRUE(av1_count_colors_with_threshold(buf.data(), kStride, 7, 9, 5,
+                                              &num_colors));
+  EXPECT_EQ(num_colors, 5);
+  EXPECT_FALSE(av1_count_colors_with_threshold(buf.data(), kStride, 7, 9, 4,
+                                               &num_colors));
+  EXPECT_GT(num_colors, 4);
+}
+
+TEST(IntraModeSearchHelpersTest, BlockdCopyAndFillPow2) {
+  constexpr int kGuard = 16;
+  constexpr uint8_t kCanary = 0xA5;
+  for (int n = 1; n <= 1024; n <<= 1) {
+    std::vector<uint8_t> src(n);
+    for (int i = 0; i < n; ++i) src[i] = static_cast<uint8_t>((i * 37 + 13));
+    std::vector<uint8_t> dst_buf(2 * kGuard + n, kCanary);
+    av1_copy_tx_type_map(dst_buf.data() + kGuard, src.data(), n);
+    for (int g = 0; g < kGuard; ++g) {
+      ASSERT_EQ(dst_buf[g], kCanary) << "n=" << n << " lead g=" << g;
+      ASSERT_EQ(dst_buf[kGuard + n + g], kCanary)
+          << "n=" << n << " trail g=" << g;
+    }
+    for (int i = 0; i < n; ++i) {
+      ASSERT_EQ(dst_buf[kGuard + i], src[i]) << "n=" << n << " i=" << i;
+    }
+  }
+  for (int n = 1; n <= 32; n <<= 1) {
+    std::vector<ENTROPY_CONTEXT> dst_buf(2 * kGuard + n,
+                                         static_cast<ENTROPY_CONTEXT>(kCanary));
+    av1_fill_entropy_ctx_pow2(dst_buf.data() + kGuard, 0x3C, n);
+    for (int g = 0; g < kGuard; ++g) {
+      ASSERT_EQ(static_cast<uint8_t>(dst_buf[g]), kCanary)
+          << "n=" << n << " lead g=" << g;
+      ASSERT_EQ(static_cast<uint8_t>(dst_buf[kGuard + n + g]), kCanary)
+          << "n=" << n << " trail g=" << g;
+    }
+    for (int i = 0; i < n; ++i) {
+      ASSERT_EQ(static_cast<uint8_t>(dst_buf[kGuard + i]), 0x3C)
+          << "n=" << n << " i=" << i;
+    }
+  }
+}
+
 }  // namespace