Commit 8fcab21151 for aom

commit 8fcab21151c1e1306511e4ff7cb0691d64557bdc
Author: Frank Galligan <fgalligan@google.com>
Date:   Wed Nov 4 13:25:11 2026 -0800

    palette: optimize centroid sort and color map cost

    Replace qsort calls in remove_duplicates and find_top_colors with
    inline insertion sort, use av1_count_colors_with_threshold for 8-bit
    UV palette candidate pruning, and compute row-major palette color-map
    contexts in closed form in av1_fast_palette_color_index_context and
    av1_cost_color_map.

    Speedup: -8.72% (1T 8b) / -9.08% (8T 8b) / -5.35% (1T 10b) screen
      allintra, -1.42% (2T) screen good, -6.06% (1T) / -2.36% (8T) 720p
      allintra, and -0.95% (1T) 720p good at cpu-used=6/4 (bit-exact).
    Binary size (x86_64 -O3): libaom.a .text -0.4 KiB (-0.00%),
      .rodata -0.0 KiB (-0.00%); stripped aomenc +0.0 KiB (+0.00%).
    Memory (peak RSS, 1080p allintra, zero heap allocs): 1T -1768 KiB
      (-3.68%), 8T +404 KiB (+0.72%).

    TAG=agy
    CONV=b929a630-a6cd-45a0-979c-1767c30178ee
    Change-Id: Ic96c9b325b914b70a9e8937504534225049db722

diff --git a/av1/common/blockd.h b/av1/common/blockd.h
index b986f61b4e..9bd0756278 100644
--- a/av1/common/blockd.h
+++ b/av1/common/blockd.h
@@ -1666,9 +1666,6 @@ static inline void av1_get_block_dimensions(BLOCK_SIZE bsize, int plane,
 // Pointer to a three-dimensional array whose first dimension is PALETTE_SIZES.
 typedef aom_cdf_prob (*MapCdf)[PALETTE_COLOR_INDEX_CONTEXTS]
                               [CDF_SIZE(PALETTE_COLORS)];
-// Pointer to a const three-dimensional array whose first dimension is
-// PALETTE_SIZES.
-typedef const int (*ColorCost)[PALETTE_COLOR_INDEX_CONTEXTS][PALETTE_COLORS];
 /* clang-format on */

 typedef struct {
@@ -1679,7 +1676,6 @@ typedef struct {
   int plane_height;
   uint8_t *color_map;
   MapCdf map_cdf;
-  ColorCost color_cost;
 } Av1ColorMapParam;

 static inline int is_nontrans_global_motion(const MACROBLOCKD *xd,
diff --git a/av1/encoder/palette.c b/av1/encoder/palette.c
index cd367b918e..4dd21086bd 100644
--- a/av1/encoder/palette.c
+++ b/av1/encoder/palette.c
@@ -9,6 +9,7 @@
  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
  */

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

@@ -32,10 +33,6 @@
 #include "av1/encoder/k_means_template.h"
 #undef AV1_K_MEANS_DIM

-static int int16_comparer(const void *a, const void *b) {
-  return (*(int16_t *)a - *(int16_t *)b);
-}
-
 /*!\brief Removes duplicated centroid indices.
  *
  * \ingroup palette_mode_search
@@ -51,7 +48,16 @@ static int int16_comparer(const void *a, const void *b) {
 static int remove_duplicates(int16_t *centroids, int num_centroids) {
   int num_unique;  // number of unique centroids
   int i;
-  qsort(centroids, num_centroids, sizeof(*centroids), int16_comparer);
+  assert(num_centroids >= 1);
+  for (i = 1; i < num_centroids; ++i) {
+    const int16_t val = centroids[i];
+    int j = i;
+    while (j > 0 && centroids[j - 1] > val) {
+      centroids[j] = centroids[j - 1];
+      --j;
+    }
+    centroids[j] = val;
+  }
   // Remove duplicates.
   num_unique = 1;
   for (i = 1; i < num_centroids; ++i) {
@@ -490,44 +496,25 @@ struct ColorCount {
   int count;
 };

-static int color_count_comp(const void *c1, const void *c2) {
-  const struct ColorCount *color_count1 = (const struct ColorCount *)c1;
-  const struct ColorCount *color_count2 = (const struct ColorCount *)c2;
-  if (color_count1->count > color_count2->count) return -1;
-  if (color_count1->count < color_count2->count) return 1;
-  if (color_count1->index < color_count2->index) return -1;
-  return 1;
-}
-
 static void find_top_colors(const int *const count_buf, int bit_depth,
                             int n_colors, int16_t *top_colors) {
+  assert(n_colors >= PALETTE_MIN_SIZE && n_colors <= PALETTE_MAX_SIZE);
   // Top color array, serving as a priority queue if more than n_colors are
   // found.
   struct ColorCount top_color_counts[PALETTE_MAX_SIZE] = { { 0 } };
   int n_color_count = 0;
+  int min_count = 0;
   for (int i = 0; i < (1 << bit_depth); ++i) {
-    if (count_buf[i] > 0) {
-      if (n_color_count < n_colors) {
-        // Keep adding to the top colors.
-        top_color_counts[n_color_count].index = i;
-        top_color_counts[n_color_count].count = count_buf[i];
-        ++n_color_count;
-        if (n_color_count == n_colors) {
-          qsort(top_color_counts, n_colors, sizeof(top_color_counts[0]),
-                color_count_comp);
-        }
-      } else {
-        // Check the worst in the sorted top.
-        if (count_buf[i] > top_color_counts[n_colors - 1].count) {
-          int j = n_colors - 1;
-          // Move up to the best one.
-          while (j >= 1 && count_buf[i] > top_color_counts[j - 1].count) --j;
-          memmove(top_color_counts + j + 1, top_color_counts + j,
-                  (n_colors - j - 1) * sizeof(top_color_counts[0]));
-          top_color_counts[j].index = i;
-          top_color_counts[j].count = count_buf[i];
-        }
+    const int count = count_buf[i];
+    if (count > min_count) {
+      int j = n_color_count < n_colors ? n_color_count++ : n_colors - 1;
+      while (j >= 1 && count > top_color_counts[j - 1].count) {
+        top_color_counts[j] = top_color_counts[j - 1];
+        --j;
       }
+      top_color_counts[j].index = i;
+      top_color_counts[j].count = count;
+      min_count = top_color_counts[n_colors - 1].count;
     }
   }
   assert(n_color_count == n_colors);
@@ -793,6 +780,9 @@ void av1_rd_pick_palette_intra_sbuv(const AV1_COMP *cpi, MACROBLOCK *x,
   av1_get_block_dimensions(bsize, 1, xd, &plane_block_width,
                            &plane_block_height, &rows, &cols);

+  // Relax chroma palette color threshold for static screen-content KF groups.
+  const int max_colors_thresh =
+      cpi->ppi->twopass.is_static_sc_kf_group ? 256 : 64;
   mbmi->uv_mode = UV_DC_PRED;
   if (seq_params->use_highbitdepth) {
     int count_buf[1 << 12];      // Maximum (1 << 12) color levels.
@@ -804,9 +794,12 @@ void av1_rd_pick_palette_intra_sbuv(const AV1_COMP *cpi, MACROBLOCK *x,
                             seq_params->bit_depth, count_buf, count_buf_8bit,
                             &colors_threshold_v, &colors_v);
   } else {
-    int count_buf[1 << 8];
-    av1_count_colors(src_u, src_stride, rows, cols, count_buf, &colors_u);
-    av1_count_colors(src_v, src_stride, rows, cols, count_buf, &colors_v);
+    colors_v = 0;
+    if (av1_count_colors_with_threshold(src_u, src_stride, rows, cols,
+                                        max_colors_thresh, &colors_u)) {
+      av1_count_colors_with_threshold(src_v, src_stride, rows, cols,
+                                      max_colors_thresh, &colors_v);
+    }
     colors_threshold_u = colors_u;
     colors_threshold_v = colors_v;
   }
@@ -817,9 +810,6 @@ void av1_rd_pick_palette_intra_sbuv(const AV1_COMP *cpi, MACROBLOCK *x,
   colors_threshold = colors_threshold_u > colors_threshold_v
                          ? colors_threshold_u
                          : colors_threshold_v;
-  // Relax chroma palette color threshold for static screen-content KF groups.
-  const int max_colors_thresh =
-      cpi->ppi->twopass.is_static_sc_kf_group ? 256 : 64;
   if (colors_threshold > 1 && colors_threshold <= max_colors_thresh) {
     int r, c, n, i, j;
     const int max_itr = 50;
diff --git a/av1/encoder/tokenize.c b/av1/encoder/tokenize.c
index 87278583af..a282d2625e 100644
--- a/av1/encoder/tokenize.c
+++ b/av1/encoder/tokenize.c
@@ -62,16 +62,45 @@ static inline int av1_fast_palette_color_index_context_on_edge(
   return 0;
 }

-#define SWAP(i, j)                           \
-  do {                                       \
-    const uint8_t tmp_score = score_rank[i]; \
-    const uint8_t tmp_color = color_rank[i]; \
-    score_rank[i] = score_rank[j];           \
-    color_rank[i] = color_rank[j];           \
-    score_rank[j] = tmp_score;               \
-    color_rank[j] = tmp_color;               \
-  } while (0)
-#define INVALID_COLOR_IDX (UINT8_MAX)
+// Closed-form palette color index context and remapped symbol index for an
+// interior pixel (r > 0 && c > 0). Neighbors are n0 = left (weight 2),
+// n1 = above (weight 2), and n2 = top-left (weight 1). Grouping equal
+// neighbors determines the context directly: 4 (all equal), 3 (n0 == n1 != n2),
+// 2 (n0 == n2 or n1 == n2), and 1 (all distinct). In context 1, the
+// equal-weight n0/n1 tie breaks in favor of the smaller color index (rank
+// (n0 > n1) for curr == n0 and (n1 > n0) for curr == n1). Unmatched curr
+// shifts up by count(distinct_neighbor > curr).
+static inline int palette_color_index_context_interior(uint8_t n0, uint8_t n1,
+                                                       uint8_t n2, uint8_t curr,
+                                                       int *color_idx) {
+  if (n0 == n1) {
+    if (n0 == n2) {
+      *color_idx = (curr == n0) ? 0 : curr + (n0 > curr);
+      return 4;
+    }
+    *color_idx = (curr == n0)   ? 0
+                 : (curr == n2) ? 1
+                                : curr + (n0 > curr) + (n2 > curr);
+    return 3;
+  }
+  if (n0 == n2) {
+    *color_idx = (curr == n0)   ? 0
+                 : (curr == n1) ? 1
+                                : curr + (n0 > curr) + (n1 > curr);
+    return 2;
+  }
+  if (n1 == n2) {
+    *color_idx = (curr == n1)   ? 0
+                 : (curr == n0) ? 1
+                                : curr + (n1 > curr) + (n0 > curr);
+    return 2;
+  }
+  *color_idx = (curr == n0)   ? (n0 > n1)
+               : (curr == n1) ? (n1 > n0)
+               : (curr == n2) ? 2
+                              : curr + (n0 > curr) + (n1 > curr) + (n2 > curr);
+  return 1;
+}

 // A faster version of av1_get_palette_color_index_context used by the encoder
 // exploiting the fact that the encoder does not need to maintain a color order.
@@ -88,109 +117,22 @@ static inline int av1_fast_palette_color_index_context(const uint8_t *color_map,
                                                         color_idx);
   }

-  // This goes in the order of left, top, and top-left. This has the advantage
-  // that unless anything here are not distinct or invalid, this will already
-  // be in sorted order. Furthermore, if either of the first two is
-  // invalid, we know the last one is also invalid.
-  uint8_t color_neighbors[NUM_PALETTE_NEIGHBORS];
-  color_neighbors[0] = color_map[(r - 0) * stride + (c - 1)];
-  color_neighbors[1] = color_map[(r - 1) * stride + (c - 0)];
-  color_neighbors[2] = color_map[(r - 1) * stride + (c - 1)];
-
-  // Aggregate duplicated values.
-  // Since our array is so small, using a couple if statements is faster
-  uint8_t scores[NUM_PALETTE_NEIGHBORS] = { 2, 2, 1 };
-  uint8_t num_invalid_colors = 0;
-  if (color_neighbors[0] == color_neighbors[1]) {
-    scores[0] += scores[1];
-    color_neighbors[1] = INVALID_COLOR_IDX;
-    num_invalid_colors += 1;
-
-    if (color_neighbors[0] == color_neighbors[2]) {
-      scores[0] += scores[2];
-      num_invalid_colors += 1;
-    }
-  } else if (color_neighbors[0] == color_neighbors[2]) {
-    scores[0] += scores[2];
-    num_invalid_colors += 1;
-  } else if (color_neighbors[1] == color_neighbors[2]) {
-    scores[1] += scores[2];
-    num_invalid_colors += 1;
-  }
-
-  const uint8_t num_valid_colors = NUM_PALETTE_NEIGHBORS - num_invalid_colors;
-
-  uint8_t *color_rank = color_neighbors;
-  uint8_t *score_rank = scores;
-
-  // Sort everything
-  if (num_valid_colors > 1) {
-    if (color_neighbors[1] == INVALID_COLOR_IDX) {
-      scores[1] = scores[2];
-      color_neighbors[1] = color_neighbors[2];
-    }
-
-    // We need to swap the first two elements if they have the same score but
-    // the color indices are not in the right order
-    if (score_rank[0] < score_rank[1] ||
-        (score_rank[0] == score_rank[1] && color_rank[0] > color_rank[1])) {
-      SWAP(0, 1);
-    }
-    if (num_valid_colors > 2) {
-      if (score_rank[0] < score_rank[2]) {
-        SWAP(0, 2);
-      }
-      if (score_rank[1] < score_rank[2]) {
-        SWAP(1, 2);
-      }
-    }
-  }
-
-  // If any of the neighbor colors has higher index than current color index,
-  // then we move up by 1 unless the current color is the same as one of the
-  // neighbors.
-  const uint8_t current_color = *color_idx = color_map[r * stride + c];
-  for (int idx = 0; idx < num_valid_colors; idx++) {
-    if (color_rank[idx] > current_color) {
-      (*color_idx)++;
-    } else if (color_rank[idx] == current_color) {
-      *color_idx = idx;
-      break;
-    }
-  }
-
-  // Get hash value of context.
-  uint8_t color_index_ctx_hash = 0;
-  static const uint8_t hash_multipliers[NUM_PALETTE_NEIGHBORS] = { 1, 2, 2 };
-  for (int idx = 0; idx < num_valid_colors; ++idx) {
-    color_index_ctx_hash += score_rank[idx] * hash_multipliers[idx];
-  }
-  assert(color_index_ctx_hash > 0);
-  assert(color_index_ctx_hash <= MAX_COLOR_CONTEXT_HASH);
-
-  // Lookup context from hash.
-  const int color_index_ctx = 9 - color_index_ctx_hash;
-  assert(color_index_ctx ==
-         av1_palette_color_index_context_lookup[color_index_ctx_hash]);
-  assert(color_index_ctx >= 0);
-  assert(color_index_ctx < PALETTE_COLOR_INDEX_CONTEXTS);
-  return color_index_ctx;
+  return palette_color_index_context_interior(
+      color_map[r * stride + (c - 1)], color_map[(r - 1) * stride + c],
+      color_map[(r - 1) * stride + (c - 1)], color_map[r * stride + c],
+      color_idx);
 }
-#undef INVALID_COLOR_IDX
-#undef SWAP

-static int cost_and_tokenize_map(Av1ColorMapParam *param, TokenExtra **t,
-                                 int plane, int calc_rate, int allow_update_cdf,
-                                 FRAME_COUNTS *counts) {
+static void cost_and_tokenize_map(Av1ColorMapParam *param, TokenExtra **t,
+                                  int plane, int allow_update_cdf,
+                                  FRAME_COUNTS *counts) {
   const uint8_t *const color_map = param->color_map;
   MapCdf map_cdf = param->map_cdf;
-  ColorCost color_cost = param->color_cost;
   const int plane_block_width = param->plane_width;
   const int rows = param->rows;
   const int cols = param->cols;
   const int n = param->n_colors;
   const int palette_size_idx = n - PALETTE_MIN_SIZE;
-  int this_rate = 0;

   (void)plane;
   (void)counts;
@@ -202,28 +144,22 @@ static int cost_and_tokenize_map(Av1ColorMapParam *param, TokenExtra **t,
       const int color_ctx = av1_fast_palette_color_index_context(
           color_map, plane_block_width, i, j, &color_new_idx);
       assert(color_new_idx >= 0 && color_new_idx < n);
-      if (calc_rate) {
-        this_rate += color_cost[palette_size_idx][color_ctx][color_new_idx];
-      } else {
-        (*t)->token = color_new_idx;
-        (*t)->color_ctx = color_ctx;
-        ++(*t);
-        if (allow_update_cdf)
-          update_cdf(map_cdf[palette_size_idx][color_ctx], color_new_idx, n);
+      (*t)->token = color_new_idx;
+      (*t)->color_ctx = color_ctx;
+      ++(*t);
+      if (allow_update_cdf)
+        update_cdf(map_cdf[palette_size_idx][color_ctx], color_new_idx, n);
 #if CONFIG_ENTROPY_STATS
-        if (plane) {
-          ++counts->palette_uv_color_index[palette_size_idx][color_ctx]
-                                          [color_new_idx];
-        } else {
-          ++counts->palette_y_color_index[palette_size_idx][color_ctx]
-                                         [color_new_idx];
-        }
-#endif
+      if (plane) {
+        ++counts->palette_uv_color_index[palette_size_idx][color_ctx]
+                                        [color_new_idx];
+      } else {
+        ++counts->palette_y_color_index[palette_size_idx][color_ctx]
+                                       [color_new_idx];
       }
+#endif
     }
   }
-  if (calc_rate) return this_rate;
-  return 0;
 }

 static void get_palette_params(const MACROBLOCK *const x, int plane,
@@ -234,8 +170,6 @@ static void get_palette_params(const MACROBLOCK *const x, int plane,
   params->color_map = xd->plane[plane].color_index_map;
   params->map_cdf = plane ? xd->tile_ctx->palette_uv_color_index_cdf
                           : xd->tile_ctx->palette_y_color_index_cdf;
-  params->color_cost = plane ? x->mode_costs.palette_uv_color_cost
-                             : x->mode_costs.palette_y_color_cost;
   params->n_colors = pmi->palette_size[plane];
   av1_get_block_dimensions(bsize, plane, xd, &params->plane_width, NULL,
                            &params->rows, &params->cols);
@@ -257,9 +191,55 @@ static void get_color_map_params(const MACROBLOCK *const x, int plane,
 int av1_cost_color_map(const MACROBLOCK *const x, int plane, BLOCK_SIZE bsize,
                        TX_SIZE tx_size, COLOR_MAP_TYPE type) {
   assert(plane == 0 || plane == 1);
-  Av1ColorMapParam color_map_params;
-  get_color_map_params(x, plane, bsize, tx_size, type, &color_map_params);
-  return cost_and_tokenize_map(&color_map_params, NULL, plane, 1, 0, NULL);
+  assert(type == PALETTE_MAP);
+  (void)tx_size;
+  (void)type;
+  const MACROBLOCKD *const xd = &x->e_mbd;
+  const int palette_size = xd->mi[0]->palette_mode_info.palette_size[plane];
+  assert(palette_size >= PALETTE_MIN_SIZE && palette_size <= PALETTE_MAX_SIZE);
+  const uint8_t *const color_map = xd->plane[plane].color_index_map;
+  const int (*const cost_tab)[PALETTE_COLORS] =
+      (plane ? x->mode_costs.palette_uv_color_cost
+             : x->mode_costs
+                   .palette_y_color_cost)[palette_size - PALETTE_MIN_SIZE];
+  int stride, rows, cols;
+  av1_get_block_dimensions(bsize, plane, xd, &stride, NULL, &rows, &cols);
+  assert(rows > 0 && cols > 0);
+  int this_rate = 0;
+  // Each pixel's context depends only on color_map and cost_tab (both
+  // read-only here), so row-major traversal matches anti-diagonal tokenization.
+  uint8_t n0 = color_map[0];
+  // Disable Clang loop vectorization: for this short loop (cols <= 64) with
+  // loop-carried n0 and indirect cost_tab[0] lookups, AVX2 auto-vectorization
+  // scalarizes index/table lookups with stack spills and bloats code size:
+  // av1_cost_color_map 281 insns (sp_ops=2) -> 451 insns (sp_ops=16).
+#if defined(__clang__)
+#pragma clang loop vectorize(disable)
+#endif
+  for (int c = 1; c < cols; ++c) {
+    const uint8_t curr = color_map[c];
+    this_rate += cost_tab[0][(curr == n0) ? 0 : curr + (n0 > curr)];
+    n0 = curr;
+  }
+  const uint8_t *above = color_map;
+  for (int r = 1; r < rows; ++r) {
+    const uint8_t *const row = above + stride;
+    uint8_t n2 = above[0];
+    n0 = row[0];
+    this_rate += cost_tab[0][(n0 == n2) ? 0 : n0 + (n2 > n0)];
+    for (int c = 1; c < cols; ++c) {
+      const uint8_t curr = row[c];
+      const uint8_t n1 = above[c];
+      int color_idx;
+      const int color_ctx =
+          palette_color_index_context_interior(n0, n1, n2, curr, &color_idx);
+      this_rate += cost_tab[color_ctx][color_idx];
+      n0 = curr;
+      n2 = n1;
+    }
+    above = row;
+  }
+  return this_rate;
 }

 void av1_tokenize_color_map(const MACROBLOCK *const x, int plane,
@@ -273,8 +253,7 @@ void av1_tokenize_color_map(const MACROBLOCK *const x, int plane,
   (*t)->token = color_map_params.color_map[0];
   (*t)->color_ctx = -1;
   ++(*t);
-  cost_and_tokenize_map(&color_map_params, t, plane, 0, allow_update_cdf,
-                        counts);
+  cost_and_tokenize_map(&color_map_params, t, plane, allow_update_cdf, counts);
 }

 static void tokenize_vartx(ThreadData *td, TX_SIZE tx_size,