Commit 653af86d52 for aom

commit 653af86d5210f4d3af4724b056b5a95127aefa30
Author: Frank Galligan <fgalligan@google.com>
Date:   Wed Dec 2 12:08:37 2026 -0800

    txb_rdopt: optimize QM 2D trellis coefficient RD

    Add a specialized 2D QM-PSNR trellis optimizer
    av1_optimize_txb_multi_qm() (guarded by CONFIG_QUANT_MATRIX) and
    dispatch from av1_optimize_txb() and av1_optimize_b() via
    av1_use_qm_txb_opt_2d():

    - Pre-check carry/shift rounding bounds in update_coeff_simple_eq2_qm()
      and update_coeff_simple_gt1_qm(), delegating |qcoeff| == 2 lowering
      to AOM_NOINLINE finish_try_lower_qm() (calling eval_better_qm_exact()
      when margin lies in [0, 1 << RDDIV_BITS]).
    - Inline Phase 1 |qc| == 1 (approx_dr / d_eob) and Phase 2 |qc| <= 2
      fast paths, defer initial EOB (ci_last) dist0, avoid TX_PAD_2D setup
      when si == 0 && |qcoeff[0]| <= 2, and track simple_cul + nz_ci[]
      in-place.

    Speedup (AMD EPYC 7B13, Clang 21, bit-exact, --enable-qm=1
    --tune=iq):
    - avifenc (CLIC 1T / 8T): -2.16% (1T) / -3.09% (8T), Web 8T -0.86%.
    - 1080p allintra --cpu-used=6 (THP off, over origin/main d91e90d7):
      -2.53% (1T) / -6.42% (8T).
    Binary size (x86_64 -O3): libaom.a .text +6.6 KiB (+0.09%),
      .rodata +0.0 KiB (+0.00%); stripped aomenc +12.0 KiB (+0.13%).
    Memory (peak RSS, THP+ASLR off): 1080p allintra 1T +116 KiB (+0.32%),
      720p good 1T +104 KiB (+0.04%), rt 1T +36 KiB (+0.09%); zero heap or
      static allocations (prior +2.1 MiB was Linux THP 2 MiB variance).

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

diff --git a/av1/encoder/txb_rdopt.c b/av1/encoder/txb_rdopt.c
index 3dd71f3c9c..5ab48987b5 100644
--- a/av1/encoder/txb_rdopt.c
+++ b/av1/encoder/txb_rdopt.c
@@ -10,6 +10,8 @@
  */

 #include <assert.h>
+#include <stdint.h>
+#include <stdlib.h>

 #include "av1/encoder/txb_rdopt.h"
 #include "av1/encoder/txb_rdopt_utils.h"
@@ -1045,6 +1047,484 @@ int av1_optimize_txb_multi(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane,
   return eob;
 }

+#if CONFIG_QUANT_MATRIX
+// Pack 32-bit rate and COEFF_CONTEXT_MASK-clamped level contribution for
+// cul_level accumulation into a single 64-bit return value.
+static inline uint64_t pack_rate_cul_qm(int rate, unsigned int abs_val) {
+  const unsigned int capped = AOMMIN(abs_val, (unsigned int)COEFF_CONTEXT_MASK);
+  return (uint64_t)(uint32_t)rate | ((uint64_t)capped << 32);
+}
+
+static inline int64_t calc_coeff_dist0_qm(intptr_t ci, const tran_low_t *tcoeff,
+                                          const tran_low_t *dqcoeff,
+                                          const qm_val_t *qmatrix, int shift) {
+  const tran_low_t tqc = tcoeff[ci];
+  const tran_low_t dqc = dqcoeff[ci];
+  const int64_t scaled_qm = (int64_t)qmatrix[ci] << shift;
+  const int64_t dist0 = get_coeff_dist_scaled_qm(tqc, 0, scaled_qm);
+  return get_coeff_dist_scaled_qm(tqc, dqc, scaled_qm) - dist0;
+}
+
+static AOM_FORCE_INLINE void update_coeff_last_qm(
+    int *accu_rate, int si, int ci, tran_low_t abs_qc, int sign, int bhl,
+    int width, int64_t rdmult, int shift, const int16_t *dequant,
+    const LV_MAP_COEFF_COST *txb_costs, const tran_low_t *tcoeff,
+    tran_low_t *qcoeff, tran_low_t *dqcoeff, const qm_val_t *iqmatrix,
+    const qm_val_t *qmatrix) {
+  assert(si > 0 && ci > 0 && abs_qc >= 2);
+  const int coeff_ctx = get_lower_levels_ctx_eob(bhl, width, si);
+  const tran_low_t tqc = tcoeff[ci];
+  const tran_low_t dqc = dqcoeff[ci];
+  const int *const base_eob = txb_costs->base_eob_cost[coeff_ctx];
+  const tran_low_t abs_qc_low = abs_qc - 1;
+  int rate, rate_low;
+  if (abs_qc == 2) {
+    rate = base_eob[1] + av1_cost_literal(1);
+    rate_low = base_eob[0] + av1_cost_literal(1);
+  } else {
+    const int br_ctx = get_br_ctx_eob(ci, bhl, TX_CLASS_2D);
+    const int *const lps_cost = txb_costs->lps_cost[br_ctx];
+    const int base_rate = base_eob[2] + av1_cost_literal(1);
+    if (abs_qc < 1 + NUM_BASE_LEVELS + COEFF_BASE_RANGE) {
+      rate = base_rate + lps_cost[abs_qc - (1 + NUM_BASE_LEVELS)];
+      rate_low =
+          (abs_qc == 3)
+              ? (base_eob[1] + av1_cost_literal(1))
+              : (base_rate + lps_cost[abs_qc_low - (1 + NUM_BASE_LEVELS)]);
+    } else {
+      rate = base_rate + get_br_cost(abs_qc, lps_cost);
+      rate_low = base_rate + get_br_cost(abs_qc_low, lps_cost);
+    }
+  }
+
+  const int dqv =
+      ((iqmatrix[ci] * dequant[1]) + (1 << (AOM_QM_BITS - 1))) >> AOM_QM_BITS;
+  tran_low_t qc_low, dqc_low;
+  get_qc_dqc_low(abs_qc, sign, dqv, shift, &qc_low, &dqc_low);
+
+  const int64_t rd_rate = RDCOST(rdmult, rate, 0);
+  const int64_t rd_low_rate = RDCOST(rdmult, rate_low, 0);
+  const int64_t scaled_qm = (int64_t)qmatrix[ci] << shift;
+  // dist(tqc, 0) cancels between rd and rd_low, and phase 1 recalculates
+  // ci_last's dist0 lazily if needed (phase 2/DC never lower EOB).
+  const int64_t dist_diff_0 = get_coeff_dist_scaled_qm(tqc, dqc, scaled_qm);
+  const int64_t dist_diff_low_0 =
+      get_coeff_dist_scaled_qm(tqc, dqc_low, scaled_qm);
+
+  const int64_t rd = rd_rate + dist_diff_0 * (1LL << RDDIV_BITS);
+  const int64_t rd_low = rd_low_rate + dist_diff_low_0 * (1LL << RDDIV_BITS);
+
+  if (rd_low < rd) {
+    qcoeff[ci] = qc_low;
+    dqcoeff[ci] = dqc_low;
+    *accu_rate += rate_low;
+  } else {
+    *accu_rate += rate;
+  }
+}
+
+// Cold borderline tie-check and |qcoeff| == 2 -> 1 update; kept out of line
+// to avoid spilling registers in the fast simple scan loop.
+static AOM_NOINLINE uint64_t
+finish_try_lower_qm(intptr_t ci, int rate, int rate_low, tran_low_t dqc_low,
+                    int64_t margin, const TxbOptCtx *restrict ctx) {
+  assert(ci > 0 && ctx->qmatrix != NULL && abs(ctx->qcoeff[ci]) == 2 &&
+         margin >= 0);
+  const tran_low_t tqc = ctx->tcoeff[ci];
+  const tran_low_t dqc = ctx->dqcoeff[ci];
+  assert(tqc != 0 && (tqc < 0) == (ctx->qcoeff[ci] < 0));
+  const int sign_mask = AOMSIGN(tqc);
+  assert((dqc ^ sign_mask) >= (tqc ^ sign_mask));
+  const int64_t scaled_qm = (int64_t)ctx->qmatrix[ci] << ctx->shift;
+  // approx_rd and approx_dd are floor shifts that under-count the exact
+  // rounded terms by at most 1, so the exact margin lies in
+  // [margin - (1 << RDDIV_BITS), margin + 1]. Only [0, 1 << RDDIV_BITS]
+  // needs the exact check.
+  const int better = (margin > (1LL << RDDIV_BITS)) ||
+                     eval_better_qm_exact(tqc, dqc, dqc_low, scaled_qm, rate,
+                                          rate_low, ctx->rdmult);
+  if (better) {
+    ctx->qcoeff[ci] = ((tran_low_t)1 ^ sign_mask) - sign_mask;
+    ctx->dqcoeff[ci] = dqc_low;
+    ctx->levels[get_padded_idx((int)ci, ctx->bhl)] = 1;
+    return (uint64_t)(uint32_t)rate_low | (1ULL << 32);
+  }
+  return (uint64_t)(uint32_t)rate | (2ULL << 32);
+}
+
+// Cold handler for |qcoeff| >= 3 in the QM 2D simple pass; kept out of line
+// so the |qcoeff| <= 2 loop stays compact without register spills.
+// bc4 points to &base_cost[coeff_ctx][4], where bc4[0..3] store level 0..3+
+// non-zero base costs including sign bit (rd.c:av1_fill_coeff_costs).
+static AOM_NOINLINE uint64_t
+update_coeff_simple_gt1_qm(intptr_t ci, unsigned int abs_qc, const int *bc4,
+                           const TxbOptCtx *restrict ctx) {
+  assert(ci > 0 && abs_qc >= 3 && ctx->iqmatrix != NULL &&
+         ctx->qmatrix != NULL);
+  const tran_low_t tqc = ctx->tcoeff[ci];
+  const tran_low_t dqc = ctx->dqcoeff[ci];
+  assert(tqc != 0 && (tqc < 0) == (ctx->qcoeff[ci] < 0));
+  const int sign_mask = AOMSIGN(tqc);
+  const int br_ctx = get_br_ctx_simple_stride(ctx->levels, (int)ci, ctx->bhl,
+                                              ctx->stride, TX_CLASS_2D);
+  const int *const lps_flat = ctx->txb_costs->lps_cost[br_ctx];
+  const int base_rate = bc4[3];
+  int rate, rate_low;
+  if (LIKELY(abs_qc < 1 + NUM_BASE_LEVELS + COEFF_BASE_RANGE)) {
+    rate = base_rate + lps_flat[abs_qc - (1 + NUM_BASE_LEVELS)];
+    if ((dqc ^ sign_mask) < (tqc ^ sign_mask)) {
+      return pack_rate_cul_qm(rate, abs_qc);
+    }
+    rate_low = (abs_qc == 3)
+                   ? bc4[2]
+                   : (base_rate + lps_flat[abs_qc - (2 + NUM_BASE_LEVELS)]);
+  } else {
+    rate = base_rate + get_br_cost((tran_low_t)abs_qc, lps_flat);
+    if ((dqc ^ sign_mask) < (tqc ^ sign_mask)) {
+      return pack_rate_cul_qm(rate, abs_qc);
+    }
+    rate_low = base_rate + get_br_cost((tran_low_t)(abs_qc - 1), lps_flat);
+  }
+
+  const int dqv =
+      ((ctx->iqmatrix[ci] * ctx->dequant_ac) + (1 << (AOM_QM_BITS - 1))) >>
+      AOM_QM_BITS;
+  const int shift = ctx->shift;
+  const unsigned int abs_qc_low = abs_qc - 1;
+  const tran_low_t abs_dqc_low =
+      (tran_low_t)(((tran_low_t)abs_qc_low * dqv) >> shift);
+  const tran_low_t dqc_low = (abs_dqc_low ^ sign_mask) - sign_mask;
+  const int64_t sum_term = (int64_t)tqc * 2 - (int64_t)dqc - (int64_t)dqc_low;
+  const int64_t rdmult = ctx->rdmult;
+  const int64_t approx_rd =
+      ((int64_t)(rate - rate_low) * rdmult) >> AV1_PROB_COST_SHIFT;
+  const int64_t scaled_qm = (int64_t)ctx->qmatrix[ci] << shift;
+  const int64_t sq_qm = scaled_qm * scaled_qm;
+  const int64_t approx_dd =
+      ((((int64_t)dqc - dqc_low) * sum_term) * sq_qm) >> (2 * AOM_QM_BITS);
+  const int64_t margin = approx_rd - approx_dd * (1LL << RDDIV_BITS);
+  const int better =
+      (margin >= 0) && (margin > (1LL << RDDIV_BITS) ||
+                        eval_better_qm_exact(tqc, dqc, dqc_low, scaled_qm, rate,
+                                             rate_low, rdmult));
+  if (better) {
+    ctx->qcoeff[ci] = ((tran_low_t)abs_qc_low ^ sign_mask) - sign_mask;
+    ctx->dqcoeff[ci] = dqc_low;
+    ctx->levels[get_padded_idx((int)ci, ctx->bhl)] =
+        (uint8_t)AOMMIN(abs_qc_low, (unsigned int)INT8_MAX);
+    return pack_rate_cul_qm(rate_low, abs_qc_low);
+  }
+  return pack_rate_cul_qm(rate, abs_qc);
+}
+
+static inline uint64_t update_coeff_simple_eq2_qm(
+    intptr_t ci, const int *bc4, const TxbOptCtx *restrict ctx) {
+  assert(ci > 0 && ctx->iqmatrix != NULL && ctx->qmatrix != NULL);
+  const tran_low_t tqc = ctx->tcoeff[ci];
+  const tran_low_t dqc = ctx->dqcoeff[ci];
+  assert(tqc != 0 && (tqc < 0) == (ctx->qcoeff[ci] < 0));
+  const int sign_mask = AOMSIGN(tqc);
+  const int rate = bc4[2];
+  if ((dqc ^ sign_mask) < (tqc ^ sign_mask)) {
+    return (uint64_t)(uint32_t)rate | (2ULL << 32);
+  }
+  const int raw_dqv =
+      (ctx->iqmatrix[ci] * ctx->dequant_ac) + (1 << (AOM_QM_BITS - 1));
+  const int shift = ctx->shift;
+  const int64_t scaled_qm = (int64_t)ctx->qmatrix[ci] << shift;
+  const int64_t sq_qm = scaled_qm * scaled_qm;
+  const tran_low_t dqc_low =
+      ((raw_dqv >> (AOM_QM_BITS + shift)) ^ sign_mask) - sign_mask;
+  const int64_t sum_term = (int64_t)tqc * 2 - (int64_t)dqc - (int64_t)dqc_low;
+  const int64_t approx_dd =
+      ((((int64_t)dqc - dqc_low) * sum_term) * sq_qm) >> (2 * AOM_QM_BITS);
+  const int rate_low = bc4[1];
+  const int64_t approx_rd =
+      ((int64_t)(rate - rate_low) * ctx->rdmult) >> AV1_PROB_COST_SHIFT;
+  const int64_t margin = approx_rd - approx_dd * (1LL << RDDIV_BITS);
+  if (margin >= 0) {
+    return finish_try_lower_qm(ci, rate, rate_low, dqc_low, margin, ctx);
+  }
+  return (uint64_t)(uint32_t)rate | (2ULL << 32);
+}
+
+// Keep the specialized QM-PSNR 2D optimizer out of line from av1_optimize_txb
+// and av1_optimize_b so non-QM builds retain untouched av1_optimize_txb_multi
+// codegen while keeping hot scan-loop scalars in registers.
+AOM_NOINLINE
+int av1_optimize_txb_multi_qm(const struct AV1_COMP *cpi, MACROBLOCK *x,
+                              int plane, int block, TX_SIZE tx_size,
+                              TX_TYPE tx_type, const TXB_CTX *const txb_ctx,
+                              int *rate_cost, int sharpness) {
+  const MACROBLOCKD *const xd = &x->e_mbd;
+  const struct macroblock_plane *p = &x->plane[plane];
+  int eob = p->eobs[block];
+  assert(eob > 1 && sharpness != 0 && tx_type < IDTX);
+  assert(cpi->oxcf.tune_cfg.dist_metric == AOM_DIST_METRIC_QM_PSNR);
+  const PLANE_TYPE plane_type = get_plane_type(plane);
+  const int seg_id = xd->mi[0]->segment_id;
+  const qm_val_t *const iqmatrix =
+      xd->plane[plane].seg_iqmatrix[seg_id][tx_size];
+  const qm_val_t *const qmatrix = xd->plane[plane].seg_qmatrix[seg_id][tx_size];
+  assert(iqmatrix != NULL && qmatrix != NULL);
+  int is_noise_pattern = 0;
+  const int64_t rdmult = get_txb_rdmult(cpi, x, xd, plane, plane_type,
+                                        sharpness, &is_noise_pattern);
+  const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
+  const int16_t *const scan = scan_order->scan;
+  const int shift = av1_get_tx_scale(tx_size);
+  const int16_t *dequant = p->dequant_QTX;
+  const int block_offset = BLOCK_OFFSET(block);
+  tran_low_t *qcoeff = p->qcoeff + block_offset;
+  tran_low_t *dqcoeff = p->dqcoeff + block_offset;
+  const tran_low_t *tcoeff = p->coeff + block_offset;
+  const CoeffCosts *coeff_costs = &x->coeff_costs;
+
+  const AV1_COMMON *cm = &cpi->common;
+  const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
+  assert(tx_type_to_class[tx_type] == TX_CLASS_2D);
+  const int bhl = get_txb_bhl(tx_size);
+  const int width = get_txb_wide(tx_size);
+  const int height = get_txb_high(tx_size);
+  const LV_MAP_COEFF_COST *txb_costs =
+      &coeff_costs->coeff_costs[txs_ctx][plane_type];
+  const int eob_multi_size = txsize_log2_minus4[tx_size];
+  const LV_MAP_EOB_COST *txb_eob_costs =
+      &coeff_costs->eob_costs[eob_multi_size][plane_type];
+
+  const int eob_cost = get_eob_cost(eob, txb_eob_costs, txb_costs, TX_CLASS_2D);
+  int accu_rate = eob_cost;
+  int si = eob - 1;
+  const int ci_last = scan[si];
+  const tran_low_t qc_last = qcoeff[ci_last];
+  const tran_low_t abs_qc_last = abs(qc_last);
+  const int sign_last = qc_last < 0;
+  const int max_nz_num = kMaxNzNum;
+  int nz_ci[kMaxNzNum + 1] = { ci_last, 0, 0 };
+  const int min_eob_cutoff = is_noise_pattern ? 8 : 5;
+  if (abs_qc_last >= 2) {
+    update_coeff_last_qm(&accu_rate, si, ci_last, abs_qc_last, sign_last, bhl,
+                         width, rdmult, shift, dequant, txb_costs, tcoeff,
+                         qcoeff, dqcoeff, iqmatrix, qmatrix);
+    --si;
+  } else {
+    assert(abs_qc_last == 1);
+    const int coeff_ctx = get_lower_levels_ctx_eob(bhl, width, si);
+    accu_rate += txb_costs->base_eob_cost[coeff_ctx][0] + av1_cost_literal(1);
+    --si;
+  }
+
+  uint8_t levels_buf[TX_PAD_2D];
+  uint8_t *const levels = set_levels(levels_buf, height);
+  if (si >= 1 || (unsigned int)(qcoeff[0] + 2) > 4) {
+    av1_txb_init_levels(qcoeff, width, height, levels);
+  }
+
+  const intptr_t stride = (1 << bhl) + TX_PAD_HOR;
+  TxbOptCtx ctx = {
+    .rdmult = rdmult,
+    .accu_dist = 0,
+    .txb_eob_costs = txb_eob_costs,
+    .txb_costs = txb_costs,
+    .dequant = dequant,
+    .tcoeff = tcoeff,
+    .qcoeff = qcoeff,
+    .dqcoeff = dqcoeff,
+    .levels = levels,
+    .iqmatrix = iqmatrix,
+    .qmatrix = qmatrix,
+    .nz_ci = nz_ci,
+    .stride = stride,
+    .eob = eob,
+    .nz_num = 1,
+    .accu_rate = accu_rate,
+    .bhl = bhl,
+    .width = width,
+    .dc_sign_ctx = txb_ctx->dc_sign_ctx,
+    .shift = shift,
+    .dequant_ac = dequant[1],
+    .sharpness = (int16_t)sharpness,
+    .tx_class = TX_CLASS_2D,
+    .min_eob_cutoff = min_eob_cutoff,
+  };
+
+  int ac_nz_num = 1;
+  unsigned int simple_cul = 0;
+  if (si >= 1) {
+    int local_rate = ctx.accu_rate;
+    int nz_num = ctx.nz_num;
+    const int8_t *const nz_map_ctx = av1_nz_map_ctx_offset[tx_size];
+    const int (*base_cost)[8] = txb_costs->base_cost;
+
+    const int min_s_phase1 = min_eob_cutoff - 1;
+    const int16_t *scan_p = scan + si;
+    const int16_t *const p1_end = scan + min_s_phase1;
+    if (scan_p >= p1_end) {
+      const int *const eob_cost_tab = txb_eob_costs->eob_cost[0];
+      int64_t local_dist = 0;
+      int pending_dist_ci = nz_ci[0];
+      do {
+        int ci;
+        tran_low_t qc;
+        int coeff_ctx;
+        for (;;) {
+          ci = *scan_p;
+          coeff_ctx = get_lower_levels_ctx_simple_fast(levels, ci, bhl, stride,
+                                                       nz_map_ctx, TX_CLASS_2D);
+          qc = qcoeff[ci];
+          if (qc != 0) break;
+          local_rate += base_cost[coeff_ctx][0];
+          if (--scan_p < p1_end) goto phase1_done;
+        }
+        if (pending_dist_ci >= 0) {
+          local_dist += calc_coeff_dist0_qm(pending_dist_ci, tcoeff, dqcoeff,
+                                            qmatrix, shift);
+          pending_dist_ci = -1;
+        }
+        const int cur_s = (int)(scan_p - scan);
+        if ((unsigned int)(qc + 1) <= 2) {
+          const int coeff_ctx_new_eob =
+              get_lower_levels_ctx_eob(bhl, width, cur_s);
+          assert(cur_s >= 4);
+          const int k = get_msb(cur_s);
+          const int bit = (cur_s >> (k - 1)) & 1;
+          const int rate_coeff_eob =
+              eob_cost_tab[k + 1] + txb_costs->eob_extra_cost[k - 1][bit] +
+              txb_costs->base_eob_cost[coeff_ctx_new_eob][0] +
+              av1_cost_literal(k);
+          const int rate_keep = local_rate + base_cost[coeff_ctx][5];
+          // Check exact RDCOST when rounding error around d_eob == 0 (or -1
+          // under arithmetic/truncating right shift) could flip the choice.
+          const int64_t approx_dr =
+              ((int64_t)(rate_coeff_eob - rate_keep) * rdmult) >>
+              AV1_PROB_COST_SHIFT;
+          const int64_t d_eob = approx_dr - local_dist * (1LL << RDDIV_BITS);
+          if ((d_eob > 0) ||
+              (d_eob >= -1 && RDCOST(rdmult, rate_coeff_eob, 0) >=
+                                  RDCOST(rdmult, rate_keep, local_dist))) {
+            if (nz_num < max_nz_num) {
+              pending_dist_ci = ci;
+            }
+            nz_ci[nz_num] = ci;
+            ++nz_num;
+            local_rate = rate_keep;
+            --scan_p;
+            continue;
+          }
+        }
+        ctx.accu_rate = local_rate;
+        ctx.accu_dist = local_dist;
+        ctx.nz_num = nz_num;
+        local_rate =
+            update_coeff_eob_nz(cur_s, ci, qc, coeff_ctx, TX_CLASS_2D, &ctx);
+        local_dist = ctx.accu_dist;
+        nz_num = ctx.nz_num;
+        --scan_p;
+      } while (scan_p >= p1_end && nz_num <= max_nz_num);
+    }
+  phase1_done:;
+    const int16_t *const p2_end = scan + 1;
+    while (scan_p >= p2_end && nz_num <= max_nz_num) {
+      const int ci = *scan_p;
+      const tran_low_t qc = qcoeff[ci];
+      const unsigned int abs_qc = (unsigned int)abs(qc);
+      const int coeff_ctx = get_lower_levels_ctx_simple_fast(
+          levels, ci, bhl, stride, nz_map_ctx, TX_CLASS_2D);
+      if (abs_qc > 2) {
+        ctx.accu_rate = local_rate;
+        ctx.nz_num = nz_num;
+        local_rate = update_coeff_eob_nz((int)(scan_p - scan), ci, qc,
+                                         coeff_ctx, TX_CLASS_2D, &ctx);
+        nz_num = ctx.nz_num;
+      } else {
+        local_rate += base_cost[coeff_ctx][4 + abs_qc];
+        assert(nz_num <= max_nz_num);
+        nz_ci[nz_num] = ci;
+        nz_num += (abs_qc != 0);
+      }
+      --scan_p;
+    }
+    si = (int)(scan_p - scan);
+    ctx.nz_num = nz_num;
+    ac_nz_num = nz_num;
+
+    if (si >= 1) {
+      const int16_t *const scan_end = scan + 1;
+      for (;;) {
+        intptr_t ci;
+        tran_low_t qc;
+        int coeff_ctx;
+        for (;;) {
+          ci = *scan_p;
+          assert(ci > 0);
+          coeff_ctx = get_lower_levels_ctx_simple_fast(
+              levels, (int)ci, bhl, stride, nz_map_ctx, TX_CLASS_2D);
+          qc = qcoeff[ci];
+          if (UNLIKELY((unsigned int)(qc + 1) > 2)) break;
+          const unsigned int is_nz = (unsigned int)qc & 1u;
+          simple_cul += is_nz;
+          local_rate += base_cost[coeff_ctx][4 + is_nz];
+          if (--scan_p < scan_end) goto simple_done;
+        }
+        const int *const bc4 = &base_cost[coeff_ctx][4];
+        const unsigned int abs_qc = (unsigned int)abs(qc);
+        const uint64_t packed =
+            (abs_qc == 2) ? update_coeff_simple_eq2_qm(ci, bc4, &ctx)
+                          : update_coeff_simple_gt1_qm(ci, abs_qc, bc4, &ctx);
+        local_rate += (int)(uint32_t)packed;
+        simple_cul += (unsigned int)(packed >> 32);
+        if (--scan_p < scan_end) break;
+      }
+    simple_done:
+      si = 0;
+    }
+    ctx.accu_rate = local_rate;
+  }
+
+  if (ac_nz_num <= max_nz_num) {
+    const tran_low_t qc_dc = qcoeff[0];
+    if (qc_dc == 0) {
+      ctx.accu_rate += txb_costs->base_cost[0][0];
+    } else {
+      ctx.accu_rate = update_coeff_eob_nz(0, 0, qc_dc, 0, TX_CLASS_2D, &ctx);
+    }
+  } else {
+    assert(si == 0);
+    update_coeff_dc(&ctx.accu_rate, tx_size, TX_CLASS_2D, bhl, stride, rdmult,
+                    shift, ctx.dc_sign_ctx, dequant, txb_costs, tcoeff, qcoeff,
+                    dqcoeff, levels, iqmatrix, qmatrix);
+  }
+  accu_rate = ctx.accu_rate;
+  eob = ctx.eob;
+
+  p->eobs[block] = eob;
+  assert(eob > 1);
+  assert(ac_nz_num >= 1 && ac_nz_num <= kMaxNzNum + 1);
+  const int non_skip_cost = txb_costs->txb_skip_cost[txb_ctx->txb_skip_ctx][0];
+  const int tx_type_cost = get_tx_type_cost(x, xd, plane, tx_size, tx_type,
+                                            cm->features.reduced_tx_set_used);
+  accu_rate += non_skip_cost + tx_type_cost;
+  const tran_low_t dc_val = qcoeff[0];
+  const int dc_sign = ((dc_val < 0) + ((dc_val > 0) << 1))
+                      << COEFF_CONTEXT_BITS;
+  // Every non-zero AC coeff is counted once either in simple_cul (Phase 3)
+  // or in nz_ci[0..ac_nz_num) (initial EOB / Phase 1 / Phase 2).
+  unsigned int cul_level = (unsigned int)abs(dc_val) + simple_cul;
+  if (cul_level < (unsigned int)COEFF_CONTEXT_MASK) {
+    for (int i = 0; i < ac_nz_num; ++i) {
+      cul_level += (unsigned int)abs(qcoeff[nz_ci[i]]);
+    }
+  }
+  p->txb_entropy_ctx[block] =
+      (uint8_t)(AOMMIN(cul_level, (unsigned int)COEFF_CONTEXT_MASK) | dc_sign);
+  assert(p->txb_entropy_ctx[block] ==
+         av1_get_txb_entropy_context(qcoeff, scan_order, eob));
+
+  *rate_cost = accu_rate;
+  return eob;
+}
+#endif  // CONFIG_QUANT_MATRIX
+
 int av1_optimize_txb(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane,
                      int block, TX_SIZE tx_size, TX_TYPE tx_type,
                      const TXB_CTX *const txb_ctx, int *rate_cost,
@@ -1053,6 +1533,13 @@ int av1_optimize_txb(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane,
   const int eob = p->eobs[block];
   assert(eob > 0);
   if (eob > 1) {
+#if CONFIG_QUANT_MATRIX
+    if (av1_use_qm_txb_opt_2d(cpi, &x->e_mbd, plane, tx_size, tx_type,
+                              sharpness)) {
+      return av1_optimize_txb_multi_qm(cpi, x, plane, block, tx_size, tx_type,
+                                       txb_ctx, rate_cost, sharpness);
+    }
+#endif  // CONFIG_QUANT_MATRIX
     return av1_optimize_txb_multi(cpi, x, plane, block, tx_size, tx_type,
                                   txb_ctx, rate_cost, sharpness);
   }
diff --git a/av1/encoder/txb_rdopt.h b/av1/encoder/txb_rdopt.h
index f8bbfb46e1..81bfebd73e 100644
--- a/av1/encoder/txb_rdopt.h
+++ b/av1/encoder/txb_rdopt.h
@@ -12,6 +12,8 @@
 #ifndef AOM_AV1_ENCODER_TXB_RDOPT_H_
 #define AOM_AV1_ENCODER_TXB_RDOPT_H_

+#include "config/aom_config.h"
+
 #include "av1/common/blockd.h"
 #include "av1/common/txb_common.h"
 #include "av1/encoder/encoder.h"
@@ -26,6 +28,26 @@ int av1_optimize_txb_multi(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane,
                            int block, TX_SIZE tx_size, TX_TYPE tx_type,
                            const TXB_CTX *const txb_ctx, int *rate_cost,
                            int sharpness);
+#if CONFIG_QUANT_MATRIX
+int av1_optimize_txb_multi_qm(const struct AV1_COMP *cpi, MACROBLOCK *x,
+                              int plane, int block, TX_SIZE tx_size,
+                              TX_TYPE tx_type, const TXB_CTX *const txb_ctx,
+                              int *rate_cost, int sharpness);
+
+static inline int av1_use_qm_txb_opt_2d(const struct AV1_COMP *cpi,
+                                        const MACROBLOCKD *xd, int plane,
+                                        TX_SIZE tx_size, TX_TYPE tx_type,
+                                        int sharpness) {
+  if (sharpness == 0 ||
+      cpi->oxcf.tune_cfg.dist_metric != AOM_DIST_METRIC_QM_PSNR ||
+      tx_type >= IDTX) {
+    return 0;
+  }
+  const int segment_id = xd->mi[0]->segment_id;
+  return xd->plane[plane].seg_iqmatrix[segment_id][tx_size] != NULL &&
+         xd->plane[plane].seg_qmatrix[segment_id][tx_size] != NULL;
+}
+#endif  // CONFIG_QUANT_MATRIX
 /*!\endcond */

 /*!\brief Adjust the magnitude of quantized coefficients to achieve better
@@ -79,9 +101,15 @@ static inline int av1_optimize_b(const struct AV1_COMP *cpi, MACROBLOCK *x,
   }

   if (eob > 1) {
+    const int sharpness = cpi->oxcf.algo_cfg.sharpness;
+#if CONFIG_QUANT_MATRIX
+    if (av1_use_qm_txb_opt_2d(cpi, xd, plane, tx_size, tx_type, sharpness)) {
+      return av1_optimize_txb_multi_qm(cpi, x, plane, block, tx_size, tx_type,
+                                       txb_ctx, rate_cost, sharpness);
+    }
+#endif  // CONFIG_QUANT_MATRIX
     return av1_optimize_txb_multi(cpi, x, plane, block, tx_size, tx_type,
-                                  txb_ctx, rate_cost,
-                                  cpi->oxcf.algo_cfg.sharpness);
+                                  txb_ctx, rate_cost, sharpness);
   }
   return av1_optimize_txb(cpi, x, plane, block, tx_size, tx_type, txb_ctx,
                           rate_cost, cpi->oxcf.algo_cfg.sharpness);