Commit af5d96314b for aom

commit af5d96314b39db6f552da95ed2a8658de808d5c0
Author: Frank Galligan <fgalligan@google.com>
Date:   Thu Nov 26 05:20:32 2026 -0800

    intra_mode_search: reuse sby winner luma in CfL

    Avoid re-running luma intra prediction and forward/inverse transform
    in av1_rd_pick_intra_sbuv_mode() for CfL when the winning luma
    search already produced reconstructed luma pixels cleanly:

    - Add SbyCflState (x->sby_cfl) in MACROBLOCK tracking valid,
      use_cfl_eval, track, blk_row, blk_col, tx_size, tx_type, last_eob,
      and last_block_offset across av1_rd_pick_intra_mode_sb(),
      av1_rd_pick_intra_sby_mode(), and search_tx_type() / tx_search.c.
    - Gate tracking to the final winner_mode_count - 1 candidate, defer
      non-zero txb inverse transform / recon to av1_sby_cfl_finish_recon(),
      copy dqcoeff via sby_cfl_txb_finish() only when stored in
      dqcoeff_buf, rewrite eob == 0 tx_type_map entries upfront via
      av1_sby_cfl_rewrite_txk(), and defer CfL luma reconstruction in
      av1_rd_pick_intra_sbuv_mode() until UV_CFL_PRED survives rate pruning.

    Guarded by #if !CONFIG_REALTIME_ONLY (0-byte no-op when
    CONFIG_REALTIME_ONLY=1); SbyCflState adds 12 B to MACROBLOCK with zero
    heap allocations.

    Speed & size vs origin/main d91e90d7c8 (EPYC 7B13, Clang 21, bit-exact):
      -0.35% (1T) / -8.06% (8T) 1080p allintra; prior pre-rebase 1080p
      allintra: -0.71% (1T) / -1.35% (8T); --rt unaffected (bit-exact).
    Binary size (x86_64 -O3): libaom.a .text +2.0 KiB (+0.03%),
      .rodata +0.0 KiB (+0.00%); stripped aomenc +8.0 KiB (+0.08%).
    Memory (peak RSS, THP+ASLR off): 1080p allintra 1T -48 KiB (-0.13%),
      8T -2144 KiB (-5.63%); 720p good 1T +1136 KiB (+0.47%), rt 1T +1120
      KiB (+2.66%) (1-rep allocator boundary shift; zero heap allocs).

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

diff --git a/av1/encoder/block.h b/av1/encoder/block.h
index c4a34d9c4f..eb9dc1f2e8 100644
--- a/av1/encoder/block.h
+++ b/av1/encoder/block.h
@@ -881,6 +881,30 @@ typedef struct SetOffsetsLoc {

 /*!\endcond */

+#if !CONFIG_REALTIME_ONLY
+/*!\brief Luma state captured during WINNER_MODE_EVAL for CfL reuse. */
+typedef struct SbyCflState {
+  //! Non-zero while search_tx_type() is tracking the winner luma candidate.
+  uint8_t track;
+  //! Non-zero when captured last-txb state can be materialized in sbuv.
+  uint8_t valid;
+  //! Non-zero if any transformed block had eob == 0 and non-DCT tx_type.
+  uint8_t rewrote_txk;
+  //! Final luma txb transform type saved for deferred IDCT.
+  uint8_t last_tx_type;
+  //! Final luma txb transform size saved for deferred IDCT.
+  uint8_t last_tx_size;
+  //! Final luma txb MI row offset within the block.
+  uint8_t last_blk_row;
+  //! Final luma txb MI column offset within the block.
+  uint8_t last_blk_col;
+  //! Final luma txb end-of-block count saved for deferred IDCT.
+  uint16_t last_eob;
+  //! Final luma txb coefficient offset inside p->dqcoeff.
+  uint16_t last_block_offset;
+} SbyCflState;
+#endif  // !CONFIG_REALTIME_ONLY
+
 //! Maximum number of estimated RD Cost records for compound average.
 #define TOP_COMP_AVG_EST_RD_COUNT 5

@@ -1519,6 +1543,10 @@ typedef struct macroblock {
    *  right edge of the frame.
    */
   int pix_to_right_edge;
+#if !CONFIG_REALTIME_ONLY
+  /*! \brief State captured from WINNER_MODE_EVAL for CfL luma reuse. */
+  SbyCflState sby_cfl;
+#endif  // !CONFIG_REALTIME_ONLY
 } MACROBLOCK;
 #undef SINGLE_REF_MODES

diff --git a/av1/encoder/intra_mode_search.c b/av1/encoder/intra_mode_search.c
index 8655309900..d0e0afceaf 100644
--- a/av1/encoder/intra_mode_search.c
+++ b/av1/encoder/intra_mode_search.c
@@ -9,11 +9,14 @@
  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
  */

+#include <assert.h>
+#include <limits.h>
 #include <stdbool.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <string.h>

+#include "aom_dsp/aom_dsp_common.h"
 #include "av1/common/av1_common_int.h"
 #include "av1/common/cfl.h"
 #include "av1/common/reconintra.h"
@@ -843,6 +846,51 @@ static bool should_prune_chroma_smooth_pred_based_on_source_variance(
   return true;
 }

+#if !CONFIG_REALTIME_ONLY
+/*!\cond */
+// Keep CfL finish+store out of the av1_rd_pick_intra_sbuv_mode() loop.
+static AOM_NOINLINE void sby_cfl_materialize(MACROBLOCK *x, BLOCK_SIZE bsize,
+                                             TX_SIZE tx_size,
+                                             int reduced_tx_set_used) {
+  assert(x != NULL);
+  MACROBLOCKD *const xd = &x->e_mbd;
+  assert(!xd->mi[0]->skip_txfm);
+  assert((unsigned)bsize < BLOCK_SIZES_ALL);
+  assert((unsigned)tx_size < TX_SIZES_ALL);
+  if (x->sby_cfl.last_eob > 0) {
+    av1_sby_cfl_finish_recon(x, reduced_tx_set_used);
+  }
+  cfl_store_block(xd, bsize, tx_size);
+}
+
+// Keep out-of-line to avoid duplicating the guard at both sby winner sites.
+static AOM_NOINLINE bool sby_cfl_can_track(const AV1_COMP *cpi,
+                                           const MACROBLOCK *x,
+                                           const MB_MODE_INFO *mbmi) {
+  assert(cpi != NULL && x != NULL && mbmi != NULL);
+  const AV1_COMMON *const cm = &cpi->common;
+  const MACROBLOCKD *const xd = &x->e_mbd;
+  const TxfmSearchParams *const tp = &x->txfm_search_params;
+  // Require bit-exact equivalence between WINNER_MODE_EVAL search_tx_type()
+  // and av1_encode_intra_block_plane(): active CfL RDO, winner-mode trellis/
+  // quant settings (dequant_QTX[1] >= 8 matches qstep != 0), no border-pad,
+  // 8-bit non-lossless/non-skip, full in-frame edges, and non-palette mode.
+  const bool can_track =
+      !cpi->sf.rt_sf.use_nonrd_pick_mode && !is_stat_generation_stage(cpi) &&
+      store_cfl_required_rdo(cm, x) != CFL_DISALLOWED &&
+      tp->coeff_opt_thresholds[0] == UINT_MAX &&
+      tp->coeff_opt_thresholds[1] == UINT_MAX && tp->predict_dc_level == 0 &&
+      !cpi->do_border_pad && !is_cur_buf_hbd(xd) &&
+      !xd->lossless[mbmi->segment_id] && !x->seg_skip_block &&
+      x->plane[0].dequant_QTX[1] >= 8 && xd->mb_to_bottom_edge >= 0 &&
+      xd->mb_to_right_edge >= 0 && mbmi->palette_mode_info.palette_size[0] == 0;
+  assert(!can_track || (xd->bd == 8 && x->pix_to_bottom_edge >= 0 &&
+                        x->pix_to_right_edge >= 0));
+  return can_track;
+}
+/*!\endcond */
+#endif  // !CONFIG_REALTIME_ONLY
+
 int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
                                     int *rate, int *rate_tokenonly,
                                     int64_t *distortion, uint8_t *skippable,
@@ -851,6 +899,11 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
   MACROBLOCKD *xd = &x->e_mbd;
   MB_MODE_INFO *mbmi = xd->mi[0];
   assert(!is_inter_block(mbmi));
+#if !CONFIG_REALTIME_ONLY
+  const uint8_t sby_valid = x->sby_cfl.valid;
+  x->sby_cfl.valid = 0;
+#endif  // !CONFIG_REALTIME_ONLY
+  xd->cfl.store_y = 0;
   MB_MODE_INFO best_mbmi = *mbmi;
   int64_t best_rd = INT64_MAX, this_rd;
   const ModeCosts *mode_costs = &x->mode_costs;
@@ -867,6 +920,25 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
     return INT64_MAX;
   }

+#if !CONFIG_REALTIME_ONLY
+  // Rewrite eob == 0 tx_type_map entries upfront so last-txb IDCT and
+  // cfl_store_block() remain deferred until UV_CFL_PRED survives pruning.
+  if (sby_valid && x->sby_cfl.rewrote_txk) {
+    av1_sby_cfl_rewrite_txk(x);
+  }
+  // Only store reconstructed luma when there's chroma RDO. When there's no
+  // chroma RDO, the reconstructed luma will be stored in encode_superblock().
+  const bool need_cfl_y = store_cfl_required_rdo(cm, x) != CFL_DISALLOWED;
+  const bool defer_cfl_y = need_cfl_y && sby_valid;
+  // When defer_cfl_y is true, sby_cfl_materialize() finishes recon on entry.
+  if (need_cfl_y && !defer_cfl_y) {
+    xd->cfl.store_y = 1;
+    av1_encode_intra_block_plane(cpi, x, mbmi->bsize, AOM_PLANE_Y,
+                                 DRY_RUN_NORMAL,
+                                 cpi->optimize_seg_arr[mbmi->segment_id]);
+    xd->cfl.store_y = 0;
+  }
+#else
   // Only store reconstructed luma when there's chroma RDO. When there's no
   // chroma RDO, the reconstructed luma will be stored in encode_superblock().
   xd->cfl.store_y = store_cfl_required_rdo(cm, x);
@@ -881,6 +953,7 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
                                  cpi->optimize_seg_arr[mbmi->segment_id]);
     xd->cfl.store_y = 0;
   }
+#endif  // !CONFIG_REALTIME_ONLY
   IntraModeSearchState intra_search_state;
   init_intra_mode_search_state(&intra_search_state);
   const CFL_ALLOWED_TYPE cfl_allowed = is_cfl_allowed(xd);
@@ -930,6 +1003,12 @@ int64_t av1_rd_pick_intra_sbuv_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
     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) {
+        sby_cfl_materialize(x, mbmi->bsize, mbmi->tx_size,
+                            cm->features.reduced_tx_set_used);
+      }
+#endif  // !CONFIG_REALTIME_ONLY
       const TX_SIZE uv_tx_size = av1_get_tx_size(AOM_PLANE_U, xd);
       if (!cfl_rd_pick_alpha(x, cpi, uv_tx_size, best_rd,
                              sf->intra_sf.cfl_search_range, &tokenonly_rd_stats,
@@ -1465,6 +1544,10 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
   MACROBLOCKD *const xd = &x->e_mbd;
   MB_MODE_INFO *const mbmi = xd->mi[0];
   assert(!is_inter_block(mbmi));
+#if !CONFIG_REALTIME_ONLY
+  x->sby_cfl.valid = 0;
+  x->sby_cfl.track = 0;
+#endif  // !CONFIG_REALTIME_ONLY
   int64_t best_model_rd = INT64_MAX;
   uint8_t directional_mode_skip_mask[INTRA_MODES] = { 0 };
   // Flag to check rd of any intra mode is better than best_rd passed to this
@@ -1687,10 +1770,29 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
         // If previous searches use only the default tx type/no R-D optimization
         // of quantized coeffs, do an extra search for the best tx type/better
         // R-D optimization of quantized coeffs
+#if !CONFIG_REALTIME_ONLY
+        // Only the final candidate can preserve its pd->dst.buf luma recon into
+        // sbuv without being overwritten by a later candidate.
+        assert(!x->sby_cfl.valid);
+        x->sby_cfl.track = (mode_idx == x->winner_mode_count - 1)
+                               ? sby_cfl_can_track(cpi, x, mbmi)
+                               : 0;
+        x->sby_cfl.rewrote_txk = 0;
+#endif  // !CONFIG_REALTIME_ONLY
         if (intra_block_yrd(cpi, x, bsize, bmode_costs, &best_rd, rate,
                             rate_tokenonly, distortion, skippable, &best_mbmi,
-                            ctx))
+                            ctx)) {
           best_mode_idx = mode_idx;
+#if !CONFIG_REALTIME_ONLY
+        } else {
+          // Clear in case a losing final candidate set valid=1 before failing
+          // RD.
+          x->sby_cfl.valid = 0;
+#endif  // !CONFIG_REALTIME_ONLY
+        }
+#if !CONFIG_REALTIME_ONLY
+        x->sby_cfl.track = 0;
+#endif  // !CONFIG_REALTIME_ONLY
       }
     }
     // Copy color_map of palette mode for final winner mode
@@ -1708,8 +1810,19 @@ int64_t av1_rd_pick_intra_sby_mode(const AV1_COMP *const cpi, MACROBLOCK *x,
       // Set params for winner mode evaluation
       set_mode_eval_params(cpi, x, WINNER_MODE_EVAL);
       *mbmi = best_mbmi;
+#if !CONFIG_REALTIME_ONLY
+      x->sby_cfl.track = sby_cfl_can_track(cpi, x, mbmi);
+      x->sby_cfl.rewrote_txk = 0;
+      if (!intra_block_yrd(cpi, x, bsize, bmode_costs, &best_rd, rate,
+                           rate_tokenonly, distortion, skippable, &best_mbmi,
+                           ctx)) {
+        x->sby_cfl.valid = 0;
+      }
+      x->sby_cfl.track = 0;
+#else
       intra_block_yrd(cpi, x, bsize, bmode_costs, &best_rd, rate,
                       rate_tokenonly, distortion, skippable, &best_mbmi, ctx);
+#endif  // !CONFIG_REALTIME_ONLY
     }
   }
   *mbmi = best_mbmi;
diff --git a/av1/encoder/rdopt.c b/av1/encoder/rdopt.c
index 233e91cbf6..c9305df4e0 100644
--- a/av1/encoder/rdopt.c
+++ b/av1/encoder/rdopt.c
@@ -3804,6 +3804,12 @@ void av1_rd_pick_intra_mode_sb(const struct AV1_COMP *cpi, struct macroblock *x,
   } else {
     rd_cost->rate = INT_MAX;
   }
+#if !CONFIG_REALTIME_ONLY
+  // Ensure deferred sby state never survives past intra mode selection (e.g.
+  // when num_planes == 1 or intra_yrd >= best_rd skips
+  // av1_rd_pick_intra_sbuv_mode).
+  x->sby_cfl.valid = 0;
+#endif  // !CONFIG_REALTIME_ONLY

   if (rd_cost->rate != INT_MAX && rd_cost->rdcost < best_rd)
     best_rd = rd_cost->rdcost;
diff --git a/av1/encoder/tx_search.c b/av1/encoder/tx_search.c
index d12281c72a..61e211398e 100644
--- a/av1/encoder/tx_search.c
+++ b/av1/encoder/tx_search.c
@@ -11,11 +11,15 @@

 #include <assert.h>
 #include <inttypes.h>
+#include <stdbool.h>
 #include <stddef.h>
+#include <string.h>

 #include "config/aom_config.h"
 #include "config/av1_rtcd.h"

+#include "aom_dsp/aom_dsp_common.h"
+
 #include "av1/common/cfl.h"
 #include "av1/common/reconintra.h"
 #include "av1/encoder/block.h"
@@ -961,6 +965,12 @@ static inline void inverse_transform_block_facade(MACROBLOCK *const x,
                               dst_stride, eob, reduced_tx_set);
 }

+static inline bool is_non_last_txb(int blk_row, int blk_col,
+                                   BLOCK_SIZE plane_bsize, TX_SIZE tx_size) {
+  return blk_row + tx_size_high_unit[tx_size] < mi_size_high[plane_bsize] ||
+         blk_col + tx_size_wide_unit[tx_size] < mi_size_wide[plane_bsize];
+}
+
 static inline void recon_intra(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
                                int block, int blk_row, int blk_col,
                                BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
@@ -972,8 +982,7 @@ static inline void recon_intra(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
   MB_MODE_INFO *mbmi = xd->mi[0];
   const int is_inter = is_inter_block(mbmi);
   if (!is_inter && best_eob &&
-      (blk_row + tx_size_high_unit[tx_size] < mi_size_high[plane_bsize] ||
-       blk_col + tx_size_wide_unit[tx_size] < mi_size_wide[plane_bsize])) {
+      is_non_last_txb(blk_row, blk_col, plane_bsize, tx_size)) {
     // if the quantized coefficients are stored in the dqcoeff buffer, we don't
     // need to do transform and quantization again.
     if (do_quant) {
@@ -2128,6 +2137,39 @@ static inline bool palette_tries_idtx(const AV1_COMP *cpi, const MACROBLOCK *x,
          !txfm_cfg->use_intra_dct_only;
 }

+#if !CONFIG_REALTIME_ONLY
+// Capture the final winning luma txb state for deferred CfL reconstruction;
+// kept AOM_NOINLINE so cold memcpy/bookkeeping stays out of search_tx_type().
+static AOM_NOINLINE void sby_cfl_txb_finish(MACROBLOCK *x, int block,
+                                            int blk_row, int blk_col,
+                                            TX_SIZE tx_size, TX_TYPE tx_type,
+                                            uint16_t eob,
+                                            const tran_low_t *dqcoeff_src) {
+  assert(x != NULL);
+  assert((unsigned)tx_size < TX_SIZES_ALL);
+  assert((unsigned)tx_type < TX_TYPES);
+  assert(eob > 0);
+  struct macroblock_plane *const p = &x->plane[0];
+  const int block_offset = BLOCK_OFFSET(block);
+  const int n_coeffs = av1_get_max_eob(tx_size);
+  assert(block_offset >= 0 && block_offset + n_coeffs <= CFL_BUF_SQUARE);
+  assert((unsigned)blk_row < (CFL_BUF_LINE >> MI_SIZE_LOG2) &&
+         (unsigned)blk_col < (CFL_BUF_LINE >> MI_SIZE_LOG2));
+  assert(eob <= n_coeffs);
+  if (dqcoeff_src != NULL) {
+    assert(p->dqcoeff != dqcoeff_src);
+    memcpy(p->dqcoeff + block_offset, dqcoeff_src + block_offset,
+           (size_t)n_coeffs * sizeof(tran_low_t));
+  }
+  x->sby_cfl.last_tx_type = (uint8_t)tx_type;
+  x->sby_cfl.last_tx_size = (uint8_t)tx_size;
+  x->sby_cfl.last_blk_row = (uint8_t)blk_row;
+  x->sby_cfl.last_blk_col = (uint8_t)blk_col;
+  x->sby_cfl.last_eob = eob;
+  x->sby_cfl.last_block_offset = (uint16_t)block_offset;
+}
+#endif  // !CONFIG_REALTIME_ONLY
+
 // Search for the best transform type for a given transform block.
 // This function can be used for both inter and intra, both luma and chroma.
 // When precalc_sse >= 0, precalc_sse and precalc_sum hold the SSE and
@@ -2151,6 +2193,10 @@ static void search_tx_type(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
   struct macroblock_plane *const p = &x->plane[plane];
   tran_low_t *orig_dqcoeff = p->dqcoeff;
   tran_low_t *best_dqcoeff = x->dqcoeff_buf;
+#if !CONFIG_REALTIME_ONLY && !defined(NDEBUG)
+  assert(!(plane == 0 && !is_inter_block(mbmi) && x->sby_cfl.track) ||
+         BLOCK_OFFSET(block) + av1_get_max_eob(tx_size) <= CFL_BUF_SQUARE);
+#endif  // !CONFIG_REALTIME_ONLY && !defined(NDEBUG)
   const int tx_type_map_idx =
       plane ? 0 : blk_row * xd->tx_type_map_stride + blk_col;
   av1_invalid_rd_stats(best_rd_stats);
@@ -2219,6 +2265,9 @@ static void search_tx_type(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
     if (best_rd_stats->skip_txfm == 1) {
       const TX_TYPE tx_type = DCT_DCT;
       if (plane == 0) xd->tx_type_map[tx_type_map_idx] = tx_type;
+#if !CONFIG_REALTIME_ONLY && !defined(NDEBUG)
+      assert(!(plane == 0 && !is_inter_block(mbmi) && x->sby_cfl.track));
+#endif  // !CONFIG_REALTIME_ONLY && !defined(NDEBUG)
       return;
     }
   }
@@ -2548,6 +2597,22 @@ static void search_tx_type(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
   recon_intra(cpi, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
               txb_ctx, skip_trellis, best_tx_type, 0, &rate_cost, best_eob);
   p->dqcoeff = orig_dqcoeff;
+#if !CONFIG_REALTIME_ONLY
+  if (plane == 0 && !is_inter_block(mbmi) && x->sby_cfl.track) {
+    if (best_eob == 0 && best_tx_type != DCT_DCT) {
+      x->sby_cfl.rewrote_txk = 1;
+    }
+    if (!is_non_last_txb(blk_row, blk_col, plane_bsize, tx_size)) {
+      if (best_eob > 0) {
+        sby_cfl_txb_finish(
+            x, block, blk_row, blk_col, tx_size, best_tx_type, best_eob,
+            (best_dqcoeff == x->dqcoeff_buf) ? best_dqcoeff : NULL);
+      } else {
+        x->sby_cfl.last_eob = 0;
+      }
+    }
+  }
+#endif  // !CONFIG_REALTIME_ONLY
 }

 // Pick transform type for a luma transform block of tx_size. Note this function
@@ -3096,7 +3161,12 @@ static int64_t uniform_txfm_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
   av1_txfm_rd_in_plane(x, cpi, rd_stats, ref_best_rd,
                        AOMMIN(no_this_rd, skip_txfm_rd), AOM_PLANE_Y, bs,
                        tx_size, ftxs_mode);
-  if (rd_stats->rate == INT_MAX) return INT64_MAX;
+  if (rd_stats->rate == INT_MAX) {
+#if !CONFIG_REALTIME_ONLY
+    if (x->sby_cfl.track) x->sby_cfl.valid = 0;
+#endif  // !CONFIG_REALTIME_ONLY
+    return INT64_MAX;
+  }

   int64_t rd;
   // rdstats->rate should include all the rate except skip/non-skip cost as the
@@ -3183,6 +3253,9 @@ static inline void choose_tx_size_type_from_rd(const AV1_COMP *const cpi,
   uint8_t best_txk_type_map[MAX_MIB_SIZE * MAX_MIB_SIZE];
   TX_SIZE best_tx_size = max_rect_tx_size;
   int64_t best_rd = INT64_MAX;
+#if !CONFIG_REALTIME_ONLY
+  bool best_in_xd = false;
+#endif  // !CONFIG_REALTIME_ONLY
   const int num_blks = bsize_to_num_blk(bs);
   x->rd_model = FULL_TXFM_RD;
   int64_t rd[MAX_TX_DEPTH + 1] = { INT64_MAX, INT64_MAX, INT64_MAX };
@@ -3220,6 +3293,11 @@ static inline void choose_tx_size_type_from_rd(const AV1_COMP *const cpi,
       best_tx_size = tx_size;
       best_rd = rd[depth];
       *rd_stats = this_rd_stats;
+#if !CONFIG_REALTIME_ONLY
+      best_in_xd = true;
+    } else {
+      best_in_xd = false;
+#endif  // !CONFIG_REALTIME_ONLY
     }
     if (tx_size == TX_4X4) break;
     // If we are searching three depths, prune the smallest size depending
@@ -3232,7 +3310,16 @@ static inline void choose_tx_size_type_from_rd(const AV1_COMP *const cpi,

   if (rd_stats->rate != INT_MAX) {
     mbmi->tx_size = best_tx_size;
+#if !CONFIG_REALTIME_ONLY
+    if (!best_in_xd) {
+      av1_copy_array(xd->tx_type_map, best_txk_type_map, num_blks);
+      x->sby_cfl.valid = 0;
+    }
+  } else {
+    x->sby_cfl.valid = 0;
+#else
     av1_copy_array(xd->tx_type_map, best_txk_type_map, num_blks);
+#endif  // !CONFIG_REALTIME_ONLY
   }

 #if !CONFIG_REALTIME_ONLY
@@ -3893,6 +3980,11 @@ void av1_pick_uniform_tx_size_type_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
   } else {
     choose_tx_size_type_from_rd(cpi, x, rd_stats, ref_best_rd, bs);
   }
+#if !CONFIG_REALTIME_ONLY
+  if (x->sby_cfl.track && rd_stats->rate == INT_MAX) {
+    x->sby_cfl.valid = 0;
+  }
+#endif  // !CONFIG_REALTIME_ONLY

   // Save the RD search results into mb_rd_record for possible reuse in future.
   if (mb_rd_record) {
@@ -3961,6 +4053,14 @@ void av1_txfm_rd_in_plane(MACROBLOCK *x, const AV1_COMP *cpi,
                           TX_SIZE tx_size, FAST_TX_SEARCH_MODE ftxs_mode) {
   assert(IMPLIES(plane == 0, x->e_mbd.mi[0]->tx_size == tx_size));

+#if !CONFIG_REALTIME_ONLY
+  if (x->sby_cfl.track) {
+    x->sby_cfl.valid = 0;
+    x->sby_cfl.rewrote_txk = 0;
+    x->sby_cfl.last_eob = 0;
+  }
+#endif  // !CONFIG_REALTIME_ONLY
+
   if (!cpi->oxcf.txfm_cfg.enable_tx64 &&
       txsize_sqr_up_map[tx_size] == TX_64X64) {
     av1_invalid_rd_stats(rd_stats);
@@ -3972,6 +4072,20 @@ void av1_txfm_rd_in_plane(MACROBLOCK *x, const AV1_COMP *cpi,
     return;
   }

+#if !CONFIG_REALTIME_ONLY
+  if (x->sby_cfl.track) {
+#ifndef NDEBUG
+    MACROBLOCKD *const xd_cfl = &x->e_mbd;
+    const MB_MODE_INFO *const mbmi_cfl = xd_cfl->mi[0];
+    assert(plane == 0 && !is_inter_block(mbmi_cfl));
+    assert(mi_size_wide[mbmi_cfl->bsize] <= (CFL_BUF_LINE >> MI_SIZE_LOG2) &&
+           mi_size_high[mbmi_cfl->bsize] <= (CFL_BUF_LINE >> MI_SIZE_LOG2));
+    assert(xd_cfl->mb_to_right_edge >= 0 && xd_cfl->mb_to_bottom_edge >= 0);
+#endif  // NDEBUG
+    if (x->rd_model != LOW_TXFM_RD) x->sby_cfl.valid = 1;
+  }
+#endif  // !CONFIG_REALTIME_ONLY
+
   MACROBLOCKD *const xd = &x->e_mbd;
   const struct macroblockd_plane *const pd = &xd->plane[plane];
   struct rdcost_block_args args;
@@ -4036,6 +4150,9 @@ void av1_txfm_rd_in_plane(MACROBLOCK *x, const AV1_COMP *cpi,

   if (invalid_rd) {
     av1_invalid_rd_stats(rd_stats);
+#if !CONFIG_REALTIME_ONLY
+    if (x->sby_cfl.track) x->sby_cfl.valid = 0;
+#endif  // !CONFIG_REALTIME_ONLY
   } else {
     *rd_stats = args.rd_stats;
   }
@@ -4154,3 +4271,73 @@ int av1_txfm_search(const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,

   return 1;
 }
+
+#if !CONFIG_REALTIME_ONLY
+void av1_sby_cfl_rewrite_txk(MACROBLOCK *x) {
+  assert(x != NULL);
+  MACROBLOCKD *const xd = &x->e_mbd;
+  const MB_MODE_INFO *const mbmi = xd->mi[0];
+  const TX_SIZE tx_size = mbmi->tx_size;
+  const BLOCK_SIZE bsize = mbmi->bsize;
+  assert((unsigned)tx_size < TX_SIZES_ALL);
+  assert((unsigned)bsize < BLOCK_SIZES_ALL);
+  const int bw = mi_size_wide[bsize];
+  const int bh = mi_size_high[bsize];
+  const int txw_unit = tx_size_wide_unit[tx_size];
+  const int txh_unit = tx_size_high_unit[tx_size];
+  assert(bw <= (CFL_BUF_LINE >> MI_SIZE_LOG2) &&
+         bh <= (CFL_BUF_LINE >> MI_SIZE_LOG2));
+  assert(xd->mb_to_right_edge >= 0 && xd->mb_to_bottom_edge >= 0);
+  assert(txw_unit > 0 && txh_unit > 0 && (bw % txw_unit) == 0 &&
+         (bh % txh_unit) == 0);
+  const int step = txw_unit * txh_unit;
+  const uint16_t *const eobs = x->plane[0].eobs;
+  int block = 0;
+  for (int blk_row = 0; blk_row < bh; blk_row += txh_unit) {
+    for (int blk_col = 0; blk_col < bw; blk_col += txw_unit) {
+      if (eobs[block] == 0) {
+        update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
+      }
+      block += step;
+    }
+  }
+}
+
+void av1_sby_cfl_finish_recon(MACROBLOCK *x, int reduced_tx_set_used) {
+  assert(x != NULL);
+  if (x->sby_cfl.last_eob > 0) {
+    MACROBLOCKD *const xd = &x->e_mbd;
+    const struct macroblockd_plane *const pd = &xd->plane[0];
+    assert(x->sby_cfl.last_tx_size < TX_SIZES_ALL);
+    assert(x->sby_cfl.last_tx_type < TX_TYPES);
+    assert(x->sby_cfl.last_block_offset +
+               av1_get_max_eob((TX_SIZE)x->sby_cfl.last_tx_size) <=
+           CFL_BUF_SQUARE);
+    const int dst_stride = pd->dst.stride;
+    const int blk_row = x->sby_cfl.last_blk_row;
+    const int blk_col = x->sby_cfl.last_blk_col;
+    assert(blk_row >= 0 && blk_row < (CFL_BUF_LINE >> MI_SIZE_LOG2));
+    assert(blk_col >= 0 && blk_col < (CFL_BUF_LINE >> MI_SIZE_LOG2));
+    uint8_t *const dst =
+        &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
+    TxfmParam param;
+    param.tx_type = (TX_TYPE)x->sby_cfl.last_tx_type;
+    param.tx_size = (TX_SIZE)x->sby_cfl.last_tx_size;
+    param.eob = x->sby_cfl.last_eob;
+    x->sby_cfl.last_eob = 0;
+    param.lossless = 0;
+    param.bd = 8;
+    param.is_hbd = 0;
+#if !defined(NDEBUG)
+    param.tx_set_type =
+        av1_get_ext_tx_set_type(param.tx_size, 0, reduced_tx_set_used);
+    assert(av1_ext_tx_used[param.tx_set_type][param.tx_type]);
+#else
+    (void)reduced_tx_set_used;
+    param.tx_set_type = EXT_TX_SET_ALL16;
+#endif
+    av1_inv_txfm_add(x->plane[0].dqcoeff + x->sby_cfl.last_block_offset, dst,
+                     dst_stride, &param);
+  }
+}
+#endif  // !CONFIG_REALTIME_ONLY
diff --git a/av1/encoder/tx_search.h b/av1/encoder/tx_search.h
index 837d192cb4..ea8bda6c66 100644
--- a/av1/encoder/tx_search.h
+++ b/av1/encoder/tx_search.h
@@ -12,6 +12,8 @@
 #ifndef AOM_AV1_ENCODER_TRANSFORM_SEARCH_H_
 #define AOM_AV1_ENCODER_TRANSFORM_SEARCH_H_

+#include "config/aom_config.h"
+
 #include "av1/common/pred_common.h"
 #include "av1/encoder/encoder.h"

@@ -200,6 +202,16 @@ int av1_txfm_search(const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
 /*!\brief Precomputes cpi->tx_type_prune_mask[] for the current frame. */
 void av1_init_tx_type_prune_mask(AV1_COMP *cpi);

+#if !CONFIG_REALTIME_ONLY
+/*!\cond */
+// Completes luma reconstruction (the skipped last-txb IDCT add) from
+// WINNER_MODE_EVAL before CfL subsampling.
+void av1_sby_cfl_finish_recon(MACROBLOCK *x, int reduced_tx_set_used);
+// Rewrites tx_type_map entries for eob == 0 luma blocks from WINNER_MODE_EVAL.
+void av1_sby_cfl_rewrite_txk(MACROBLOCK *x);
+/*!\endcond */
+#endif  // !CONFIG_REALTIME_ONLY
+
 #if defined(AOM_INTERNAL_HIDDEN_VISIBILITY) && defined(__ELF__) && \
     (defined(__GNUC__) || defined(__clang__))
 #pragma GCC visibility pop