Coverage Report

Created: 2026-04-01 07:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/aom/av1/encoder/palette.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
3
 *
4
 * This source code is subject to the terms of the BSD 2 Clause License and
5
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
 * was not distributed with this source code in the LICENSE file, you can
7
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8
 * Media Patent License 1.0 was not distributed with this source code in the
9
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
 */
11
12
#include <math.h>
13
#include <stdlib.h>
14
15
#include "av1/common/pred_common.h"
16
17
#include "aom_ports/bitops.h"
18
#include "av1/encoder/block.h"
19
#include "av1/encoder/cost.h"
20
#include "av1/encoder/encoder.h"
21
#include "av1/encoder/intra_mode_search.h"
22
#include "av1/encoder/intra_mode_search_utils.h"
23
#include "av1/encoder/palette.h"
24
#include "av1/encoder/random.h"
25
#include "av1/encoder/rdopt_utils.h"
26
#include "av1/encoder/tx_search.h"
27
28
0
#define AV1_K_MEANS_DIM 1
29
#include "av1/encoder/k_means_template.h"
30
#undef AV1_K_MEANS_DIM
31
0
#define AV1_K_MEANS_DIM 2
32
#include "av1/encoder/k_means_template.h"
33
#undef AV1_K_MEANS_DIM
34
35
0
static int int16_comparer(const void *a, const void *b) {
36
0
  return (*(int16_t *)a - *(int16_t *)b);
37
0
}
38
39
/*!\brief Removes duplicated centroid indices.
40
 *
41
 * \ingroup palette_mode_search
42
 * \param[in]    centroids          A list of centroids index.
43
 * \param[in]    num_centroids      Number of centroids.
44
 *
45
 * \return Returns the number of unique centroids and saves the unique centroids
46
 * in beginning of the centroids array.
47
 *
48
 * \attention The centroids should be rounded to integers before calling this
49
 * method.
50
 */
51
0
static int remove_duplicates(int16_t *centroids, int num_centroids) {
52
0
  int num_unique;  // number of unique centroids
53
0
  int i;
54
0
  qsort(centroids, num_centroids, sizeof(*centroids), int16_comparer);
55
  // Remove duplicates.
56
0
  num_unique = 1;
57
0
  for (i = 1; i < num_centroids; ++i) {
58
0
    if (centroids[i] != centroids[i - 1]) {  // found a new unique centroid
59
0
      centroids[num_unique++] = centroids[i];
60
0
    }
61
0
  }
62
0
  return num_unique;
63
0
}
64
65
static int delta_encode_cost(const int *colors, int num, int bit_depth,
66
0
                             int min_val) {
67
0
  if (num <= 0) return 0;
68
0
  int bits_cost = bit_depth;
69
0
  if (num == 1) return bits_cost;
70
0
  bits_cost += 2;
71
0
  int max_delta = 0;
72
0
  int deltas[PALETTE_MAX_SIZE];
73
0
  const int min_bits = bit_depth - 3;
74
0
  for (int i = 1; i < num; ++i) {
75
0
    const int delta = colors[i] - colors[i - 1];
76
0
    deltas[i - 1] = delta;
77
0
    assert(delta >= min_val);
78
0
    if (delta > max_delta) max_delta = delta;
79
0
  }
80
0
  int bits_per_delta = AOMMAX(aom_ceil_log2(max_delta + 1 - min_val), min_bits);
81
0
  assert(bits_per_delta <= bit_depth);
82
0
  int range = (1 << bit_depth) - colors[0] - min_val;
83
0
  for (int i = 0; i < num - 1; ++i) {
84
0
    bits_cost += bits_per_delta;
85
0
    range -= deltas[i];
86
0
    bits_per_delta = AOMMIN(bits_per_delta, aom_ceil_log2(range));
87
0
  }
88
0
  return bits_cost;
89
0
}
90
91
int av1_index_color_cache(const uint16_t *color_cache, int n_cache,
92
                          const uint16_t *colors, int n_colors,
93
0
                          uint8_t *cache_color_found, int *out_cache_colors) {
94
0
  if (n_cache <= 0) {
95
0
    for (int i = 0; i < n_colors; ++i) out_cache_colors[i] = colors[i];
96
0
    return n_colors;
97
0
  }
98
0
  memset(cache_color_found, 0, n_cache * sizeof(*cache_color_found));
99
0
  int n_in_cache = 0;
100
0
  int in_cache_flags[PALETTE_MAX_SIZE];
101
0
  memset(in_cache_flags, 0, sizeof(in_cache_flags));
102
0
  for (int i = 0; i < n_cache && n_in_cache < n_colors; ++i) {
103
0
    for (int j = 0; j < n_colors; ++j) {
104
0
      if (colors[j] == color_cache[i]) {
105
0
        in_cache_flags[j] = 1;
106
0
        cache_color_found[i] = 1;
107
0
        ++n_in_cache;
108
0
        break;
109
0
      }
110
0
    }
111
0
  }
112
0
  int j = 0;
113
0
  for (int i = 0; i < n_colors; ++i)
114
0
    if (!in_cache_flags[i]) out_cache_colors[j++] = colors[i];
115
0
  assert(j == n_colors - n_in_cache);
116
0
  return j;
117
0
}
118
119
int av1_get_palette_delta_bits_v(const PALETTE_MODE_INFO *const pmi,
120
                                 int bit_depth, int *zero_count,
121
0
                                 int *min_bits) {
122
0
  const int n = pmi->palette_size[1];
123
0
  const int max_val = 1 << bit_depth;
124
0
  int max_d = 0;
125
0
  *min_bits = bit_depth - 4;
126
0
  *zero_count = 0;
127
0
  for (int i = 1; i < n; ++i) {
128
0
    const int delta = pmi->palette_colors[2 * PALETTE_MAX_SIZE + i] -
129
0
                      pmi->palette_colors[2 * PALETTE_MAX_SIZE + i - 1];
130
0
    const int v = abs(delta);
131
0
    const int d = AOMMIN(v, max_val - v);
132
0
    if (d > max_d) max_d = d;
133
0
    if (d == 0) ++(*zero_count);
134
0
  }
135
0
  return AOMMAX(aom_ceil_log2(max_d + 1), *min_bits);
136
0
}
137
138
int av1_palette_color_cost_y(const PALETTE_MODE_INFO *const pmi,
139
                             const uint16_t *color_cache, int n_cache,
140
0
                             int bit_depth) {
141
0
  const int n = pmi->palette_size[0];
142
0
  int out_cache_colors[PALETTE_MAX_SIZE];
143
0
  uint8_t cache_color_found[2 * PALETTE_MAX_SIZE];
144
0
  const int n_out_cache =
145
0
      av1_index_color_cache(color_cache, n_cache, pmi->palette_colors, n,
146
0
                            cache_color_found, out_cache_colors);
147
0
  const int total_bits =
148
0
      n_cache + delta_encode_cost(out_cache_colors, n_out_cache, bit_depth, 1);
149
0
  return av1_cost_literal(total_bits);
150
0
}
151
152
int av1_palette_color_cost_uv(const PALETTE_MODE_INFO *const pmi,
153
                              const uint16_t *color_cache, int n_cache,
154
0
                              int bit_depth) {
155
0
  const int n = pmi->palette_size[1];
156
0
  int total_bits = 0;
157
  // U channel palette color cost.
158
0
  int out_cache_colors[PALETTE_MAX_SIZE];
159
0
  uint8_t cache_color_found[2 * PALETTE_MAX_SIZE];
160
0
  const int n_out_cache = av1_index_color_cache(
161
0
      color_cache, n_cache, pmi->palette_colors + PALETTE_MAX_SIZE, n,
162
0
      cache_color_found, out_cache_colors);
163
0
  total_bits +=
164
0
      n_cache + delta_encode_cost(out_cache_colors, n_out_cache, bit_depth, 0);
165
166
  // V channel palette color cost.
167
0
  int zero_count = 0, min_bits_v = 0;
168
0
  const int bits_v =
169
0
      av1_get_palette_delta_bits_v(pmi, bit_depth, &zero_count, &min_bits_v);
170
0
  const int bits_using_delta =
171
0
      2 + bit_depth + (bits_v + 1) * (n - 1) - zero_count;
172
0
  const int bits_using_raw = bit_depth * n;
173
0
  total_bits += 1 + AOMMIN(bits_using_delta, bits_using_raw);
174
0
  return av1_cost_literal(total_bits);
175
0
}
176
177
// Extends 'color_map' array from 'orig_width x orig_height' to 'new_width x
178
// new_height'. Extra rows and columns are filled in by copying last valid
179
// row/column.
180
static inline void extend_palette_color_map(uint8_t *const color_map,
181
                                            int orig_width, int orig_height,
182
0
                                            int new_width, int new_height) {
183
0
  int j;
184
0
  assert(new_width >= orig_width);
185
0
  assert(new_height >= orig_height);
186
0
  if (new_width == orig_width && new_height == orig_height) return;
187
188
0
  for (j = orig_height - 1; j >= 0; --j) {
189
0
    memmove(color_map + j * new_width, color_map + j * orig_width, orig_width);
190
    // Copy last column to extra columns.
191
0
    memset(color_map + j * new_width + orig_width,
192
0
           color_map[j * new_width + orig_width - 1], new_width - orig_width);
193
0
  }
194
  // Copy last row to extra rows.
195
0
  for (j = orig_height; j < new_height; ++j) {
196
0
    memcpy(color_map + j * new_width, color_map + (orig_height - 1) * new_width,
197
0
           new_width);
198
0
  }
199
0
}
200
201
// Bias toward using colors in the cache.
202
// TODO(huisu): Try other schemes to improve compression.
203
static inline void optimize_palette_colors(uint16_t *color_cache, int n_cache,
204
                                           int n_colors, int stride,
205
0
                                           int16_t *centroids, int bit_depth) {
206
0
  if (n_cache <= 0) return;
207
0
  for (int i = 0; i < n_colors * stride; i += stride) {
208
0
    int min_diff = abs((int)centroids[i] - (int)color_cache[0]);
209
0
    int idx = 0;
210
0
    for (int j = 1; j < n_cache; ++j) {
211
0
      const int this_diff = abs((int)centroids[i] - (int)color_cache[j]);
212
0
      if (this_diff < min_diff) {
213
0
        min_diff = this_diff;
214
0
        idx = j;
215
0
      }
216
0
    }
217
0
    const int min_threshold = 4 << (bit_depth - 8);
218
0
    if (min_diff <= min_threshold) centroids[i] = color_cache[idx];
219
0
  }
220
0
}
221
222
/*!\brief Calculate the luma palette cost from a given color palette
223
 *
224
 * \ingroup palette_mode_search
225
 * \callergraph
226
 * Given the base colors as specified in centroids[], calculate the RD cost
227
 * of palette mode.
228
 */
229
static inline void palette_rd_y(
230
    const AV1_COMP *const cpi, MACROBLOCK *x, MB_MODE_INFO *mbmi,
231
    BLOCK_SIZE bsize, int dc_mode_cost, const int16_t *data, int16_t *centroids,
232
    int n, uint16_t *color_cache, int n_cache, bool do_header_rd_based_gating,
233
    MB_MODE_INFO *best_mbmi, uint8_t *best_palette_color_map, int64_t *best_rd,
234
    int *rate, int *rate_tokenonly, int64_t *distortion, uint8_t *skippable,
235
    int *beat_best_rd, PICK_MODE_CONTEXT *ctx, uint8_t *tx_type_map,
236
    int *beat_best_palette_rd, bool *do_header_rd_based_breakout,
237
0
    int discount_color_cost) {
238
0
  if (do_header_rd_based_breakout != NULL) *do_header_rd_based_breakout = false;
239
0
  optimize_palette_colors(color_cache, n_cache, n, 1, centroids,
240
0
                          cpi->common.seq_params->bit_depth);
241
0
  const int num_unique_colors = remove_duplicates(centroids, n);
242
0
  if (num_unique_colors < PALETTE_MIN_SIZE) {
243
    // Too few unique colors to create a palette. And DC_PRED will work
244
    // well for that case anyway. So skip.
245
0
    return;
246
0
  }
247
0
  PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
248
0
  if (cpi->common.seq_params->use_highbitdepth) {
249
0
    for (int i = 0; i < num_unique_colors; ++i) {
250
0
      pmi->palette_colors[i] = clip_pixel_highbd(
251
0
          (int)centroids[i], cpi->common.seq_params->bit_depth);
252
0
    }
253
0
  } else {
254
0
    for (int i = 0; i < num_unique_colors; ++i) {
255
0
      pmi->palette_colors[i] = clip_pixel(centroids[i]);
256
0
    }
257
0
  }
258
0
  pmi->palette_size[0] = num_unique_colors;
259
0
  MACROBLOCKD *const xd = &x->e_mbd;
260
0
  uint8_t *const color_map = xd->plane[0].color_index_map;
261
0
  int block_width, block_height, rows, cols;
262
0
  av1_get_block_dimensions(bsize, 0, xd, &block_width, &block_height, &rows,
263
0
                           &cols);
264
0
  av1_calc_indices(data, centroids, color_map, rows * cols, num_unique_colors,
265
0
                   1);
266
0
  extend_palette_color_map(color_map, cols, rows, block_width, block_height);
267
268
0
  RD_STATS tokenonly_rd_stats;
269
0
  int this_rate;
270
271
0
  if (do_header_rd_based_gating) {
272
0
    assert(do_header_rd_based_breakout != NULL);
273
0
    const int palette_mode_rate = intra_mode_info_cost_y(
274
0
        cpi, x, mbmi, bsize, dc_mode_cost, discount_color_cost);
275
0
    const int64_t header_rd = RDCOST(x->rdmult, palette_mode_rate, 0);
276
    // Less aggressive pruning when prune_luma_palette_size_search_level == 1.
277
0
    const int header_rd_shift =
278
0
        (cpi->sf.intra_sf.prune_luma_palette_size_search_level == 1) ? 1 : 0;
279
    // Terminate further palette_size search, if the header cost corresponding
280
    // to lower palette_size is more than *best_rd << header_rd_shift. This
281
    // logic is implemented with a right shift in the LHS to prevent a possible
282
    // overflow with the left shift in RHS.
283
0
    if ((header_rd >> header_rd_shift) > *best_rd) {
284
0
      *do_header_rd_based_breakout = true;
285
0
      return;
286
0
    }
287
0
    av1_pick_uniform_tx_size_type_yrd(cpi, x, &tokenonly_rd_stats, bsize,
288
0
                                      *best_rd);
289
0
    if (tokenonly_rd_stats.rate == INT_MAX) return;
290
0
    this_rate = tokenonly_rd_stats.rate + palette_mode_rate;
291
0
  } else {
292
0
    av1_pick_uniform_tx_size_type_yrd(cpi, x, &tokenonly_rd_stats, bsize,
293
0
                                      *best_rd);
294
0
    if (tokenonly_rd_stats.rate == INT_MAX) return;
295
0
    this_rate = tokenonly_rd_stats.rate +
296
0
                intra_mode_info_cost_y(cpi, x, mbmi, bsize, dc_mode_cost,
297
0
                                       discount_color_cost);
298
0
  }
299
300
0
  int64_t this_rd = RDCOST(x->rdmult, this_rate, tokenonly_rd_stats.dist);
301
0
  if (!xd->lossless[mbmi->segment_id] && block_signals_txsize(mbmi->bsize)) {
302
0
    tokenonly_rd_stats.rate -= tx_size_cost(x, bsize, mbmi->tx_size);
303
0
  }
304
  // Collect mode stats for multiwinner mode processing
305
0
  const int txfm_search_done = 1;
306
0
  store_winner_mode_stats(
307
0
      &cpi->common, x, mbmi, NULL, NULL, NULL, THR_DC, color_map, bsize,
308
0
      this_rd, cpi->sf.winner_mode_sf.multi_winner_mode_type, txfm_search_done);
309
0
  if (this_rd < *best_rd) {
310
0
    *best_rd = this_rd;
311
    // Setting beat_best_rd flag because current mode rd is better than best_rd.
312
    // This flag need to be updated only for palette evaluation in key frames
313
0
    if (beat_best_rd) *beat_best_rd = 1;
314
0
    memcpy(best_palette_color_map, color_map,
315
0
           block_width * block_height * sizeof(color_map[0]));
316
0
    *best_mbmi = *mbmi;
317
0
    av1_copy_array(tx_type_map, xd->tx_type_map, ctx->num_4x4_blk);
318
0
    if (rate) *rate = this_rate;
319
0
    if (rate_tokenonly) *rate_tokenonly = tokenonly_rd_stats.rate;
320
0
    if (distortion) *distortion = tokenonly_rd_stats.dist;
321
0
    if (skippable) *skippable = tokenonly_rd_stats.skip_txfm;
322
0
    if (beat_best_palette_rd) *beat_best_palette_rd = 1;
323
0
  }
324
0
}
325
326
0
static inline int is_iter_over(int curr_idx, int end_idx, int step_size) {
327
0
  assert(step_size != 0);
328
0
  return (step_size > 0) ? curr_idx >= end_idx : curr_idx <= end_idx;
329
0
}
330
331
// Performs count-based palette search with number of colors in interval
332
// [start_n, end_n) with step size step_size. If step_size < 0, then end_n can
333
// be less than start_n. Saves the last numbers searched in last_n_searched and
334
// returns the best number of colors found.
335
static inline int perform_top_color_palette_search(
336
    const AV1_COMP *const cpi, MACROBLOCK *x, MB_MODE_INFO *mbmi,
337
    BLOCK_SIZE bsize, int dc_mode_cost, const int16_t *data,
338
    int16_t *top_colors, int start_n, int end_n, int step_size,
339
    bool do_header_rd_based_gating, int *last_n_searched, uint16_t *color_cache,
340
    int n_cache, MB_MODE_INFO *best_mbmi, uint8_t *best_palette_color_map,
341
    int64_t *best_rd, int *rate, int *rate_tokenonly, int64_t *distortion,
342
    uint8_t *skippable, int *beat_best_rd, PICK_MODE_CONTEXT *ctx,
343
0
    uint8_t *tx_type_map, int discount_color_cost) {
344
0
  int16_t centroids[PALETTE_MAX_SIZE];
345
0
  int n = start_n;
346
0
  int top_color_winner = end_n;
347
  /* clang-format off */
348
0
  assert(IMPLIES(step_size < 0, start_n > end_n));
349
  /* clang-format on */
350
0
  assert(IMPLIES(step_size > 0, start_n < end_n));
351
0
  while (!is_iter_over(n, end_n, step_size)) {
352
0
    int beat_best_palette_rd = 0;
353
0
    bool do_header_rd_based_breakout = false;
354
0
    memcpy(centroids, top_colors, n * sizeof(top_colors[0]));
355
0
    palette_rd_y(cpi, x, mbmi, bsize, dc_mode_cost, data, centroids, n,
356
0
                 color_cache, n_cache, do_header_rd_based_gating, best_mbmi,
357
0
                 best_palette_color_map, best_rd, rate, rate_tokenonly,
358
0
                 distortion, skippable, beat_best_rd, ctx, tx_type_map,
359
0
                 &beat_best_palette_rd, &do_header_rd_based_breakout,
360
0
                 discount_color_cost);
361
0
    *last_n_searched = n;
362
0
    if (do_header_rd_based_breakout) {
363
      // Terminate palette_size search by setting last_n_searched to end_n.
364
0
      *last_n_searched = end_n;
365
0
      break;
366
0
    }
367
0
    if (beat_best_palette_rd) {
368
0
      top_color_winner = n;
369
0
    } else if (cpi->sf.intra_sf.prune_palette_search_level == 2) {
370
      // At search level 2, we return immediately if we don't see an improvement
371
0
      return top_color_winner;
372
0
    }
373
0
    n += step_size;
374
0
  }
375
0
  return top_color_winner;
376
0
}
377
378
// Performs k-means based palette search with number of colors in interval
379
// [start_n, end_n) with step size step_size. If step_size < 0, then end_n can
380
// be less than start_n. Saves the last numbers searched in last_n_searched and
381
// returns the best number of colors found.
382
static inline int perform_k_means_palette_search(
383
    const AV1_COMP *const cpi, MACROBLOCK *x, MB_MODE_INFO *mbmi,
384
    BLOCK_SIZE bsize, int dc_mode_cost, const int16_t *data, int lower_bound,
385
    int upper_bound, int start_n, int end_n, int step_size,
386
    bool do_header_rd_based_gating, int *last_n_searched, uint16_t *color_cache,
387
    int n_cache, MB_MODE_INFO *best_mbmi, uint8_t *best_palette_color_map,
388
    int64_t *best_rd, int *rate, int *rate_tokenonly, int64_t *distortion,
389
    uint8_t *skippable, int *beat_best_rd, PICK_MODE_CONTEXT *ctx,
390
    uint8_t *tx_type_map, uint8_t *color_map, int data_points,
391
0
    int discount_color_cost) {
392
0
  int16_t centroids[PALETTE_MAX_SIZE];
393
0
  const int max_itr = 50;
394
0
  int n = start_n;
395
0
  int top_color_winner = end_n;
396
  /* clang-format off */
397
0
  assert(IMPLIES(step_size < 0, start_n > end_n));
398
  /* clang-format on */
399
0
  assert(IMPLIES(step_size > 0, start_n < end_n));
400
0
  while (!is_iter_over(n, end_n, step_size)) {
401
0
    int beat_best_palette_rd = 0;
402
0
    bool do_header_rd_based_breakout = false;
403
0
    for (int i = 0; i < n; ++i) {
404
0
      centroids[i] =
405
0
          lower_bound + (2 * i + 1) * (upper_bound - lower_bound) / n / 2;
406
0
    }
407
0
    av1_k_means(data, centroids, color_map, data_points, n, 1, max_itr);
408
0
    palette_rd_y(cpi, x, mbmi, bsize, dc_mode_cost, data, centroids, n,
409
0
                 color_cache, n_cache, do_header_rd_based_gating, best_mbmi,
410
0
                 best_palette_color_map, best_rd, rate, rate_tokenonly,
411
0
                 distortion, skippable, beat_best_rd, ctx, tx_type_map,
412
0
                 &beat_best_palette_rd, &do_header_rd_based_breakout,
413
0
                 discount_color_cost);
414
0
    *last_n_searched = n;
415
0
    if (do_header_rd_based_breakout) {
416
      // Terminate palette_size search by setting last_n_searched to end_n.
417
0
      *last_n_searched = end_n;
418
0
      break;
419
0
    }
420
0
    if (beat_best_palette_rd) {
421
0
      top_color_winner = n;
422
0
    } else if (cpi->sf.intra_sf.prune_palette_search_level == 2) {
423
      // At search level 2, we return immediately if we don't see an improvement
424
0
      return top_color_winner;
425
0
    }
426
0
    n += step_size;
427
0
  }
428
0
  return top_color_winner;
429
0
}
430
431
// Sets the parameters to search the current number of colors +- 1
432
static inline void set_stage2_params(int *min_n, int *max_n, int *step_size,
433
0
                                     int winner, int end_n) {
434
  // Set min to winner - 1 unless we are already at the border, then we set it
435
  // to winner + 1
436
0
  *min_n = (winner == PALETTE_MIN_SIZE) ? (PALETTE_MIN_SIZE + 1)
437
0
                                        : AOMMAX(winner - 1, PALETTE_MIN_SIZE);
438
  // Set max to winner + 1 unless we are already at the border, then we set it
439
  // to winner - 1
440
0
  *max_n =
441
0
      (winner == end_n) ? (winner - 1) : AOMMIN(winner + 1, PALETTE_MAX_SIZE);
442
443
  // Set the step size to max_n - min_n so we only search those two values.
444
  // If max_n == min_n, then set step_size to 1 to avoid infinite loop later.
445
0
  *step_size = AOMMAX(1, *max_n - *min_n);
446
0
}
447
448
static inline void fill_data_and_get_bounds(const uint8_t *src,
449
                                            const int src_stride,
450
                                            const int rows, const int cols,
451
                                            const int is_high_bitdepth,
452
                                            int16_t *data, int *lower_bound,
453
0
                                            int *upper_bound) {
454
0
  if (is_high_bitdepth) {
455
0
    const uint16_t *src_ptr = CONVERT_TO_SHORTPTR(src);
456
0
    *lower_bound = *upper_bound = src_ptr[0];
457
0
    for (int r = 0; r < rows; ++r) {
458
0
      for (int c = 0; c < cols; ++c) {
459
0
        const int val = src_ptr[c];
460
0
        data[c] = (int16_t)val;
461
0
        *lower_bound = AOMMIN(*lower_bound, val);
462
0
        *upper_bound = AOMMAX(*upper_bound, val);
463
0
      }
464
0
      src_ptr += src_stride;
465
0
      data += cols;
466
0
    }
467
0
    return;
468
0
  }
469
470
  // low bit depth
471
0
  *lower_bound = *upper_bound = src[0];
472
0
  for (int r = 0; r < rows; ++r) {
473
0
    for (int c = 0; c < cols; ++c) {
474
0
      const int val = src[c];
475
0
      data[c] = (int16_t)val;
476
0
      *lower_bound = AOMMIN(*lower_bound, val);
477
0
      *upper_bound = AOMMAX(*upper_bound, val);
478
0
    }
479
0
    src += src_stride;
480
0
    data += cols;
481
0
  }
482
0
}
483
484
/*! \brief Colors are sorted by their count: the higher the better.
485
 */
486
struct ColorCount {
487
  //! Color index in the histogram.
488
  int index;
489
  //! Histogram count.
490
  int count;
491
};
492
493
0
static int color_count_comp(const void *c1, const void *c2) {
494
0
  const struct ColorCount *color_count1 = (const struct ColorCount *)c1;
495
0
  const struct ColorCount *color_count2 = (const struct ColorCount *)c2;
496
0
  if (color_count1->count > color_count2->count) return -1;
497
0
  if (color_count1->count < color_count2->count) return 1;
498
0
  if (color_count1->index < color_count2->index) return -1;
499
0
  return 1;
500
0
}
501
502
static void find_top_colors(const int *const count_buf, int bit_depth,
503
0
                            int n_colors, int16_t *top_colors) {
504
  // Top color array, serving as a priority queue if more than n_colors are
505
  // found.
506
0
  struct ColorCount top_color_counts[PALETTE_MAX_SIZE] = { { 0 } };
507
0
  int n_color_count = 0;
508
0
  for (int i = 0; i < (1 << bit_depth); ++i) {
509
0
    if (count_buf[i] > 0) {
510
0
      if (n_color_count < n_colors) {
511
        // Keep adding to the top colors.
512
0
        top_color_counts[n_color_count].index = i;
513
0
        top_color_counts[n_color_count].count = count_buf[i];
514
0
        ++n_color_count;
515
0
        if (n_color_count == n_colors) {
516
0
          qsort(top_color_counts, n_colors, sizeof(top_color_counts[0]),
517
0
                color_count_comp);
518
0
        }
519
0
      } else {
520
        // Check the worst in the sorted top.
521
0
        if (count_buf[i] > top_color_counts[n_colors - 1].count) {
522
0
          int j = n_colors - 1;
523
          // Move up to the best one.
524
0
          while (j >= 1 && count_buf[i] > top_color_counts[j - 1].count) --j;
525
0
          memmove(top_color_counts + j + 1, top_color_counts + j,
526
0
                  (n_colors - j - 1) * sizeof(top_color_counts[0]));
527
0
          top_color_counts[j].index = i;
528
0
          top_color_counts[j].count = count_buf[i];
529
0
        }
530
0
      }
531
0
    }
532
0
  }
533
0
  assert(n_color_count == n_colors);
534
535
0
  for (int i = 0; i < n_colors; ++i) {
536
0
    top_colors[i] = top_color_counts[i].index;
537
0
  }
538
0
}
539
540
void av1_rd_pick_palette_intra_sby(
541
    const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int dc_mode_cost,
542
    MB_MODE_INFO *best_mbmi, uint8_t *best_palette_color_map, int64_t *best_rd,
543
    int *rate, int *rate_tokenonly, int64_t *distortion, uint8_t *skippable,
544
0
    int *beat_best_rd, PICK_MODE_CONTEXT *ctx, uint8_t *tx_type_map) {
545
0
  MACROBLOCKD *const xd = &x->e_mbd;
546
0
  MB_MODE_INFO *const mbmi = xd->mi[0];
547
0
  assert(!is_inter_block(mbmi));
548
0
  assert(av1_allow_palette(cpi->common.features.allow_screen_content_tools,
549
0
                           bsize));
550
0
  assert(PALETTE_MAX_SIZE == 8);
551
0
  assert(PALETTE_MIN_SIZE == 2);
552
553
0
  const int src_stride = x->plane[0].src.stride;
554
0
  const uint8_t *const src = x->plane[0].src.buf;
555
0
  int block_width, block_height, rows, cols;
556
0
  av1_get_block_dimensions(bsize, 0, xd, &block_width, &block_height, &rows,
557
0
                           &cols);
558
0
  const SequenceHeader *const seq_params = cpi->common.seq_params;
559
0
  const int is_hbd = seq_params->use_highbitdepth;
560
0
  const int bit_depth = seq_params->bit_depth;
561
0
  const int discount_color_cost = cpi->sf.rt_sf.discount_color_cost;
562
0
  int unused;
563
564
0
  int count_buf[1 << 12];  // Maximum (1 << 12) color levels.
565
0
  int colors, colors_threshold = 0;
566
0
  if (is_hbd) {
567
0
    int count_buf_8bit[1 << 8];  // Maximum (1 << 8) bins for hbd path.
568
0
    av1_count_colors_highbd(src, src_stride, rows, cols, bit_depth, count_buf,
569
0
                            count_buf_8bit, &colors_threshold, &colors);
570
0
  } else {
571
0
    av1_count_colors(src, src_stride, rows, cols, count_buf, &colors);
572
0
    colors_threshold = colors;
573
0
  }
574
575
0
  uint8_t *const color_map = xd->plane[0].color_index_map;
576
0
  int color_thresh_palette = x->color_palette_thresh;
577
  // Allow for larger color_threshold for palette search, based on color,
578
  // scene_change, and block source variance.
579
  // Since palette is Y based, only allow larger threshold if block
580
  // color_dist is below threshold.
581
0
  if (cpi->sf.rt_sf.use_nonrd_pick_mode &&
582
0
      cpi->sf.rt_sf.increase_color_thresh_palette && cpi->rc.high_source_sad &&
583
0
      x->source_variance > 50) {
584
0
    int64_t norm_color_dist = 0;
585
0
    if (x->color_sensitivity[0] || x->color_sensitivity[1]) {
586
0
      norm_color_dist = x->min_dist_inter_uv >>
587
0
                        (mi_size_wide_log2[bsize] + mi_size_high_log2[bsize]);
588
0
      if (x->color_sensitivity[0] && x->color_sensitivity[1])
589
0
        norm_color_dist = norm_color_dist >> 1;
590
0
    }
591
0
    if (norm_color_dist < 8000) color_thresh_palette += 20;
592
0
  }
593
0
  if (colors_threshold > 1 && colors_threshold <= color_thresh_palette) {
594
0
    int16_t *const data = x->palette_buffer->kmeans_data_buf;
595
0
    int16_t centroids[PALETTE_MAX_SIZE];
596
0
    int lower_bound, upper_bound;
597
0
    fill_data_and_get_bounds(src, src_stride, rows, cols, is_hbd, data,
598
0
                             &lower_bound, &upper_bound);
599
600
0
    mbmi->mode = DC_PRED;
601
0
    mbmi->filter_intra_mode_info.use_filter_intra = 0;
602
603
0
    uint16_t color_cache[2 * PALETTE_MAX_SIZE];
604
0
    const int n_cache = av1_get_palette_cache(xd, 0, color_cache);
605
606
    // Find the dominant colors, stored in top_colors[].
607
0
    int16_t top_colors[PALETTE_MAX_SIZE] = { 0 };
608
0
    find_top_colors(count_buf, bit_depth, AOMMIN(colors, PALETTE_MAX_SIZE),
609
0
                    top_colors);
610
611
    // The following are the approaches used for header rdcost based gating
612
    // for early termination for different values of prune_palette_search_level.
613
    // 0: Pruning based on header rdcost for ascending order palette_size
614
    // search.
615
    // 1: When colors > PALETTE_MIN_SIZE, enabled only for coarse palette_size
616
    // search and for finer search do_header_rd_based_gating parameter is
617
    // explicitly passed as 'false'.
618
    // 2: Enabled only for ascending order palette_size search and for
619
    // descending order search do_header_rd_based_gating parameter is explicitly
620
    // passed as 'false'.
621
0
    const bool do_header_rd_based_gating =
622
0
        cpi->sf.intra_sf.prune_luma_palette_size_search_level != 0;
623
624
    // TODO(huisu@google.com): Try to avoid duplicate computation in cases
625
    // where the dominant colors and the k-means results are similar.
626
0
    if ((cpi->sf.intra_sf.prune_palette_search_level == 1) &&
627
0
        (colors > PALETTE_MIN_SIZE)) {
628
      // Start index and step size below are chosen to evaluate unique
629
      // candidates in neighbor search, in case a winner candidate is found in
630
      // coarse search. Example,
631
      // 1) 8 colors (end_n = 8): 2,3,4,5,6,7,8. start_n is chosen as 2 and step
632
      // size is chosen as 3. Therefore, coarse search will evaluate 2, 5 and 8.
633
      // If winner is found at 5, then 4 and 6 are evaluated. Similarly, for 2
634
      // (3) and 8 (7).
635
      // 2) 7 colors (end_n = 7): 2,3,4,5,6,7. If start_n is chosen as 2 (same
636
      // as for 8 colors) then step size should also be 2, to cover all
637
      // candidates. Coarse search will evaluate 2, 4 and 6. If winner is either
638
      // 2 or 4, 3 will be evaluated. Instead, if start_n=3 and step_size=3,
639
      // coarse search will evaluate 3 and 6. For the winner, unique neighbors
640
      // (3: 2,4 or 6: 5,7) would be evaluated.
641
642
      // Start index for coarse palette search for dominant colors and k-means
643
0
      const uint8_t start_n_lookup_table[PALETTE_MAX_SIZE + 1] = { 0, 0, 0,
644
0
                                                                   3, 3, 2,
645
0
                                                                   3, 3, 2 };
646
      // Step size for coarse palette search for dominant colors and k-means
647
0
      const uint8_t step_size_lookup_table[PALETTE_MAX_SIZE + 1] = { 0, 0, 0,
648
0
                                                                     3, 3, 3,
649
0
                                                                     3, 3, 3 };
650
651
      // Choose the start index and step size for coarse search based on number
652
      // of colors
653
0
      const int max_n = AOMMIN(colors, PALETTE_MAX_SIZE);
654
0
      const int min_n = start_n_lookup_table[max_n];
655
0
      const int step_size = step_size_lookup_table[max_n];
656
0
      assert(min_n >= PALETTE_MIN_SIZE);
657
      // Perform top color coarse palette search to find the winner candidate
658
0
      const int top_color_winner = perform_top_color_palette_search(
659
0
          cpi, x, mbmi, bsize, dc_mode_cost, data, top_colors, min_n, max_n + 1,
660
0
          step_size, do_header_rd_based_gating, &unused, color_cache, n_cache,
661
0
          best_mbmi, best_palette_color_map, best_rd, rate, rate_tokenonly,
662
0
          distortion, skippable, beat_best_rd, ctx, tx_type_map,
663
0
          discount_color_cost);
664
      // Evaluate neighbors for the winner color (if winner is found) in the
665
      // above coarse search for dominant colors
666
0
      if (top_color_winner <= max_n) {
667
0
        int stage2_min_n, stage2_max_n, stage2_step_size;
668
0
        set_stage2_params(&stage2_min_n, &stage2_max_n, &stage2_step_size,
669
0
                          top_color_winner, max_n);
670
        // perform finer search for the winner candidate
671
0
        perform_top_color_palette_search(
672
0
            cpi, x, mbmi, bsize, dc_mode_cost, data, top_colors, stage2_min_n,
673
0
            stage2_max_n + 1, stage2_step_size,
674
0
            /*do_header_rd_based_gating=*/false, &unused, color_cache, n_cache,
675
0
            best_mbmi, best_palette_color_map, best_rd, rate, rate_tokenonly,
676
0
            distortion, skippable, beat_best_rd, ctx, tx_type_map,
677
0
            discount_color_cost);
678
0
      }
679
      // K-means clustering.
680
      // Perform k-means coarse palette search to find the winner candidate
681
0
      const int k_means_winner = perform_k_means_palette_search(
682
0
          cpi, x, mbmi, bsize, dc_mode_cost, data, lower_bound, upper_bound,
683
0
          min_n, max_n + 1, step_size, do_header_rd_based_gating, &unused,
684
0
          color_cache, n_cache, best_mbmi, best_palette_color_map, best_rd,
685
0
          rate, rate_tokenonly, distortion, skippable, beat_best_rd, ctx,
686
0
          tx_type_map, color_map, rows * cols, discount_color_cost);
687
      // Evaluate neighbors for the winner color (if winner is found) in the
688
      // above coarse search for k-means
689
0
      if (k_means_winner <= max_n) {
690
0
        int start_n_stage2, end_n_stage2, step_size_stage2;
691
0
        set_stage2_params(&start_n_stage2, &end_n_stage2, &step_size_stage2,
692
0
                          k_means_winner, max_n);
693
        // perform finer search for the winner candidate
694
0
        perform_k_means_palette_search(
695
0
            cpi, x, mbmi, bsize, dc_mode_cost, data, lower_bound, upper_bound,
696
0
            start_n_stage2, end_n_stage2 + 1, step_size_stage2,
697
0
            /*do_header_rd_based_gating=*/false, &unused, color_cache, n_cache,
698
0
            best_mbmi, best_palette_color_map, best_rd, rate, rate_tokenonly,
699
0
            distortion, skippable, beat_best_rd, ctx, tx_type_map, color_map,
700
0
            rows * cols, discount_color_cost);
701
0
      }
702
0
    } else {
703
0
      const int max_n = AOMMIN(colors, PALETTE_MAX_SIZE),
704
0
                min_n = PALETTE_MIN_SIZE;
705
      // Perform top color palette search in ascending order
706
0
      int last_n_searched = min_n;
707
0
      perform_top_color_palette_search(
708
0
          cpi, x, mbmi, bsize, dc_mode_cost, data, top_colors, min_n, max_n + 1,
709
0
          1, do_header_rd_based_gating, &last_n_searched, color_cache, n_cache,
710
0
          best_mbmi, best_palette_color_map, best_rd, rate, rate_tokenonly,
711
0
          distortion, skippable, beat_best_rd, ctx, tx_type_map,
712
0
          discount_color_cost);
713
0
      if (last_n_searched < max_n) {
714
        // Search in descending order until we get to the previous best
715
0
        perform_top_color_palette_search(
716
0
            cpi, x, mbmi, bsize, dc_mode_cost, data, top_colors, max_n,
717
0
            last_n_searched, -1, /*do_header_rd_based_gating=*/false, &unused,
718
0
            color_cache, n_cache, best_mbmi, best_palette_color_map, best_rd,
719
0
            rate, rate_tokenonly, distortion, skippable, beat_best_rd, ctx,
720
0
            tx_type_map, discount_color_cost);
721
0
      }
722
      // K-means clustering.
723
0
      if (colors == PALETTE_MIN_SIZE) {
724
        // Special case: These colors automatically become the centroids.
725
0
        assert(colors == 2);
726
0
        centroids[0] = lower_bound;
727
0
        centroids[1] = upper_bound;
728
0
        palette_rd_y(cpi, x, mbmi, bsize, dc_mode_cost, data, centroids, colors,
729
0
                     color_cache, n_cache, /*do_header_rd_based_gating=*/false,
730
0
                     best_mbmi, best_palette_color_map, best_rd, rate,
731
0
                     rate_tokenonly, distortion, skippable, beat_best_rd, ctx,
732
0
                     tx_type_map, NULL, NULL, discount_color_cost);
733
0
      } else {
734
        // Perform k-means palette search in ascending order
735
0
        last_n_searched = min_n;
736
0
        perform_k_means_palette_search(
737
0
            cpi, x, mbmi, bsize, dc_mode_cost, data, lower_bound, upper_bound,
738
0
            min_n, max_n + 1, 1, do_header_rd_based_gating, &last_n_searched,
739
0
            color_cache, n_cache, best_mbmi, best_palette_color_map, best_rd,
740
0
            rate, rate_tokenonly, distortion, skippable, beat_best_rd, ctx,
741
0
            tx_type_map, color_map, rows * cols, discount_color_cost);
742
0
        if (last_n_searched < max_n) {
743
          // Search in descending order until we get to the previous best
744
0
          perform_k_means_palette_search(
745
0
              cpi, x, mbmi, bsize, dc_mode_cost, data, lower_bound, upper_bound,
746
0
              max_n, last_n_searched, -1, /*do_header_rd_based_gating=*/false,
747
0
              &unused, color_cache, n_cache, best_mbmi, best_palette_color_map,
748
0
              best_rd, rate, rate_tokenonly, distortion, skippable,
749
0
              beat_best_rd, ctx, tx_type_map, color_map, rows * cols,
750
0
              discount_color_cost);
751
0
        }
752
0
      }
753
0
    }
754
0
  }
755
756
0
  if (best_mbmi->palette_mode_info.palette_size[0] > 0) {
757
0
    memcpy(color_map, best_palette_color_map,
758
0
           block_width * block_height * sizeof(best_palette_color_map[0]));
759
    // Gather the stats to determine whether to use screen content tools in
760
    // function av1_determine_sc_tools_with_encoding().
761
0
    x->palette_pixels += (block_width * block_height);
762
0
  }
763
0
  *mbmi = *best_mbmi;
764
0
}
765
766
void av1_rd_pick_palette_intra_sbuv(const AV1_COMP *cpi, MACROBLOCK *x,
767
                                    int dc_mode_cost,
768
                                    uint8_t *best_palette_color_map,
769
                                    MB_MODE_INFO *const best_mbmi,
770
                                    int64_t *best_rd, int *rate,
771
                                    int *rate_tokenonly, int64_t *distortion,
772
0
                                    uint8_t *skippable) {
773
0
  MACROBLOCKD *const xd = &x->e_mbd;
774
0
  MB_MODE_INFO *const mbmi = xd->mi[0];
775
0
  assert(!is_inter_block(mbmi));
776
0
  assert(av1_allow_palette(cpi->common.features.allow_screen_content_tools,
777
0
                           mbmi->bsize));
778
0
  PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
779
0
  const BLOCK_SIZE bsize = mbmi->bsize;
780
0
  const SequenceHeader *const seq_params = cpi->common.seq_params;
781
0
  int this_rate;
782
0
  int64_t this_rd;
783
0
  int colors_u, colors_v;
784
0
  int colors_threshold_u = 0, colors_threshold_v = 0, colors_threshold = 0;
785
0
  const int src_stride = x->plane[1].src.stride;
786
0
  const uint8_t *const src_u = x->plane[1].src.buf;
787
0
  const uint8_t *const src_v = x->plane[2].src.buf;
788
0
  uint8_t *const color_map = xd->plane[1].color_index_map;
789
0
  RD_STATS tokenonly_rd_stats;
790
0
  int plane_block_width, plane_block_height, rows, cols;
791
0
  av1_get_block_dimensions(bsize, 1, xd, &plane_block_width,
792
0
                           &plane_block_height, &rows, &cols);
793
794
0
  mbmi->uv_mode = UV_DC_PRED;
795
0
  if (seq_params->use_highbitdepth) {
796
0
    int count_buf[1 << 12];      // Maximum (1 << 12) color levels.
797
0
    int count_buf_8bit[1 << 8];  // Maximum (1 << 8) bins for hbd path.
798
0
    av1_count_colors_highbd(src_u, src_stride, rows, cols,
799
0
                            seq_params->bit_depth, count_buf, count_buf_8bit,
800
0
                            &colors_threshold_u, &colors_u);
801
0
    av1_count_colors_highbd(src_v, src_stride, rows, cols,
802
0
                            seq_params->bit_depth, count_buf, count_buf_8bit,
803
0
                            &colors_threshold_v, &colors_v);
804
0
  } else {
805
0
    int count_buf[1 << 8];
806
0
    av1_count_colors(src_u, src_stride, rows, cols, count_buf, &colors_u);
807
0
    av1_count_colors(src_v, src_stride, rows, cols, count_buf, &colors_v);
808
0
    colors_threshold_u = colors_u;
809
0
    colors_threshold_v = colors_v;
810
0
  }
811
812
0
  uint16_t color_cache[2 * PALETTE_MAX_SIZE];
813
0
  const int n_cache = av1_get_palette_cache(xd, 1, color_cache);
814
815
0
  colors_threshold = colors_threshold_u > colors_threshold_v
816
0
                         ? colors_threshold_u
817
0
                         : colors_threshold_v;
818
0
  if (colors_threshold > 1 && colors_threshold <= 64) {
819
0
    int r, c, n, i, j;
820
0
    const int max_itr = 50;
821
0
    int lb_u, ub_u, val_u;
822
0
    int lb_v, ub_v, val_v;
823
0
    int16_t *const data = x->palette_buffer->kmeans_data_buf;
824
0
    int16_t centroids[2 * PALETTE_MAX_SIZE];
825
826
0
    uint16_t *src_u16 = CONVERT_TO_SHORTPTR(src_u);
827
0
    uint16_t *src_v16 = CONVERT_TO_SHORTPTR(src_v);
828
0
    if (seq_params->use_highbitdepth) {
829
0
      lb_u = src_u16[0];
830
0
      ub_u = src_u16[0];
831
0
      lb_v = src_v16[0];
832
0
      ub_v = src_v16[0];
833
0
    } else {
834
0
      lb_u = src_u[0];
835
0
      ub_u = src_u[0];
836
0
      lb_v = src_v[0];
837
0
      ub_v = src_v[0];
838
0
    }
839
840
0
    for (r = 0; r < rows; ++r) {
841
0
      for (c = 0; c < cols; ++c) {
842
0
        if (seq_params->use_highbitdepth) {
843
0
          val_u = src_u16[r * src_stride + c];
844
0
          val_v = src_v16[r * src_stride + c];
845
0
          data[(r * cols + c) * 2] = val_u;
846
0
          data[(r * cols + c) * 2 + 1] = val_v;
847
0
        } else {
848
0
          val_u = src_u[r * src_stride + c];
849
0
          val_v = src_v[r * src_stride + c];
850
0
          data[(r * cols + c) * 2] = val_u;
851
0
          data[(r * cols + c) * 2 + 1] = val_v;
852
0
        }
853
0
        if (val_u < lb_u)
854
0
          lb_u = val_u;
855
0
        else if (val_u > ub_u)
856
0
          ub_u = val_u;
857
0
        if (val_v < lb_v)
858
0
          lb_v = val_v;
859
0
        else if (val_v > ub_v)
860
0
          ub_v = val_v;
861
0
      }
862
0
    }
863
864
0
    const int colors = colors_u > colors_v ? colors_u : colors_v;
865
0
    const int max_colors =
866
0
        colors > PALETTE_MAX_SIZE ? PALETTE_MAX_SIZE : colors;
867
0
    for (n = PALETTE_MIN_SIZE; n <= max_colors; ++n) {
868
0
      for (i = 0; i < n; ++i) {
869
0
        centroids[i * 2] = lb_u + (2 * i + 1) * (ub_u - lb_u) / n / 2;
870
0
        centroids[i * 2 + 1] = lb_v + (2 * i + 1) * (ub_v - lb_v) / n / 2;
871
0
      }
872
0
      av1_k_means(data, centroids, color_map, rows * cols, n, 2, max_itr);
873
0
      optimize_palette_colors(color_cache, n_cache, n, 2, centroids,
874
0
                              cpi->common.seq_params->bit_depth);
875
      // Sort the U channel colors in ascending order.
876
0
      for (i = 0; i < 2 * (n - 1); i += 2) {
877
0
        int min_idx = i;
878
0
        int min_val = centroids[i];
879
0
        for (j = i + 2; j < 2 * n; j += 2)
880
0
          if (centroids[j] < min_val) min_val = centroids[j], min_idx = j;
881
0
        if (min_idx != i) {
882
0
          int temp_u = centroids[i], temp_v = centroids[i + 1];
883
0
          centroids[i] = centroids[min_idx];
884
0
          centroids[i + 1] = centroids[min_idx + 1];
885
0
          centroids[min_idx] = temp_u, centroids[min_idx + 1] = temp_v;
886
0
        }
887
0
      }
888
0
      av1_calc_indices(data, centroids, color_map, rows * cols, n, 2);
889
0
      extend_palette_color_map(color_map, cols, rows, plane_block_width,
890
0
                               plane_block_height);
891
0
      pmi->palette_size[1] = n;
892
0
      for (i = 1; i < 3; ++i) {
893
0
        for (j = 0; j < n; ++j) {
894
0
          if (seq_params->use_highbitdepth)
895
0
            pmi->palette_colors[i * PALETTE_MAX_SIZE + j] = clip_pixel_highbd(
896
0
                (int)centroids[j * 2 + i - 1], seq_params->bit_depth);
897
0
          else
898
0
            pmi->palette_colors[i * PALETTE_MAX_SIZE + j] =
899
0
                clip_pixel((int)centroids[j * 2 + i - 1]);
900
0
        }
901
0
      }
902
903
0
      if (cpi->sf.intra_sf.early_term_chroma_palette_size_search) {
904
0
        const int palette_mode_rate =
905
0
            intra_mode_info_cost_uv(cpi, x, mbmi, bsize, dc_mode_cost);
906
0
        const int64_t header_rd = RDCOST(x->rdmult, palette_mode_rate, 0);
907
        // Terminate further palette_size search, if header cost corresponding
908
        // to lower palette_size is more than the best_rd.
909
0
        if (header_rd >= *best_rd) break;
910
0
        av1_txfm_uvrd(cpi, x, &tokenonly_rd_stats, bsize, *best_rd);
911
0
        if (tokenonly_rd_stats.rate == INT_MAX) continue;
912
0
        this_rate = tokenonly_rd_stats.rate + palette_mode_rate;
913
0
      } else {
914
0
        av1_txfm_uvrd(cpi, x, &tokenonly_rd_stats, bsize, *best_rd);
915
0
        if (tokenonly_rd_stats.rate == INT_MAX) continue;
916
0
        this_rate = tokenonly_rd_stats.rate +
917
0
                    intra_mode_info_cost_uv(cpi, x, mbmi, bsize, dc_mode_cost);
918
0
      }
919
920
0
      this_rd = RDCOST(x->rdmult, this_rate, tokenonly_rd_stats.dist);
921
0
      if (this_rd < *best_rd) {
922
0
        *best_rd = this_rd;
923
0
        *best_mbmi = *mbmi;
924
0
        memcpy(best_palette_color_map, color_map,
925
0
               plane_block_width * plane_block_height *
926
0
                   sizeof(best_palette_color_map[0]));
927
0
        *rate = this_rate;
928
0
        *distortion = tokenonly_rd_stats.dist;
929
0
        *rate_tokenonly = tokenonly_rd_stats.rate;
930
0
        *skippable = tokenonly_rd_stats.skip_txfm;
931
0
      }
932
0
    }
933
0
  }
934
0
  if (best_mbmi->palette_mode_info.palette_size[1] > 0) {
935
0
    memcpy(color_map, best_palette_color_map,
936
0
           plane_block_width * plane_block_height *
937
0
               sizeof(best_palette_color_map[0]));
938
0
  }
939
0
}
940
941
0
void av1_restore_uv_color_map(const AV1_COMP *cpi, MACROBLOCK *x) {
942
0
  MACROBLOCKD *const xd = &x->e_mbd;
943
0
  MB_MODE_INFO *const mbmi = xd->mi[0];
944
0
  PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
945
0
  const BLOCK_SIZE bsize = mbmi->bsize;
946
0
  int src_stride = x->plane[1].src.stride;
947
0
  const uint8_t *const src_u = x->plane[1].src.buf;
948
0
  const uint8_t *const src_v = x->plane[2].src.buf;
949
0
  int16_t *const data = x->palette_buffer->kmeans_data_buf;
950
0
  int16_t centroids[2 * PALETTE_MAX_SIZE];
951
0
  uint8_t *const color_map = xd->plane[1].color_index_map;
952
0
  int r, c;
953
0
  const uint16_t *const src_u16 = CONVERT_TO_SHORTPTR(src_u);
954
0
  const uint16_t *const src_v16 = CONVERT_TO_SHORTPTR(src_v);
955
0
  int plane_block_width, plane_block_height, rows, cols;
956
0
  av1_get_block_dimensions(bsize, 1, xd, &plane_block_width,
957
0
                           &plane_block_height, &rows, &cols);
958
959
0
  for (r = 0; r < rows; ++r) {
960
0
    for (c = 0; c < cols; ++c) {
961
0
      if (cpi->common.seq_params->use_highbitdepth) {
962
0
        data[(r * cols + c) * 2] = src_u16[r * src_stride + c];
963
0
        data[(r * cols + c) * 2 + 1] = src_v16[r * src_stride + c];
964
0
      } else {
965
0
        data[(r * cols + c) * 2] = src_u[r * src_stride + c];
966
0
        data[(r * cols + c) * 2 + 1] = src_v[r * src_stride + c];
967
0
      }
968
0
    }
969
0
  }
970
971
0
  for (r = 1; r < 3; ++r) {
972
0
    for (c = 0; c < pmi->palette_size[1]; ++c) {
973
0
      centroids[c * 2 + r - 1] = pmi->palette_colors[r * PALETTE_MAX_SIZE + c];
974
0
    }
975
0
  }
976
977
0
  av1_calc_indices(data, centroids, color_map, rows * cols,
978
0
                   pmi->palette_size[1], 2);
979
0
  extend_palette_color_map(color_map, cols, rows, plane_block_width,
980
0
                           plane_block_height);
981
0
}