1 /*
2 * Copyright (c) 2020, 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 "av1/common/cfl.h"
13 #include "av1/common/reconintra.h"
14 #include "av1/encoder/block.h"
15 #include "av1/encoder/hybrid_fwd_txfm.h"
16 #include "av1/common/idct.h"
17 #include "av1/encoder/model_rd.h"
18 #include "av1/encoder/random.h"
19 #include "av1/encoder/rdopt_utils.h"
20 #include "av1/encoder/sorting_network.h"
21 #include "av1/encoder/tx_prune_model_weights.h"
22 #include "av1/encoder/tx_search.h"
23 #include "av1/encoder/txb_rdopt.h"
24
25 #define PROB_THRESH_OFFSET_TX_TYPE 100
26
27 struct rdcost_block_args {
28 const AV1_COMP *cpi;
29 MACROBLOCK *x;
30 ENTROPY_CONTEXT t_above[MAX_MIB_SIZE];
31 ENTROPY_CONTEXT t_left[MAX_MIB_SIZE];
32 RD_STATS rd_stats;
33 int64_t current_rd;
34 int64_t best_rd;
35 int exit_early;
36 int incomplete_exit;
37 FAST_TX_SEARCH_MODE ftxs_mode;
38 int skip_trellis;
39 };
40
41 typedef struct {
42 int64_t rd;
43 int txb_entropy_ctx;
44 TX_TYPE tx_type;
45 } TxCandidateInfo;
46
47 // origin_threshold * 128 / 100
48 static const uint32_t skip_pred_threshold[3][BLOCK_SIZES_ALL] = {
49 {
50 64, 64, 64, 70, 60, 60, 68, 68, 68, 68, 68,
51 68, 68, 68, 68, 68, 64, 64, 70, 70, 68, 68,
52 },
53 {
54 88, 88, 88, 86, 87, 87, 68, 68, 68, 68, 68,
55 68, 68, 68, 68, 68, 88, 88, 86, 86, 68, 68,
56 },
57 {
58 90, 93, 93, 90, 93, 93, 74, 74, 74, 74, 74,
59 74, 74, 74, 74, 74, 90, 90, 90, 90, 74, 74,
60 },
61 };
62
63 // lookup table for predict_skip_txfm
64 // int max_tx_size = max_txsize_rect_lookup[bsize];
65 // if (tx_size_high[max_tx_size] > 16 || tx_size_wide[max_tx_size] > 16)
66 // max_tx_size = AOMMIN(max_txsize_lookup[bsize], TX_16X16);
67 static const TX_SIZE max_predict_sf_tx_size[BLOCK_SIZES_ALL] = {
68 TX_4X4, TX_4X8, TX_8X4, TX_8X8, TX_8X16, TX_16X8,
69 TX_16X16, TX_16X16, TX_16X16, TX_16X16, TX_16X16, TX_16X16,
70 TX_16X16, TX_16X16, TX_16X16, TX_16X16, TX_4X16, TX_16X4,
71 TX_8X8, TX_8X8, TX_16X16, TX_16X16,
72 };
73
74 // look-up table for sqrt of number of pixels in a transform block
75 // rounded up to the nearest integer.
76 static const int sqrt_tx_pixels_2d[TX_SIZES_ALL] = { 4, 8, 16, 32, 32, 6, 6,
77 12, 12, 23, 23, 32, 32, 8,
78 8, 16, 16, 23, 23 };
79
get_block_residue_hash(MACROBLOCK * x,BLOCK_SIZE bsize)80 static INLINE uint32_t get_block_residue_hash(MACROBLOCK *x, BLOCK_SIZE bsize) {
81 const int rows = block_size_high[bsize];
82 const int cols = block_size_wide[bsize];
83 const int16_t *diff = x->plane[0].src_diff;
84 const uint32_t hash =
85 av1_get_crc32c_value(&x->txfm_search_info.mb_rd_record->crc_calculator,
86 (uint8_t *)diff, 2 * rows * cols);
87 return (hash << 5) + bsize;
88 }
89
find_mb_rd_info(const MB_RD_RECORD * const mb_rd_record,const int64_t ref_best_rd,const uint32_t hash)90 static INLINE int32_t find_mb_rd_info(const MB_RD_RECORD *const mb_rd_record,
91 const int64_t ref_best_rd,
92 const uint32_t hash) {
93 int32_t match_index = -1;
94 if (ref_best_rd != INT64_MAX) {
95 for (int i = 0; i < mb_rd_record->num; ++i) {
96 const int index = (mb_rd_record->index_start + i) % RD_RECORD_BUFFER_LEN;
97 // If there is a match in the mb_rd_record, fetch the RD decision and
98 // terminate early.
99 if (mb_rd_record->mb_rd_info[index].hash_value == hash) {
100 match_index = index;
101 break;
102 }
103 }
104 }
105 return match_index;
106 }
107
fetch_mb_rd_info(int n4,const MB_RD_INFO * const mb_rd_info,RD_STATS * const rd_stats,MACROBLOCK * const x)108 static AOM_INLINE void fetch_mb_rd_info(int n4,
109 const MB_RD_INFO *const mb_rd_info,
110 RD_STATS *const rd_stats,
111 MACROBLOCK *const x) {
112 MACROBLOCKD *const xd = &x->e_mbd;
113 MB_MODE_INFO *const mbmi = xd->mi[0];
114 mbmi->tx_size = mb_rd_info->tx_size;
115 memcpy(x->txfm_search_info.blk_skip, mb_rd_info->blk_skip,
116 sizeof(mb_rd_info->blk_skip[0]) * n4);
117 av1_copy(mbmi->inter_tx_size, mb_rd_info->inter_tx_size);
118 av1_copy_array(xd->tx_type_map, mb_rd_info->tx_type_map, n4);
119 *rd_stats = mb_rd_info->rd_stats;
120 }
121
av1_pixel_diff_dist(const MACROBLOCK * x,int plane,int blk_row,int blk_col,const BLOCK_SIZE plane_bsize,const BLOCK_SIZE tx_bsize,unsigned int * block_mse_q8)122 int64_t av1_pixel_diff_dist(const MACROBLOCK *x, int plane, int blk_row,
123 int blk_col, const BLOCK_SIZE plane_bsize,
124 const BLOCK_SIZE tx_bsize,
125 unsigned int *block_mse_q8) {
126 int visible_rows, visible_cols;
127 const MACROBLOCKD *xd = &x->e_mbd;
128 get_txb_dimensions(xd, plane, plane_bsize, blk_row, blk_col, tx_bsize, NULL,
129 NULL, &visible_cols, &visible_rows);
130 const int diff_stride = block_size_wide[plane_bsize];
131 const int16_t *diff = x->plane[plane].src_diff;
132
133 diff += ((blk_row * diff_stride + blk_col) << MI_SIZE_LOG2);
134 uint64_t sse =
135 aom_sum_squares_2d_i16(diff, diff_stride, visible_cols, visible_rows);
136 if (block_mse_q8 != NULL) {
137 if (visible_cols > 0 && visible_rows > 0)
138 *block_mse_q8 =
139 (unsigned int)((256 * sse) / (visible_cols * visible_rows));
140 else
141 *block_mse_q8 = UINT_MAX;
142 }
143 return sse;
144 }
145
146 // Computes the residual block's SSE and mean on all visible 4x4s in the
147 // transform block
pixel_diff_stats(MACROBLOCK * x,int plane,int blk_row,int blk_col,const BLOCK_SIZE plane_bsize,const BLOCK_SIZE tx_bsize,unsigned int * block_mse_q8,int64_t * per_px_mean,uint64_t * block_var)148 static INLINE int64_t pixel_diff_stats(
149 MACROBLOCK *x, int plane, int blk_row, int blk_col,
150 const BLOCK_SIZE plane_bsize, const BLOCK_SIZE tx_bsize,
151 unsigned int *block_mse_q8, int64_t *per_px_mean, uint64_t *block_var) {
152 int visible_rows, visible_cols;
153 const MACROBLOCKD *xd = &x->e_mbd;
154 get_txb_dimensions(xd, plane, plane_bsize, blk_row, blk_col, tx_bsize, NULL,
155 NULL, &visible_cols, &visible_rows);
156 const int diff_stride = block_size_wide[plane_bsize];
157 const int16_t *diff = x->plane[plane].src_diff;
158
159 diff += ((blk_row * diff_stride + blk_col) << MI_SIZE_LOG2);
160 uint64_t sse = 0;
161 int sum = 0;
162 sse = aom_sum_sse_2d_i16(diff, diff_stride, visible_cols, visible_rows, &sum);
163 if (visible_cols > 0 && visible_rows > 0) {
164 double norm_factor = 1.0 / (visible_cols * visible_rows);
165 int sign_sum = sum > 0 ? 1 : -1;
166 // Conversion to transform domain
167 *per_px_mean = (int64_t)(norm_factor * abs(sum)) << 7;
168 *per_px_mean = sign_sum * (*per_px_mean);
169 *block_mse_q8 = (unsigned int)(norm_factor * (256 * sse));
170 *block_var = (uint64_t)(sse - (uint64_t)(norm_factor * sum * sum));
171 } else {
172 *block_mse_q8 = UINT_MAX;
173 }
174 return sse;
175 }
176
177 // Uses simple features on top of DCT coefficients to quickly predict
178 // whether optimal RD decision is to skip encoding the residual.
179 // The sse value is stored in dist.
predict_skip_txfm(MACROBLOCK * x,BLOCK_SIZE bsize,int64_t * dist,int reduced_tx_set)180 static int predict_skip_txfm(MACROBLOCK *x, BLOCK_SIZE bsize, int64_t *dist,
181 int reduced_tx_set) {
182 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
183 const int bw = block_size_wide[bsize];
184 const int bh = block_size_high[bsize];
185 const MACROBLOCKD *xd = &x->e_mbd;
186 const int16_t dc_q = av1_dc_quant_QTX(x->qindex, 0, xd->bd);
187
188 *dist = av1_pixel_diff_dist(x, 0, 0, 0, bsize, bsize, NULL);
189
190 const int64_t mse = *dist / bw / bh;
191 // Normalized quantizer takes the transform upscaling factor (8 for tx size
192 // smaller than 32) into account.
193 const int16_t normalized_dc_q = dc_q >> 3;
194 const int64_t mse_thresh = (int64_t)normalized_dc_q * normalized_dc_q / 8;
195 // For faster early skip decision, use dist to compare against threshold so
196 // that quality risk is less for the skip=1 decision. Otherwise, use mse
197 // since the fwd_txfm coeff checks will take care of quality
198 // TODO(any): Use dist to return 0 when skip_txfm_level is 1
199 int64_t pred_err = (txfm_params->skip_txfm_level >= 2) ? *dist : mse;
200 // Predict not to skip when error is larger than threshold.
201 if (pred_err > mse_thresh) return 0;
202 // Return as skip otherwise for aggressive early skip
203 else if (txfm_params->skip_txfm_level >= 2)
204 return 1;
205
206 const int max_tx_size = max_predict_sf_tx_size[bsize];
207 const int tx_h = tx_size_high[max_tx_size];
208 const int tx_w = tx_size_wide[max_tx_size];
209 DECLARE_ALIGNED(32, tran_low_t, coefs[32 * 32]);
210 TxfmParam param;
211 param.tx_type = DCT_DCT;
212 param.tx_size = max_tx_size;
213 param.bd = xd->bd;
214 param.is_hbd = is_cur_buf_hbd(xd);
215 param.lossless = 0;
216 param.tx_set_type = av1_get_ext_tx_set_type(
217 param.tx_size, is_inter_block(xd->mi[0]), reduced_tx_set);
218 const int bd_idx = (xd->bd == 8) ? 0 : ((xd->bd == 10) ? 1 : 2);
219 const uint32_t max_qcoef_thresh = skip_pred_threshold[bd_idx][bsize];
220 const int16_t *src_diff = x->plane[0].src_diff;
221 const int n_coeff = tx_w * tx_h;
222 const int16_t ac_q = av1_ac_quant_QTX(x->qindex, 0, xd->bd);
223 const uint32_t dc_thresh = max_qcoef_thresh * dc_q;
224 const uint32_t ac_thresh = max_qcoef_thresh * ac_q;
225 for (int row = 0; row < bh; row += tx_h) {
226 for (int col = 0; col < bw; col += tx_w) {
227 av1_fwd_txfm(src_diff + col, coefs, bw, ¶m);
228 // Operating on TX domain, not pixels; we want the QTX quantizers
229 const uint32_t dc_coef = (((uint32_t)abs(coefs[0])) << 7);
230 if (dc_coef >= dc_thresh) return 0;
231 for (int i = 1; i < n_coeff; ++i) {
232 const uint32_t ac_coef = (((uint32_t)abs(coefs[i])) << 7);
233 if (ac_coef >= ac_thresh) return 0;
234 }
235 }
236 src_diff += tx_h * bw;
237 }
238 return 1;
239 }
240
241 // Used to set proper context for early termination with skip = 1.
set_skip_txfm(MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bsize,int64_t dist)242 static AOM_INLINE void set_skip_txfm(MACROBLOCK *x, RD_STATS *rd_stats,
243 BLOCK_SIZE bsize, int64_t dist) {
244 MACROBLOCKD *const xd = &x->e_mbd;
245 MB_MODE_INFO *const mbmi = xd->mi[0];
246 const int n4 = bsize_to_num_blk(bsize);
247 const TX_SIZE tx_size = max_txsize_rect_lookup[bsize];
248 memset(xd->tx_type_map, DCT_DCT, sizeof(xd->tx_type_map[0]) * n4);
249 memset(mbmi->inter_tx_size, tx_size, sizeof(mbmi->inter_tx_size));
250 mbmi->tx_size = tx_size;
251 for (int i = 0; i < n4; ++i)
252 set_blk_skip(x->txfm_search_info.blk_skip, 0, i, 1);
253 rd_stats->skip_txfm = 1;
254 if (is_cur_buf_hbd(xd)) dist = ROUND_POWER_OF_TWO(dist, (xd->bd - 8) * 2);
255 rd_stats->dist = rd_stats->sse = (dist << 4);
256 // Though decision is to make the block as skip based on luma stats,
257 // it is possible that block becomes non skip after chroma rd. In addition
258 // intermediate non skip costs calculated by caller function will be
259 // incorrect, if rate is set as zero (i.e., if zero_blk_rate is not
260 // accounted). Hence intermediate rate is populated to code the luma tx blks
261 // as skip, the caller function based on final rd decision (i.e., skip vs
262 // non-skip) sets the final rate accordingly. Here the rate populated
263 // corresponds to coding all the tx blocks with zero_blk_rate (based on max tx
264 // size possible) in the current block. Eg: For 128*128 block, rate would be
265 // 4 * zero_blk_rate where zero_blk_rate corresponds to coding of one 64x64 tx
266 // block as 'all zeros'
267 ENTROPY_CONTEXT ctxa[MAX_MIB_SIZE];
268 ENTROPY_CONTEXT ctxl[MAX_MIB_SIZE];
269 av1_get_entropy_contexts(bsize, &xd->plane[0], ctxa, ctxl);
270 ENTROPY_CONTEXT *ta = ctxa;
271 ENTROPY_CONTEXT *tl = ctxl;
272 const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
273 TXB_CTX txb_ctx;
274 get_txb_ctx(bsize, tx_size, 0, ta, tl, &txb_ctx);
275 const int zero_blk_rate = x->coeff_costs.coeff_costs[txs_ctx][PLANE_TYPE_Y]
276 .txb_skip_cost[txb_ctx.txb_skip_ctx][1];
277 rd_stats->rate = zero_blk_rate *
278 (block_size_wide[bsize] >> tx_size_wide_log2[tx_size]) *
279 (block_size_high[bsize] >> tx_size_high_log2[tx_size]);
280 }
281
save_mb_rd_info(int n4,uint32_t hash,const MACROBLOCK * const x,const RD_STATS * const rd_stats,MB_RD_RECORD * mb_rd_record)282 static AOM_INLINE void save_mb_rd_info(int n4, uint32_t hash,
283 const MACROBLOCK *const x,
284 const RD_STATS *const rd_stats,
285 MB_RD_RECORD *mb_rd_record) {
286 int index;
287 if (mb_rd_record->num < RD_RECORD_BUFFER_LEN) {
288 index =
289 (mb_rd_record->index_start + mb_rd_record->num) % RD_RECORD_BUFFER_LEN;
290 ++mb_rd_record->num;
291 } else {
292 index = mb_rd_record->index_start;
293 mb_rd_record->index_start =
294 (mb_rd_record->index_start + 1) % RD_RECORD_BUFFER_LEN;
295 }
296 MB_RD_INFO *const mb_rd_info = &mb_rd_record->mb_rd_info[index];
297 const MACROBLOCKD *const xd = &x->e_mbd;
298 const MB_MODE_INFO *const mbmi = xd->mi[0];
299 mb_rd_info->hash_value = hash;
300 mb_rd_info->tx_size = mbmi->tx_size;
301 memcpy(mb_rd_info->blk_skip, x->txfm_search_info.blk_skip,
302 sizeof(mb_rd_info->blk_skip[0]) * n4);
303 av1_copy(mb_rd_info->inter_tx_size, mbmi->inter_tx_size);
304 av1_copy_array(mb_rd_info->tx_type_map, xd->tx_type_map, n4);
305 mb_rd_info->rd_stats = *rd_stats;
306 }
307
get_search_init_depth(int mi_width,int mi_height,int is_inter,const SPEED_FEATURES * sf,int tx_size_search_method)308 static int get_search_init_depth(int mi_width, int mi_height, int is_inter,
309 const SPEED_FEATURES *sf,
310 int tx_size_search_method) {
311 if (tx_size_search_method == USE_LARGESTALL) return MAX_VARTX_DEPTH;
312
313 if (sf->tx_sf.tx_size_search_lgr_block) {
314 if (mi_width > mi_size_wide[BLOCK_64X64] ||
315 mi_height > mi_size_high[BLOCK_64X64])
316 return MAX_VARTX_DEPTH;
317 }
318
319 if (is_inter) {
320 return (mi_height != mi_width)
321 ? sf->tx_sf.inter_tx_size_search_init_depth_rect
322 : sf->tx_sf.inter_tx_size_search_init_depth_sqr;
323 } else {
324 return (mi_height != mi_width)
325 ? sf->tx_sf.intra_tx_size_search_init_depth_rect
326 : sf->tx_sf.intra_tx_size_search_init_depth_sqr;
327 }
328 }
329
330 static AOM_INLINE void select_tx_block(
331 const AV1_COMP *cpi, MACROBLOCK *x, int blk_row, int blk_col, int block,
332 TX_SIZE tx_size, int depth, BLOCK_SIZE plane_bsize, ENTROPY_CONTEXT *ta,
333 ENTROPY_CONTEXT *tl, TXFM_CONTEXT *tx_above, TXFM_CONTEXT *tx_left,
334 RD_STATS *rd_stats, int64_t prev_level_rd, int64_t ref_best_rd,
335 int *is_cost_valid, FAST_TX_SEARCH_MODE ftxs_mode);
336
337 // NOTE: CONFIG_COLLECT_RD_STATS has 3 possible values
338 // 0: Do not collect any RD stats
339 // 1: Collect RD stats for transform units
340 // 2: Collect RD stats for partition units
341 #if CONFIG_COLLECT_RD_STATS
342
get_energy_distribution_fine(const AV1_COMP * cpi,BLOCK_SIZE bsize,const uint8_t * src,int src_stride,const uint8_t * dst,int dst_stride,int need_4th,double * hordist,double * verdist)343 static AOM_INLINE void get_energy_distribution_fine(
344 const AV1_COMP *cpi, BLOCK_SIZE bsize, const uint8_t *src, int src_stride,
345 const uint8_t *dst, int dst_stride, int need_4th, double *hordist,
346 double *verdist) {
347 const int bw = block_size_wide[bsize];
348 const int bh = block_size_high[bsize];
349 unsigned int esq[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
350
351 if (bsize < BLOCK_16X16 || (bsize >= BLOCK_4X16 && bsize <= BLOCK_32X8)) {
352 // Special cases: calculate 'esq' values manually, as we don't have 'vf'
353 // functions for the 16 (very small) sub-blocks of this block.
354 const int w_shift = (bw == 4) ? 0 : (bw == 8) ? 1 : (bw == 16) ? 2 : 3;
355 const int h_shift = (bh == 4) ? 0 : (bh == 8) ? 1 : (bh == 16) ? 2 : 3;
356 assert(bw <= 32);
357 assert(bh <= 32);
358 assert(((bw - 1) >> w_shift) + (((bh - 1) >> h_shift) << 2) == 15);
359 if (cpi->common.seq_params->use_highbitdepth) {
360 const uint16_t *src16 = CONVERT_TO_SHORTPTR(src);
361 const uint16_t *dst16 = CONVERT_TO_SHORTPTR(dst);
362 for (int i = 0; i < bh; ++i)
363 for (int j = 0; j < bw; ++j) {
364 const int index = (j >> w_shift) + ((i >> h_shift) << 2);
365 esq[index] +=
366 (src16[j + i * src_stride] - dst16[j + i * dst_stride]) *
367 (src16[j + i * src_stride] - dst16[j + i * dst_stride]);
368 }
369 } else {
370 for (int i = 0; i < bh; ++i)
371 for (int j = 0; j < bw; ++j) {
372 const int index = (j >> w_shift) + ((i >> h_shift) << 2);
373 esq[index] += (src[j + i * src_stride] - dst[j + i * dst_stride]) *
374 (src[j + i * src_stride] - dst[j + i * dst_stride]);
375 }
376 }
377 } else { // Calculate 'esq' values using 'vf' functions on the 16 sub-blocks.
378 const int f_index =
379 (bsize < BLOCK_SIZES) ? bsize - BLOCK_16X16 : bsize - BLOCK_8X16;
380 assert(f_index >= 0 && f_index < BLOCK_SIZES_ALL);
381 const BLOCK_SIZE subsize = (BLOCK_SIZE)f_index;
382 assert(block_size_wide[bsize] == 4 * block_size_wide[subsize]);
383 assert(block_size_high[bsize] == 4 * block_size_high[subsize]);
384 cpi->ppi->fn_ptr[subsize].vf(src, src_stride, dst, dst_stride, &esq[0]);
385 cpi->ppi->fn_ptr[subsize].vf(src + bw / 4, src_stride, dst + bw / 4,
386 dst_stride, &esq[1]);
387 cpi->ppi->fn_ptr[subsize].vf(src + bw / 2, src_stride, dst + bw / 2,
388 dst_stride, &esq[2]);
389 cpi->ppi->fn_ptr[subsize].vf(src + 3 * bw / 4, src_stride, dst + 3 * bw / 4,
390 dst_stride, &esq[3]);
391 src += bh / 4 * src_stride;
392 dst += bh / 4 * dst_stride;
393
394 cpi->ppi->fn_ptr[subsize].vf(src, src_stride, dst, dst_stride, &esq[4]);
395 cpi->ppi->fn_ptr[subsize].vf(src + bw / 4, src_stride, dst + bw / 4,
396 dst_stride, &esq[5]);
397 cpi->ppi->fn_ptr[subsize].vf(src + bw / 2, src_stride, dst + bw / 2,
398 dst_stride, &esq[6]);
399 cpi->ppi->fn_ptr[subsize].vf(src + 3 * bw / 4, src_stride, dst + 3 * bw / 4,
400 dst_stride, &esq[7]);
401 src += bh / 4 * src_stride;
402 dst += bh / 4 * dst_stride;
403
404 cpi->ppi->fn_ptr[subsize].vf(src, src_stride, dst, dst_stride, &esq[8]);
405 cpi->ppi->fn_ptr[subsize].vf(src + bw / 4, src_stride, dst + bw / 4,
406 dst_stride, &esq[9]);
407 cpi->ppi->fn_ptr[subsize].vf(src + bw / 2, src_stride, dst + bw / 2,
408 dst_stride, &esq[10]);
409 cpi->ppi->fn_ptr[subsize].vf(src + 3 * bw / 4, src_stride, dst + 3 * bw / 4,
410 dst_stride, &esq[11]);
411 src += bh / 4 * src_stride;
412 dst += bh / 4 * dst_stride;
413
414 cpi->ppi->fn_ptr[subsize].vf(src, src_stride, dst, dst_stride, &esq[12]);
415 cpi->ppi->fn_ptr[subsize].vf(src + bw / 4, src_stride, dst + bw / 4,
416 dst_stride, &esq[13]);
417 cpi->ppi->fn_ptr[subsize].vf(src + bw / 2, src_stride, dst + bw / 2,
418 dst_stride, &esq[14]);
419 cpi->ppi->fn_ptr[subsize].vf(src + 3 * bw / 4, src_stride, dst + 3 * bw / 4,
420 dst_stride, &esq[15]);
421 }
422
423 double total = (double)esq[0] + esq[1] + esq[2] + esq[3] + esq[4] + esq[5] +
424 esq[6] + esq[7] + esq[8] + esq[9] + esq[10] + esq[11] +
425 esq[12] + esq[13] + esq[14] + esq[15];
426 if (total > 0) {
427 const double e_recip = 1.0 / total;
428 hordist[0] = ((double)esq[0] + esq[4] + esq[8] + esq[12]) * e_recip;
429 hordist[1] = ((double)esq[1] + esq[5] + esq[9] + esq[13]) * e_recip;
430 hordist[2] = ((double)esq[2] + esq[6] + esq[10] + esq[14]) * e_recip;
431 if (need_4th) {
432 hordist[3] = ((double)esq[3] + esq[7] + esq[11] + esq[15]) * e_recip;
433 }
434 verdist[0] = ((double)esq[0] + esq[1] + esq[2] + esq[3]) * e_recip;
435 verdist[1] = ((double)esq[4] + esq[5] + esq[6] + esq[7]) * e_recip;
436 verdist[2] = ((double)esq[8] + esq[9] + esq[10] + esq[11]) * e_recip;
437 if (need_4th) {
438 verdist[3] = ((double)esq[12] + esq[13] + esq[14] + esq[15]) * e_recip;
439 }
440 } else {
441 hordist[0] = verdist[0] = 0.25;
442 hordist[1] = verdist[1] = 0.25;
443 hordist[2] = verdist[2] = 0.25;
444 if (need_4th) {
445 hordist[3] = verdist[3] = 0.25;
446 }
447 }
448 }
449
get_sse_norm(const int16_t * diff,int stride,int w,int h)450 static double get_sse_norm(const int16_t *diff, int stride, int w, int h) {
451 double sum = 0.0;
452 for (int j = 0; j < h; ++j) {
453 for (int i = 0; i < w; ++i) {
454 const int err = diff[j * stride + i];
455 sum += err * err;
456 }
457 }
458 assert(w > 0 && h > 0);
459 return sum / (w * h);
460 }
461
get_sad_norm(const int16_t * diff,int stride,int w,int h)462 static double get_sad_norm(const int16_t *diff, int stride, int w, int h) {
463 double sum = 0.0;
464 for (int j = 0; j < h; ++j) {
465 for (int i = 0; i < w; ++i) {
466 sum += abs(diff[j * stride + i]);
467 }
468 }
469 assert(w > 0 && h > 0);
470 return sum / (w * h);
471 }
472
get_2x2_normalized_sses_and_sads(const AV1_COMP * const cpi,BLOCK_SIZE tx_bsize,const uint8_t * const src,int src_stride,const uint8_t * const dst,int dst_stride,const int16_t * const src_diff,int diff_stride,double * const sse_norm_arr,double * const sad_norm_arr)473 static AOM_INLINE void get_2x2_normalized_sses_and_sads(
474 const AV1_COMP *const cpi, BLOCK_SIZE tx_bsize, const uint8_t *const src,
475 int src_stride, const uint8_t *const dst, int dst_stride,
476 const int16_t *const src_diff, int diff_stride, double *const sse_norm_arr,
477 double *const sad_norm_arr) {
478 const BLOCK_SIZE tx_bsize_half =
479 get_partition_subsize(tx_bsize, PARTITION_SPLIT);
480 if (tx_bsize_half == BLOCK_INVALID) { // manually calculate stats
481 const int half_width = block_size_wide[tx_bsize] / 2;
482 const int half_height = block_size_high[tx_bsize] / 2;
483 for (int row = 0; row < 2; ++row) {
484 for (int col = 0; col < 2; ++col) {
485 const int16_t *const this_src_diff =
486 src_diff + row * half_height * diff_stride + col * half_width;
487 if (sse_norm_arr) {
488 sse_norm_arr[row * 2 + col] =
489 get_sse_norm(this_src_diff, diff_stride, half_width, half_height);
490 }
491 if (sad_norm_arr) {
492 sad_norm_arr[row * 2 + col] =
493 get_sad_norm(this_src_diff, diff_stride, half_width, half_height);
494 }
495 }
496 }
497 } else { // use function pointers to calculate stats
498 const int half_width = block_size_wide[tx_bsize_half];
499 const int half_height = block_size_high[tx_bsize_half];
500 const int num_samples_half = half_width * half_height;
501 for (int row = 0; row < 2; ++row) {
502 for (int col = 0; col < 2; ++col) {
503 const uint8_t *const this_src =
504 src + row * half_height * src_stride + col * half_width;
505 const uint8_t *const this_dst =
506 dst + row * half_height * dst_stride + col * half_width;
507
508 if (sse_norm_arr) {
509 unsigned int this_sse;
510 cpi->ppi->fn_ptr[tx_bsize_half].vf(this_src, src_stride, this_dst,
511 dst_stride, &this_sse);
512 sse_norm_arr[row * 2 + col] = (double)this_sse / num_samples_half;
513 }
514
515 if (sad_norm_arr) {
516 const unsigned int this_sad = cpi->ppi->fn_ptr[tx_bsize_half].sdf(
517 this_src, src_stride, this_dst, dst_stride);
518 sad_norm_arr[row * 2 + col] = (double)this_sad / num_samples_half;
519 }
520 }
521 }
522 }
523 }
524
525 #if CONFIG_COLLECT_RD_STATS == 1
get_mean(const int16_t * diff,int stride,int w,int h)526 static double get_mean(const int16_t *diff, int stride, int w, int h) {
527 double sum = 0.0;
528 for (int j = 0; j < h; ++j) {
529 for (int i = 0; i < w; ++i) {
530 sum += diff[j * stride + i];
531 }
532 }
533 assert(w > 0 && h > 0);
534 return sum / (w * h);
535 }
PrintTransformUnitStats(const AV1_COMP * const cpi,MACROBLOCK * x,const RD_STATS * const rd_stats,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,TX_TYPE tx_type,int64_t rd)536 static AOM_INLINE void PrintTransformUnitStats(
537 const AV1_COMP *const cpi, MACROBLOCK *x, const RD_STATS *const rd_stats,
538 int blk_row, int blk_col, BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
539 TX_TYPE tx_type, int64_t rd) {
540 if (rd_stats->rate == INT_MAX || rd_stats->dist == INT64_MAX) return;
541
542 // Generate small sample to restrict output size.
543 static unsigned int seed = 21743;
544 if (lcg_rand16(&seed) % 256 > 0) return;
545
546 const char output_file[] = "tu_stats.txt";
547 FILE *fout = fopen(output_file, "a");
548 if (!fout) return;
549
550 const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
551 const MACROBLOCKD *const xd = &x->e_mbd;
552 const int plane = 0;
553 struct macroblock_plane *const p = &x->plane[plane];
554 const struct macroblockd_plane *const pd = &xd->plane[plane];
555 const int txw = tx_size_wide[tx_size];
556 const int txh = tx_size_high[tx_size];
557 const int dequant_shift = (is_cur_buf_hbd(xd)) ? xd->bd - 5 : 3;
558 const int q_step = p->dequant_QTX[1] >> dequant_shift;
559 const int num_samples = txw * txh;
560
561 const double rate_norm = (double)rd_stats->rate / num_samples;
562 const double dist_norm = (double)rd_stats->dist / num_samples;
563
564 fprintf(fout, "%g %g", rate_norm, dist_norm);
565
566 const int src_stride = p->src.stride;
567 const uint8_t *const src =
568 &p->src.buf[(blk_row * src_stride + blk_col) << MI_SIZE_LOG2];
569 const int dst_stride = pd->dst.stride;
570 const uint8_t *const dst =
571 &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
572 unsigned int sse;
573 cpi->ppi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
574 const double sse_norm = (double)sse / num_samples;
575
576 const unsigned int sad =
577 cpi->ppi->fn_ptr[tx_bsize].sdf(src, src_stride, dst, dst_stride);
578 const double sad_norm = (double)sad / num_samples;
579
580 fprintf(fout, " %g %g", sse_norm, sad_norm);
581
582 const int diff_stride = block_size_wide[plane_bsize];
583 const int16_t *const src_diff =
584 &p->src_diff[(blk_row * diff_stride + blk_col) << MI_SIZE_LOG2];
585
586 double sse_norm_arr[4], sad_norm_arr[4];
587 get_2x2_normalized_sses_and_sads(cpi, tx_bsize, src, src_stride, dst,
588 dst_stride, src_diff, diff_stride,
589 sse_norm_arr, sad_norm_arr);
590 for (int i = 0; i < 4; ++i) {
591 fprintf(fout, " %g", sse_norm_arr[i]);
592 }
593 for (int i = 0; i < 4; ++i) {
594 fprintf(fout, " %g", sad_norm_arr[i]);
595 }
596
597 const TX_TYPE_1D tx_type_1d_row = htx_tab[tx_type];
598 const TX_TYPE_1D tx_type_1d_col = vtx_tab[tx_type];
599
600 fprintf(fout, " %d %d %d %d %d", q_step, tx_size_wide[tx_size],
601 tx_size_high[tx_size], tx_type_1d_row, tx_type_1d_col);
602
603 int model_rate;
604 int64_t model_dist;
605 model_rd_sse_fn[MODELRD_CURVFIT](cpi, x, tx_bsize, plane, sse, num_samples,
606 &model_rate, &model_dist);
607 const double model_rate_norm = (double)model_rate / num_samples;
608 const double model_dist_norm = (double)model_dist / num_samples;
609 fprintf(fout, " %g %g", model_rate_norm, model_dist_norm);
610
611 const double mean = get_mean(src_diff, diff_stride, txw, txh);
612 float hor_corr, vert_corr;
613 av1_get_horver_correlation_full(src_diff, diff_stride, txw, txh, &hor_corr,
614 &vert_corr);
615 fprintf(fout, " %g %g %g", mean, hor_corr, vert_corr);
616
617 double hdist[4] = { 0 }, vdist[4] = { 0 };
618 get_energy_distribution_fine(cpi, tx_bsize, src, src_stride, dst, dst_stride,
619 1, hdist, vdist);
620 fprintf(fout, " %g %g %g %g %g %g %g %g", hdist[0], hdist[1], hdist[2],
621 hdist[3], vdist[0], vdist[1], vdist[2], vdist[3]);
622
623 fprintf(fout, " %d %" PRId64, x->rdmult, rd);
624
625 fprintf(fout, "\n");
626 fclose(fout);
627 }
628 #endif // CONFIG_COLLECT_RD_STATS == 1
629
630 #if CONFIG_COLLECT_RD_STATS >= 2
get_sse(const AV1_COMP * cpi,const MACROBLOCK * x)631 static int64_t get_sse(const AV1_COMP *cpi, const MACROBLOCK *x) {
632 const AV1_COMMON *cm = &cpi->common;
633 const int num_planes = av1_num_planes(cm);
634 const MACROBLOCKD *xd = &x->e_mbd;
635 const MB_MODE_INFO *mbmi = xd->mi[0];
636 int64_t total_sse = 0;
637 for (int plane = 0; plane < num_planes; ++plane) {
638 const struct macroblock_plane *const p = &x->plane[plane];
639 const struct macroblockd_plane *const pd = &xd->plane[plane];
640 const BLOCK_SIZE bs =
641 get_plane_block_size(mbmi->bsize, pd->subsampling_x, pd->subsampling_y);
642 unsigned int sse;
643
644 if (plane) continue;
645
646 cpi->ppi->fn_ptr[bs].vf(p->src.buf, p->src.stride, pd->dst.buf,
647 pd->dst.stride, &sse);
648 total_sse += sse;
649 }
650 total_sse <<= 4;
651 return total_sse;
652 }
653
get_est_rate_dist(const TileDataEnc * tile_data,BLOCK_SIZE bsize,int64_t sse,int * est_residue_cost,int64_t * est_dist)654 static int get_est_rate_dist(const TileDataEnc *tile_data, BLOCK_SIZE bsize,
655 int64_t sse, int *est_residue_cost,
656 int64_t *est_dist) {
657 const InterModeRdModel *md = &tile_data->inter_mode_rd_models[bsize];
658 if (md->ready) {
659 if (sse < md->dist_mean) {
660 *est_residue_cost = 0;
661 *est_dist = sse;
662 } else {
663 *est_dist = (int64_t)round(md->dist_mean);
664 const double est_ld = md->a * sse + md->b;
665 // Clamp estimated rate cost by INT_MAX / 2.
666 // TODO(angiebird@google.com): find better solution than clamping.
667 if (fabs(est_ld) < 1e-2) {
668 *est_residue_cost = INT_MAX / 2;
669 } else {
670 double est_residue_cost_dbl = ((sse - md->dist_mean) / est_ld);
671 if (est_residue_cost_dbl < 0) {
672 *est_residue_cost = 0;
673 } else {
674 *est_residue_cost =
675 (int)AOMMIN((int64_t)round(est_residue_cost_dbl), INT_MAX / 2);
676 }
677 }
678 if (*est_residue_cost <= 0) {
679 *est_residue_cost = 0;
680 *est_dist = sse;
681 }
682 }
683 return 1;
684 }
685 return 0;
686 }
687
get_highbd_diff_mean(const uint8_t * src8,int src_stride,const uint8_t * dst8,int dst_stride,int w,int h)688 static double get_highbd_diff_mean(const uint8_t *src8, int src_stride,
689 const uint8_t *dst8, int dst_stride, int w,
690 int h) {
691 const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
692 const uint16_t *dst = CONVERT_TO_SHORTPTR(dst8);
693 double sum = 0.0;
694 for (int j = 0; j < h; ++j) {
695 for (int i = 0; i < w; ++i) {
696 const int diff = src[j * src_stride + i] - dst[j * dst_stride + i];
697 sum += diff;
698 }
699 }
700 assert(w > 0 && h > 0);
701 return sum / (w * h);
702 }
703
get_diff_mean(const uint8_t * src,int src_stride,const uint8_t * dst,int dst_stride,int w,int h)704 static double get_diff_mean(const uint8_t *src, int src_stride,
705 const uint8_t *dst, int dst_stride, int w, int h) {
706 double sum = 0.0;
707 for (int j = 0; j < h; ++j) {
708 for (int i = 0; i < w; ++i) {
709 const int diff = src[j * src_stride + i] - dst[j * dst_stride + i];
710 sum += diff;
711 }
712 }
713 assert(w > 0 && h > 0);
714 return sum / (w * h);
715 }
716
PrintPredictionUnitStats(const AV1_COMP * const cpi,const TileDataEnc * tile_data,MACROBLOCK * x,const RD_STATS * const rd_stats,BLOCK_SIZE plane_bsize)717 static AOM_INLINE void PrintPredictionUnitStats(const AV1_COMP *const cpi,
718 const TileDataEnc *tile_data,
719 MACROBLOCK *x,
720 const RD_STATS *const rd_stats,
721 BLOCK_SIZE plane_bsize) {
722 if (rd_stats->rate == INT_MAX || rd_stats->dist == INT64_MAX) return;
723
724 if (cpi->sf.inter_sf.inter_mode_rd_model_estimation == 1 &&
725 (tile_data == NULL ||
726 !tile_data->inter_mode_rd_models[plane_bsize].ready))
727 return;
728 (void)tile_data;
729 // Generate small sample to restrict output size.
730 static unsigned int seed = 95014;
731
732 if ((lcg_rand16(&seed) % (1 << (14 - num_pels_log2_lookup[plane_bsize]))) !=
733 1)
734 return;
735
736 const char output_file[] = "pu_stats.txt";
737 FILE *fout = fopen(output_file, "a");
738 if (!fout) return;
739
740 MACROBLOCKD *const xd = &x->e_mbd;
741 const int plane = 0;
742 struct macroblock_plane *const p = &x->plane[plane];
743 struct macroblockd_plane *pd = &xd->plane[plane];
744 const int diff_stride = block_size_wide[plane_bsize];
745 int bw, bh;
746 get_txb_dimensions(xd, plane, plane_bsize, 0, 0, plane_bsize, NULL, NULL, &bw,
747 &bh);
748 const int num_samples = bw * bh;
749 const int dequant_shift = (is_cur_buf_hbd(xd)) ? xd->bd - 5 : 3;
750 const int q_step = p->dequant_QTX[1] >> dequant_shift;
751 const int shift = (xd->bd - 8);
752
753 const double rate_norm = (double)rd_stats->rate / num_samples;
754 const double dist_norm = (double)rd_stats->dist / num_samples;
755 const double rdcost_norm =
756 (double)RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist) / num_samples;
757
758 fprintf(fout, "%g %g %g", rate_norm, dist_norm, rdcost_norm);
759
760 const int src_stride = p->src.stride;
761 const uint8_t *const src = p->src.buf;
762 const int dst_stride = pd->dst.stride;
763 const uint8_t *const dst = pd->dst.buf;
764 const int16_t *const src_diff = p->src_diff;
765
766 int64_t sse = calculate_sse(xd, p, pd, bw, bh);
767 const double sse_norm = (double)sse / num_samples;
768
769 const unsigned int sad =
770 cpi->ppi->fn_ptr[plane_bsize].sdf(src, src_stride, dst, dst_stride);
771 const double sad_norm =
772 (double)sad / (1 << num_pels_log2_lookup[plane_bsize]);
773
774 fprintf(fout, " %g %g", sse_norm, sad_norm);
775
776 double sse_norm_arr[4], sad_norm_arr[4];
777 get_2x2_normalized_sses_and_sads(cpi, plane_bsize, src, src_stride, dst,
778 dst_stride, src_diff, diff_stride,
779 sse_norm_arr, sad_norm_arr);
780 if (shift) {
781 for (int k = 0; k < 4; ++k) sse_norm_arr[k] /= (1 << (2 * shift));
782 for (int k = 0; k < 4; ++k) sad_norm_arr[k] /= (1 << shift);
783 }
784 for (int i = 0; i < 4; ++i) {
785 fprintf(fout, " %g", sse_norm_arr[i]);
786 }
787 for (int i = 0; i < 4; ++i) {
788 fprintf(fout, " %g", sad_norm_arr[i]);
789 }
790
791 fprintf(fout, " %d %d %d %d", q_step, x->rdmult, bw, bh);
792
793 int model_rate;
794 int64_t model_dist;
795 model_rd_sse_fn[MODELRD_CURVFIT](cpi, x, plane_bsize, plane, sse, num_samples,
796 &model_rate, &model_dist);
797 const double model_rdcost_norm =
798 (double)RDCOST(x->rdmult, model_rate, model_dist) / num_samples;
799 const double model_rate_norm = (double)model_rate / num_samples;
800 const double model_dist_norm = (double)model_dist / num_samples;
801 fprintf(fout, " %g %g %g", model_rate_norm, model_dist_norm,
802 model_rdcost_norm);
803
804 double mean;
805 if (is_cur_buf_hbd(xd)) {
806 mean = get_highbd_diff_mean(p->src.buf, p->src.stride, pd->dst.buf,
807 pd->dst.stride, bw, bh);
808 } else {
809 mean = get_diff_mean(p->src.buf, p->src.stride, pd->dst.buf, pd->dst.stride,
810 bw, bh);
811 }
812 mean /= (1 << shift);
813 float hor_corr, vert_corr;
814 av1_get_horver_correlation_full(src_diff, diff_stride, bw, bh, &hor_corr,
815 &vert_corr);
816 fprintf(fout, " %g %g %g", mean, hor_corr, vert_corr);
817
818 double hdist[4] = { 0 }, vdist[4] = { 0 };
819 get_energy_distribution_fine(cpi, plane_bsize, src, src_stride, dst,
820 dst_stride, 1, hdist, vdist);
821 fprintf(fout, " %g %g %g %g %g %g %g %g", hdist[0], hdist[1], hdist[2],
822 hdist[3], vdist[0], vdist[1], vdist[2], vdist[3]);
823
824 if (cpi->sf.inter_sf.inter_mode_rd_model_estimation == 1) {
825 assert(tile_data->inter_mode_rd_models[plane_bsize].ready);
826 const int64_t overall_sse = get_sse(cpi, x);
827 int est_residue_cost = 0;
828 int64_t est_dist = 0;
829 get_est_rate_dist(tile_data, plane_bsize, overall_sse, &est_residue_cost,
830 &est_dist);
831 const double est_residue_cost_norm = (double)est_residue_cost / num_samples;
832 const double est_dist_norm = (double)est_dist / num_samples;
833 const double est_rdcost_norm =
834 (double)RDCOST(x->rdmult, est_residue_cost, est_dist) / num_samples;
835 fprintf(fout, " %g %g %g", est_residue_cost_norm, est_dist_norm,
836 est_rdcost_norm);
837 }
838
839 fprintf(fout, "\n");
840 fclose(fout);
841 }
842 #endif // CONFIG_COLLECT_RD_STATS >= 2
843 #endif // CONFIG_COLLECT_RD_STATS
844
inverse_transform_block_facade(MACROBLOCK * const x,int plane,int block,int blk_row,int blk_col,int eob,int reduced_tx_set)845 static AOM_INLINE void inverse_transform_block_facade(MACROBLOCK *const x,
846 int plane, int block,
847 int blk_row, int blk_col,
848 int eob,
849 int reduced_tx_set) {
850 if (!eob) return;
851 struct macroblock_plane *const p = &x->plane[plane];
852 MACROBLOCKD *const xd = &x->e_mbd;
853 tran_low_t *dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
854 const PLANE_TYPE plane_type = get_plane_type(plane);
855 const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
856 const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, blk_row, blk_col,
857 tx_size, reduced_tx_set);
858
859 struct macroblockd_plane *const pd = &xd->plane[plane];
860 const int dst_stride = pd->dst.stride;
861 uint8_t *dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
862 av1_inverse_transform_block(xd, dqcoeff, plane, tx_type, tx_size, dst,
863 dst_stride, eob, reduced_tx_set);
864 }
865
recon_intra(const AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,const TXB_CTX * const txb_ctx,int skip_trellis,TX_TYPE best_tx_type,int do_quant,int * rate_cost,uint16_t best_eob)866 static INLINE void recon_intra(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
867 int block, int blk_row, int blk_col,
868 BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
869 const TXB_CTX *const txb_ctx, int skip_trellis,
870 TX_TYPE best_tx_type, int do_quant,
871 int *rate_cost, uint16_t best_eob) {
872 const AV1_COMMON *cm = &cpi->common;
873 MACROBLOCKD *xd = &x->e_mbd;
874 MB_MODE_INFO *mbmi = xd->mi[0];
875 const int is_inter = is_inter_block(mbmi);
876 if (!is_inter && best_eob &&
877 (blk_row + tx_size_high_unit[tx_size] < mi_size_high[plane_bsize] ||
878 blk_col + tx_size_wide_unit[tx_size] < mi_size_wide[plane_bsize])) {
879 // if the quantized coefficients are stored in the dqcoeff buffer, we don't
880 // need to do transform and quantization again.
881 if (do_quant) {
882 TxfmParam txfm_param_intra;
883 QUANT_PARAM quant_param_intra;
884 av1_setup_xform(cm, x, tx_size, best_tx_type, &txfm_param_intra);
885 av1_setup_quant(tx_size, !skip_trellis,
886 skip_trellis
887 ? (USE_B_QUANT_NO_TRELLIS ? AV1_XFORM_QUANT_B
888 : AV1_XFORM_QUANT_FP)
889 : AV1_XFORM_QUANT_FP,
890 cpi->oxcf.q_cfg.quant_b_adapt, &quant_param_intra);
891 av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, best_tx_type,
892 &quant_param_intra);
893 av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize,
894 &txfm_param_intra, &quant_param_intra);
895 if (quant_param_intra.use_optimize_b) {
896 av1_optimize_b(cpi, x, plane, block, tx_size, best_tx_type, txb_ctx,
897 rate_cost);
898 }
899 }
900
901 inverse_transform_block_facade(x, plane, block, blk_row, blk_col,
902 x->plane[plane].eobs[block],
903 cm->features.reduced_tx_set_used);
904
905 // This may happen because of hash collision. The eob stored in the hash
906 // table is non-zero, but the real eob is zero. We need to make sure tx_type
907 // is DCT_DCT in this case.
908 if (plane == 0 && x->plane[plane].eobs[block] == 0 &&
909 best_tx_type != DCT_DCT) {
910 update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
911 }
912 }
913 }
914
pixel_dist_visible_only(const AV1_COMP * const cpi,const MACROBLOCK * x,const uint8_t * src,const int src_stride,const uint8_t * dst,const int dst_stride,const BLOCK_SIZE tx_bsize,int txb_rows,int txb_cols,int visible_rows,int visible_cols)915 static unsigned pixel_dist_visible_only(
916 const AV1_COMP *const cpi, const MACROBLOCK *x, const uint8_t *src,
917 const int src_stride, const uint8_t *dst, const int dst_stride,
918 const BLOCK_SIZE tx_bsize, int txb_rows, int txb_cols, int visible_rows,
919 int visible_cols) {
920 unsigned sse;
921
922 if (txb_rows == visible_rows && txb_cols == visible_cols) {
923 cpi->ppi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
924 return sse;
925 }
926
927 #if CONFIG_AV1_HIGHBITDEPTH
928 const MACROBLOCKD *xd = &x->e_mbd;
929 if (is_cur_buf_hbd(xd)) {
930 uint64_t sse64 = aom_highbd_sse_odd_size(src, src_stride, dst, dst_stride,
931 visible_cols, visible_rows);
932 return (unsigned int)ROUND_POWER_OF_TWO(sse64, (xd->bd - 8) * 2);
933 }
934 #else
935 (void)x;
936 #endif
937 sse = aom_sse_odd_size(src, src_stride, dst, dst_stride, visible_cols,
938 visible_rows);
939 return sse;
940 }
941
942 // Compute the pixel domain distortion from src and dst on all visible 4x4s in
943 // the
944 // transform block.
pixel_dist(const AV1_COMP * const cpi,const MACROBLOCK * x,int plane,const uint8_t * src,const int src_stride,const uint8_t * dst,const int dst_stride,int blk_row,int blk_col,const BLOCK_SIZE plane_bsize,const BLOCK_SIZE tx_bsize)945 static unsigned pixel_dist(const AV1_COMP *const cpi, const MACROBLOCK *x,
946 int plane, const uint8_t *src, const int src_stride,
947 const uint8_t *dst, const int dst_stride,
948 int blk_row, int blk_col,
949 const BLOCK_SIZE plane_bsize,
950 const BLOCK_SIZE tx_bsize) {
951 int txb_rows, txb_cols, visible_rows, visible_cols;
952 const MACROBLOCKD *xd = &x->e_mbd;
953
954 get_txb_dimensions(xd, plane, plane_bsize, blk_row, blk_col, tx_bsize,
955 &txb_cols, &txb_rows, &visible_cols, &visible_rows);
956 assert(visible_rows > 0);
957 assert(visible_cols > 0);
958
959 unsigned sse = pixel_dist_visible_only(cpi, x, src, src_stride, dst,
960 dst_stride, tx_bsize, txb_rows,
961 txb_cols, visible_rows, visible_cols);
962
963 return sse;
964 }
965
dist_block_px_domain(const AV1_COMP * cpi,MACROBLOCK * x,int plane,BLOCK_SIZE plane_bsize,int block,int blk_row,int blk_col,TX_SIZE tx_size)966 static INLINE int64_t dist_block_px_domain(const AV1_COMP *cpi, MACROBLOCK *x,
967 int plane, BLOCK_SIZE plane_bsize,
968 int block, int blk_row, int blk_col,
969 TX_SIZE tx_size) {
970 MACROBLOCKD *const xd = &x->e_mbd;
971 const struct macroblock_plane *const p = &x->plane[plane];
972 const uint16_t eob = p->eobs[block];
973 const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
974 const int bsw = block_size_wide[tx_bsize];
975 const int bsh = block_size_high[tx_bsize];
976 const int src_stride = x->plane[plane].src.stride;
977 const int dst_stride = xd->plane[plane].dst.stride;
978 // Scale the transform block index to pixel unit.
979 const int src_idx = (blk_row * src_stride + blk_col) << MI_SIZE_LOG2;
980 const int dst_idx = (blk_row * dst_stride + blk_col) << MI_SIZE_LOG2;
981 const uint8_t *src = &x->plane[plane].src.buf[src_idx];
982 const uint8_t *dst = &xd->plane[plane].dst.buf[dst_idx];
983 const tran_low_t *dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
984
985 assert(cpi != NULL);
986 assert(tx_size_wide_log2[0] == tx_size_high_log2[0]);
987
988 uint8_t *recon;
989 DECLARE_ALIGNED(16, uint16_t, recon16[MAX_TX_SQUARE]);
990
991 #if CONFIG_AV1_HIGHBITDEPTH
992 if (is_cur_buf_hbd(xd)) {
993 recon = CONVERT_TO_BYTEPTR(recon16);
994 aom_highbd_convolve_copy(CONVERT_TO_SHORTPTR(dst), dst_stride,
995 CONVERT_TO_SHORTPTR(recon), MAX_TX_SIZE, bsw, bsh);
996 } else {
997 recon = (uint8_t *)recon16;
998 aom_convolve_copy(dst, dst_stride, recon, MAX_TX_SIZE, bsw, bsh);
999 }
1000 #else
1001 recon = (uint8_t *)recon16;
1002 aom_convolve_copy(dst, dst_stride, recon, MAX_TX_SIZE, bsw, bsh);
1003 #endif
1004
1005 const PLANE_TYPE plane_type = get_plane_type(plane);
1006 TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
1007 cpi->common.features.reduced_tx_set_used);
1008 av1_inverse_transform_block(xd, dqcoeff, plane, tx_type, tx_size, recon,
1009 MAX_TX_SIZE, eob,
1010 cpi->common.features.reduced_tx_set_used);
1011
1012 return 16 * pixel_dist(cpi, x, plane, src, src_stride, recon, MAX_TX_SIZE,
1013 blk_row, blk_col, plane_bsize, tx_bsize);
1014 }
1015
1016 // pruning thresholds for prune_txk_type and prune_txk_type_separ
1017 static const int prune_factors[5] = { 200, 200, 120, 80, 40 }; // scale 1000
1018 static const int mul_factors[5] = { 80, 80, 70, 50, 30 }; // scale 100
1019
1020 // R-D costs are sorted in ascending order.
sort_rd(int64_t rds[],int txk[],int len)1021 static INLINE void sort_rd(int64_t rds[], int txk[], int len) {
1022 int i, j, k;
1023
1024 for (i = 1; i <= len - 1; ++i) {
1025 for (j = 0; j < i; ++j) {
1026 if (rds[j] > rds[i]) {
1027 int64_t temprd;
1028 int tempi;
1029
1030 temprd = rds[i];
1031 tempi = txk[i];
1032
1033 for (k = i; k > j; k--) {
1034 rds[k] = rds[k - 1];
1035 txk[k] = txk[k - 1];
1036 }
1037
1038 rds[j] = temprd;
1039 txk[j] = tempi;
1040 break;
1041 }
1042 }
1043 }
1044 }
1045
av1_block_error_qm(const tran_low_t * coeff,const tran_low_t * dqcoeff,intptr_t block_size,const qm_val_t * qmatrix,const int16_t * scan,int64_t * ssz)1046 static INLINE int64_t av1_block_error_qm(const tran_low_t *coeff,
1047 const tran_low_t *dqcoeff,
1048 intptr_t block_size,
1049 const qm_val_t *qmatrix,
1050 const int16_t *scan, int64_t *ssz) {
1051 int i;
1052 int64_t error = 0, sqcoeff = 0;
1053
1054 for (i = 0; i < block_size; i++) {
1055 int64_t weight = qmatrix[scan[i]];
1056 int64_t dd = coeff[i] - dqcoeff[i];
1057 dd *= weight;
1058 int64_t cc = coeff[i];
1059 cc *= weight;
1060 // The ranges of coeff and dqcoeff are
1061 // bd8 : 18 bits (including sign)
1062 // bd10: 20 bits (including sign)
1063 // bd12: 22 bits (including sign)
1064 // As AOM_QM_BITS is 5, the intermediate quantities in the calculation
1065 // below should fit in 54 bits, thus no overflow should happen.
1066 error += (dd * dd + (1 << (2 * AOM_QM_BITS - 1))) >> (2 * AOM_QM_BITS);
1067 sqcoeff += (cc * cc + (1 << (2 * AOM_QM_BITS - 1))) >> (2 * AOM_QM_BITS);
1068 }
1069
1070 *ssz = sqcoeff;
1071 return error;
1072 }
1073
dist_block_tx_domain(MACROBLOCK * x,int plane,int block,TX_SIZE tx_size,const qm_val_t * qmatrix,const int16_t * scan,int64_t * out_dist,int64_t * out_sse)1074 static INLINE void dist_block_tx_domain(MACROBLOCK *x, int plane, int block,
1075 TX_SIZE tx_size,
1076 const qm_val_t *qmatrix,
1077 const int16_t *scan, int64_t *out_dist,
1078 int64_t *out_sse) {
1079 const struct macroblock_plane *const p = &x->plane[plane];
1080 // Transform domain distortion computation is more efficient as it does
1081 // not involve an inverse transform, but it is less accurate.
1082 const int buffer_length = av1_get_max_eob(tx_size);
1083 int64_t this_sse;
1084 // TX-domain results need to shift down to Q2/D10 to match pixel
1085 // domain distortion values which are in Q2^2
1086 int shift = (MAX_TX_SCALE - av1_get_tx_scale(tx_size)) * 2;
1087 const int block_offset = BLOCK_OFFSET(block);
1088 tran_low_t *const coeff = p->coeff + block_offset;
1089 tran_low_t *const dqcoeff = p->dqcoeff + block_offset;
1090 #if CONFIG_AV1_HIGHBITDEPTH
1091 MACROBLOCKD *const xd = &x->e_mbd;
1092 if (is_cur_buf_hbd(xd)) {
1093 // TODO(veluca): handle use_qm_dist_metric for HBD too.
1094 *out_dist = av1_highbd_block_error(coeff, dqcoeff, buffer_length, &this_sse,
1095 xd->bd);
1096 } else {
1097 #endif
1098 if (qmatrix == NULL || !x->txfm_search_params.use_qm_dist_metric) {
1099 *out_dist = av1_block_error(coeff, dqcoeff, buffer_length, &this_sse);
1100 } else {
1101 *out_dist = av1_block_error_qm(coeff, dqcoeff, buffer_length, qmatrix,
1102 scan, &this_sse);
1103 }
1104 #if CONFIG_AV1_HIGHBITDEPTH
1105 }
1106 #endif
1107
1108 *out_dist = RIGHT_SIGNED_SHIFT(*out_dist, shift);
1109 *out_sse = RIGHT_SIGNED_SHIFT(this_sse, shift);
1110 }
1111
prune_txk_type_separ(const AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,TX_SIZE tx_size,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,int * txk_map,int16_t allowed_tx_mask,int prune_factor,const TXB_CTX * const txb_ctx,int reduced_tx_set_used,int64_t ref_best_rd,int num_sel)1112 uint16_t prune_txk_type_separ(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
1113 int block, TX_SIZE tx_size, int blk_row,
1114 int blk_col, BLOCK_SIZE plane_bsize, int *txk_map,
1115 int16_t allowed_tx_mask, int prune_factor,
1116 const TXB_CTX *const txb_ctx,
1117 int reduced_tx_set_used, int64_t ref_best_rd,
1118 int num_sel) {
1119 const AV1_COMMON *cm = &cpi->common;
1120 MACROBLOCKD *xd = &x->e_mbd;
1121
1122 int idx;
1123
1124 int64_t rds_v[4];
1125 int64_t rds_h[4];
1126 int idx_v[4] = { 0, 1, 2, 3 };
1127 int idx_h[4] = { 0, 1, 2, 3 };
1128 int skip_v[4] = { 0 };
1129 int skip_h[4] = { 0 };
1130 const int idx_map[16] = {
1131 DCT_DCT, DCT_ADST, DCT_FLIPADST, V_DCT,
1132 ADST_DCT, ADST_ADST, ADST_FLIPADST, V_ADST,
1133 FLIPADST_DCT, FLIPADST_ADST, FLIPADST_FLIPADST, V_FLIPADST,
1134 H_DCT, H_ADST, H_FLIPADST, IDTX
1135 };
1136
1137 const int sel_pattern_v[16] = {
1138 0, 0, 1, 1, 0, 2, 1, 2, 2, 0, 3, 1, 3, 2, 3, 3
1139 };
1140 const int sel_pattern_h[16] = {
1141 0, 1, 0, 1, 2, 0, 2, 1, 2, 3, 0, 3, 1, 3, 2, 3
1142 };
1143
1144 QUANT_PARAM quant_param;
1145 TxfmParam txfm_param;
1146 av1_setup_xform(cm, x, tx_size, DCT_DCT, &txfm_param);
1147 av1_setup_quant(tx_size, 1, AV1_XFORM_QUANT_B, cpi->oxcf.q_cfg.quant_b_adapt,
1148 &quant_param);
1149 int tx_type;
1150 // to ensure we can try ones even outside of ext_tx_set of current block
1151 // this function should only be called for size < 16
1152 assert(txsize_sqr_up_map[tx_size] <= TX_16X16);
1153 txfm_param.tx_set_type = EXT_TX_SET_ALL16;
1154
1155 int rate_cost = 0;
1156 int64_t dist = 0, sse = 0;
1157 // evaluate horizontal with vertical DCT
1158 for (idx = 0; idx < 4; ++idx) {
1159 tx_type = idx_map[idx];
1160 txfm_param.tx_type = tx_type;
1161
1162 av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
1163 &quant_param);
1164
1165 av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
1166 &quant_param);
1167
1168 const SCAN_ORDER *const scan_order =
1169 get_scan(txfm_param.tx_size, txfm_param.tx_type);
1170 dist_block_tx_domain(x, plane, block, tx_size, quant_param.qmatrix,
1171 scan_order->scan, &dist, &sse);
1172
1173 rate_cost = av1_cost_coeffs_txb_laplacian(x, plane, block, tx_size, tx_type,
1174 txb_ctx, reduced_tx_set_used, 0);
1175
1176 rds_h[idx] = RDCOST(x->rdmult, rate_cost, dist);
1177
1178 if ((rds_h[idx] - (rds_h[idx] >> 2)) > ref_best_rd) {
1179 skip_h[idx] = 1;
1180 }
1181 }
1182 sort_rd(rds_h, idx_h, 4);
1183 for (idx = 1; idx < 4; idx++) {
1184 if (rds_h[idx] > rds_h[0] * 1.2) skip_h[idx_h[idx]] = 1;
1185 }
1186
1187 if (skip_h[idx_h[0]]) return (uint16_t)0xFFFF;
1188
1189 // evaluate vertical with the best horizontal chosen
1190 rds_v[0] = rds_h[0];
1191 int start_v = 1, end_v = 4;
1192 const int *idx_map_v = idx_map + idx_h[0];
1193
1194 for (idx = start_v; idx < end_v; ++idx) {
1195 tx_type = idx_map_v[idx_v[idx] * 4];
1196 txfm_param.tx_type = tx_type;
1197
1198 av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
1199 &quant_param);
1200
1201 av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
1202 &quant_param);
1203
1204 const SCAN_ORDER *const scan_order =
1205 get_scan(txfm_param.tx_size, txfm_param.tx_type);
1206 dist_block_tx_domain(x, plane, block, tx_size, quant_param.qmatrix,
1207 scan_order->scan, &dist, &sse);
1208
1209 rate_cost = av1_cost_coeffs_txb_laplacian(x, plane, block, tx_size, tx_type,
1210 txb_ctx, reduced_tx_set_used, 0);
1211
1212 rds_v[idx] = RDCOST(x->rdmult, rate_cost, dist);
1213
1214 if ((rds_v[idx] - (rds_v[idx] >> 2)) > ref_best_rd) {
1215 skip_v[idx] = 1;
1216 }
1217 }
1218 sort_rd(rds_v, idx_v, 4);
1219 for (idx = 1; idx < 4; idx++) {
1220 if (rds_v[idx] > rds_v[0] * 1.2) skip_v[idx_v[idx]] = 1;
1221 }
1222
1223 // combine rd_h and rd_v to prune tx candidates
1224 int i_v, i_h;
1225 int64_t rds[16];
1226 int num_cand = 0, last = TX_TYPES - 1;
1227
1228 for (int i = 0; i < 16; i++) {
1229 i_v = sel_pattern_v[i];
1230 i_h = sel_pattern_h[i];
1231 tx_type = idx_map[idx_v[i_v] * 4 + idx_h[i_h]];
1232 if (!(allowed_tx_mask & (1 << tx_type)) || skip_h[idx_h[i_h]] ||
1233 skip_v[idx_v[i_v]]) {
1234 txk_map[last] = tx_type;
1235 last--;
1236 } else {
1237 txk_map[num_cand] = tx_type;
1238 rds[num_cand] = rds_v[i_v] + rds_h[i_h];
1239 if (rds[num_cand] == 0) rds[num_cand] = 1;
1240 num_cand++;
1241 }
1242 }
1243 sort_rd(rds, txk_map, num_cand);
1244
1245 uint16_t prune = (uint16_t)(~(1 << txk_map[0]));
1246 num_sel = AOMMIN(num_sel, num_cand);
1247
1248 for (int i = 1; i < num_sel; i++) {
1249 int64_t factor = 1800 * (rds[i] - rds[0]) / (rds[0]);
1250 if (factor < (int64_t)prune_factor)
1251 prune &= ~(1 << txk_map[i]);
1252 else
1253 break;
1254 }
1255 return prune;
1256 }
1257
prune_txk_type(const AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,TX_SIZE tx_size,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,int * txk_map,uint16_t allowed_tx_mask,int prune_factor,const TXB_CTX * const txb_ctx,int reduced_tx_set_used)1258 uint16_t prune_txk_type(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
1259 int block, TX_SIZE tx_size, int blk_row, int blk_col,
1260 BLOCK_SIZE plane_bsize, int *txk_map,
1261 uint16_t allowed_tx_mask, int prune_factor,
1262 const TXB_CTX *const txb_ctx, int reduced_tx_set_used) {
1263 const AV1_COMMON *cm = &cpi->common;
1264 MACROBLOCKD *xd = &x->e_mbd;
1265 int tx_type;
1266
1267 int64_t rds[TX_TYPES];
1268
1269 int num_cand = 0;
1270 int last = TX_TYPES - 1;
1271
1272 TxfmParam txfm_param;
1273 QUANT_PARAM quant_param;
1274 av1_setup_xform(cm, x, tx_size, DCT_DCT, &txfm_param);
1275 av1_setup_quant(tx_size, 1, AV1_XFORM_QUANT_B, cpi->oxcf.q_cfg.quant_b_adapt,
1276 &quant_param);
1277
1278 for (int idx = 0; idx < TX_TYPES; idx++) {
1279 tx_type = idx;
1280 int rate_cost = 0;
1281 int64_t dist = 0, sse = 0;
1282 if (!(allowed_tx_mask & (1 << tx_type))) {
1283 txk_map[last] = tx_type;
1284 last--;
1285 continue;
1286 }
1287 txfm_param.tx_type = tx_type;
1288
1289 av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
1290 &quant_param);
1291
1292 // do txfm and quantization
1293 av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
1294 &quant_param);
1295 // estimate rate cost
1296 rate_cost = av1_cost_coeffs_txb_laplacian(x, plane, block, tx_size, tx_type,
1297 txb_ctx, reduced_tx_set_used, 0);
1298 // tx domain dist
1299 const SCAN_ORDER *const scan_order =
1300 get_scan(txfm_param.tx_size, txfm_param.tx_type);
1301 dist_block_tx_domain(x, plane, block, tx_size, quant_param.qmatrix,
1302 scan_order->scan, &dist, &sse);
1303
1304 txk_map[num_cand] = tx_type;
1305 rds[num_cand] = RDCOST(x->rdmult, rate_cost, dist);
1306 if (rds[num_cand] == 0) rds[num_cand] = 1;
1307 num_cand++;
1308 }
1309
1310 if (num_cand == 0) return (uint16_t)0xFFFF;
1311
1312 sort_rd(rds, txk_map, num_cand);
1313 uint16_t prune = (uint16_t)(~(1 << txk_map[0]));
1314
1315 // 0 < prune_factor <= 1000 controls aggressiveness
1316 int64_t factor = 0;
1317 for (int idx = 1; idx < num_cand; idx++) {
1318 factor = 1000 * (rds[idx] - rds[0]) / rds[0];
1319 if (factor < (int64_t)prune_factor)
1320 prune &= ~(1 << txk_map[idx]);
1321 else
1322 break;
1323 }
1324 return prune;
1325 }
1326
1327 // These thresholds were calibrated to provide a certain number of TX types
1328 // pruned by the model on average, i.e. selecting a threshold with index i
1329 // will lead to pruning i+1 TX types on average
1330 static const float *prune_2D_adaptive_thresholds[] = {
1331 // TX_4X4
1332 (float[]){ 0.00549f, 0.01306f, 0.02039f, 0.02747f, 0.03406f, 0.04065f,
1333 0.04724f, 0.05383f, 0.06067f, 0.06799f, 0.07605f, 0.08533f,
1334 0.09778f, 0.11780f },
1335 // TX_8X8
1336 (float[]){ 0.00037f, 0.00183f, 0.00525f, 0.01038f, 0.01697f, 0.02502f,
1337 0.03381f, 0.04333f, 0.05286f, 0.06287f, 0.07434f, 0.08850f,
1338 0.10803f, 0.14124f },
1339 // TX_16X16
1340 (float[]){ 0.01404f, 0.02000f, 0.04211f, 0.05164f, 0.05798f, 0.06335f,
1341 0.06897f, 0.07629f, 0.08875f, 0.11169f },
1342 // TX_32X32
1343 NULL,
1344 // TX_64X64
1345 NULL,
1346 // TX_4X8
1347 (float[]){ 0.00183f, 0.00745f, 0.01428f, 0.02185f, 0.02966f, 0.03723f,
1348 0.04456f, 0.05188f, 0.05920f, 0.06702f, 0.07605f, 0.08704f,
1349 0.10168f, 0.12585f },
1350 // TX_8X4
1351 (float[]){ 0.00085f, 0.00476f, 0.01135f, 0.01892f, 0.02698f, 0.03528f,
1352 0.04358f, 0.05164f, 0.05994f, 0.06848f, 0.07849f, 0.09021f,
1353 0.10583f, 0.13123f },
1354 // TX_8X16
1355 (float[]){ 0.00037f, 0.00232f, 0.00671f, 0.01257f, 0.01965f, 0.02722f,
1356 0.03552f, 0.04382f, 0.05237f, 0.06189f, 0.07336f, 0.08728f,
1357 0.10730f, 0.14221f },
1358 // TX_16X8
1359 (float[]){ 0.00061f, 0.00330f, 0.00818f, 0.01453f, 0.02185f, 0.02966f,
1360 0.03772f, 0.04578f, 0.05383f, 0.06262f, 0.07288f, 0.08582f,
1361 0.10339f, 0.13464f },
1362 // TX_16X32
1363 NULL,
1364 // TX_32X16
1365 NULL,
1366 // TX_32X64
1367 NULL,
1368 // TX_64X32
1369 NULL,
1370 // TX_4X16
1371 (float[]){ 0.00232f, 0.00671f, 0.01257f, 0.01941f, 0.02673f, 0.03430f,
1372 0.04211f, 0.04968f, 0.05750f, 0.06580f, 0.07507f, 0.08655f,
1373 0.10242f, 0.12878f },
1374 // TX_16X4
1375 (float[]){ 0.00110f, 0.00525f, 0.01208f, 0.01990f, 0.02795f, 0.03601f,
1376 0.04358f, 0.05115f, 0.05896f, 0.06702f, 0.07629f, 0.08752f,
1377 0.10217f, 0.12610f },
1378 // TX_8X32
1379 NULL,
1380 // TX_32X8
1381 NULL,
1382 // TX_16X64
1383 NULL,
1384 // TX_64X16
1385 NULL,
1386 };
1387
get_adaptive_thresholds(TX_SIZE tx_size,TxSetType tx_set_type,TX_TYPE_PRUNE_MODE prune_2d_txfm_mode)1388 static INLINE float get_adaptive_thresholds(
1389 TX_SIZE tx_size, TxSetType tx_set_type,
1390 TX_TYPE_PRUNE_MODE prune_2d_txfm_mode) {
1391 const int prune_aggr_table[5][2] = {
1392 { 4, 1 }, { 6, 3 }, { 9, 6 }, { 9, 6 }, { 12, 9 }
1393 };
1394 int pruning_aggressiveness = 0;
1395 if (tx_set_type == EXT_TX_SET_ALL16)
1396 pruning_aggressiveness =
1397 prune_aggr_table[prune_2d_txfm_mode - TX_TYPE_PRUNE_1][0];
1398 else if (tx_set_type == EXT_TX_SET_DTT9_IDTX_1DDCT)
1399 pruning_aggressiveness =
1400 prune_aggr_table[prune_2d_txfm_mode - TX_TYPE_PRUNE_1][1];
1401
1402 return prune_2D_adaptive_thresholds[tx_size][pruning_aggressiveness];
1403 }
1404
get_energy_distribution_finer(const int16_t * diff,int stride,int bw,int bh,float * hordist,float * verdist)1405 static AOM_INLINE void get_energy_distribution_finer(const int16_t *diff,
1406 int stride, int bw, int bh,
1407 float *hordist,
1408 float *verdist) {
1409 // First compute downscaled block energy values (esq); downscale factors
1410 // are defined by w_shift and h_shift.
1411 unsigned int esq[256];
1412 const int w_shift = bw <= 8 ? 0 : 1;
1413 const int h_shift = bh <= 8 ? 0 : 1;
1414 const int esq_w = bw >> w_shift;
1415 const int esq_h = bh >> h_shift;
1416 const int esq_sz = esq_w * esq_h;
1417 int i, j;
1418 memset(esq, 0, esq_sz * sizeof(esq[0]));
1419 if (w_shift) {
1420 for (i = 0; i < bh; i++) {
1421 unsigned int *cur_esq_row = esq + (i >> h_shift) * esq_w;
1422 const int16_t *cur_diff_row = diff + i * stride;
1423 for (j = 0; j < bw; j += 2) {
1424 cur_esq_row[j >> 1] += (cur_diff_row[j] * cur_diff_row[j] +
1425 cur_diff_row[j + 1] * cur_diff_row[j + 1]);
1426 }
1427 }
1428 } else {
1429 for (i = 0; i < bh; i++) {
1430 unsigned int *cur_esq_row = esq + (i >> h_shift) * esq_w;
1431 const int16_t *cur_diff_row = diff + i * stride;
1432 for (j = 0; j < bw; j++) {
1433 cur_esq_row[j] += cur_diff_row[j] * cur_diff_row[j];
1434 }
1435 }
1436 }
1437
1438 uint64_t total = 0;
1439 for (i = 0; i < esq_sz; i++) total += esq[i];
1440
1441 // Output hordist and verdist arrays are normalized 1D projections of esq
1442 if (total == 0) {
1443 float hor_val = 1.0f / esq_w;
1444 for (j = 0; j < esq_w - 1; j++) hordist[j] = hor_val;
1445 float ver_val = 1.0f / esq_h;
1446 for (i = 0; i < esq_h - 1; i++) verdist[i] = ver_val;
1447 return;
1448 }
1449
1450 const float e_recip = 1.0f / (float)total;
1451 memset(hordist, 0, (esq_w - 1) * sizeof(hordist[0]));
1452 memset(verdist, 0, (esq_h - 1) * sizeof(verdist[0]));
1453 const unsigned int *cur_esq_row;
1454 for (i = 0; i < esq_h - 1; i++) {
1455 cur_esq_row = esq + i * esq_w;
1456 for (j = 0; j < esq_w - 1; j++) {
1457 hordist[j] += (float)cur_esq_row[j];
1458 verdist[i] += (float)cur_esq_row[j];
1459 }
1460 verdist[i] += (float)cur_esq_row[j];
1461 }
1462 cur_esq_row = esq + i * esq_w;
1463 for (j = 0; j < esq_w - 1; j++) hordist[j] += (float)cur_esq_row[j];
1464
1465 for (j = 0; j < esq_w - 1; j++) hordist[j] *= e_recip;
1466 for (i = 0; i < esq_h - 1; i++) verdist[i] *= e_recip;
1467 }
1468
check_bit_mask(uint16_t mask,int val)1469 static AOM_INLINE bool check_bit_mask(uint16_t mask, int val) {
1470 return mask & (1 << val);
1471 }
1472
set_bit_mask(uint16_t * mask,int val)1473 static AOM_INLINE void set_bit_mask(uint16_t *mask, int val) {
1474 *mask |= (1 << val);
1475 }
1476
unset_bit_mask(uint16_t * mask,int val)1477 static AOM_INLINE void unset_bit_mask(uint16_t *mask, int val) {
1478 *mask &= ~(1 << val);
1479 }
1480
prune_tx_2D(MACROBLOCK * x,BLOCK_SIZE bsize,TX_SIZE tx_size,int blk_row,int blk_col,TxSetType tx_set_type,TX_TYPE_PRUNE_MODE prune_2d_txfm_mode,int * txk_map,uint16_t * allowed_tx_mask)1481 static void prune_tx_2D(MACROBLOCK *x, BLOCK_SIZE bsize, TX_SIZE tx_size,
1482 int blk_row, int blk_col, TxSetType tx_set_type,
1483 TX_TYPE_PRUNE_MODE prune_2d_txfm_mode, int *txk_map,
1484 uint16_t *allowed_tx_mask) {
1485 // This table is used because the search order is different from the enum
1486 // order.
1487 static const int tx_type_table_2D[16] = {
1488 DCT_DCT, DCT_ADST, DCT_FLIPADST, V_DCT,
1489 ADST_DCT, ADST_ADST, ADST_FLIPADST, V_ADST,
1490 FLIPADST_DCT, FLIPADST_ADST, FLIPADST_FLIPADST, V_FLIPADST,
1491 H_DCT, H_ADST, H_FLIPADST, IDTX
1492 };
1493 if (tx_set_type != EXT_TX_SET_ALL16 &&
1494 tx_set_type != EXT_TX_SET_DTT9_IDTX_1DDCT)
1495 return;
1496 #if CONFIG_NN_V2
1497 NN_CONFIG_V2 *nn_config_hor = av1_tx_type_nnconfig_map_hor[tx_size];
1498 NN_CONFIG_V2 *nn_config_ver = av1_tx_type_nnconfig_map_ver[tx_size];
1499 #else
1500 const NN_CONFIG *nn_config_hor = av1_tx_type_nnconfig_map_hor[tx_size];
1501 const NN_CONFIG *nn_config_ver = av1_tx_type_nnconfig_map_ver[tx_size];
1502 #endif
1503 if (!nn_config_hor || !nn_config_ver) return; // Model not established yet.
1504
1505 float hfeatures[16], vfeatures[16];
1506 float hscores[4], vscores[4];
1507 float scores_2D_raw[16];
1508 const int bw = tx_size_wide[tx_size];
1509 const int bh = tx_size_high[tx_size];
1510 const int hfeatures_num = bw <= 8 ? bw : bw / 2;
1511 const int vfeatures_num = bh <= 8 ? bh : bh / 2;
1512 assert(hfeatures_num <= 16);
1513 assert(vfeatures_num <= 16);
1514
1515 const struct macroblock_plane *const p = &x->plane[0];
1516 const int diff_stride = block_size_wide[bsize];
1517 const int16_t *diff = p->src_diff + 4 * blk_row * diff_stride + 4 * blk_col;
1518 get_energy_distribution_finer(diff, diff_stride, bw, bh, hfeatures,
1519 vfeatures);
1520
1521 av1_get_horver_correlation_full(diff, diff_stride, bw, bh,
1522 &hfeatures[hfeatures_num - 1],
1523 &vfeatures[vfeatures_num - 1]);
1524
1525 #if CONFIG_NN_V2
1526 av1_nn_predict_v2(hfeatures, nn_config_hor, 0, hscores);
1527 av1_nn_predict_v2(vfeatures, nn_config_ver, 0, vscores);
1528 #else
1529 av1_nn_predict(hfeatures, nn_config_hor, 1, hscores);
1530 av1_nn_predict(vfeatures, nn_config_ver, 1, vscores);
1531 #endif
1532
1533 for (int i = 0; i < 4; i++) {
1534 float *cur_scores_2D = scores_2D_raw + i * 4;
1535 cur_scores_2D[0] = vscores[i] * hscores[0];
1536 cur_scores_2D[1] = vscores[i] * hscores[1];
1537 cur_scores_2D[2] = vscores[i] * hscores[2];
1538 cur_scores_2D[3] = vscores[i] * hscores[3];
1539 }
1540
1541 assert(TX_TYPES == 16);
1542 // This version of the function only works when there are at most 16 classes.
1543 // So we will need to change the optimization or use av1_nn_softmax instead if
1544 // this ever gets changed.
1545 av1_nn_fast_softmax_16(scores_2D_raw, scores_2D_raw);
1546
1547 const float score_thresh =
1548 get_adaptive_thresholds(tx_size, tx_set_type, prune_2d_txfm_mode);
1549
1550 // Always keep the TX type with the highest score, prune all others with
1551 // score below score_thresh.
1552 int max_score_i = 0;
1553 float max_score = 0.0f;
1554 uint16_t allow_bitmask = 0;
1555 float sum_score = 0.0;
1556 // Calculate sum of allowed tx type score and Populate allow bit mask based
1557 // on score_thresh and allowed_tx_mask
1558 int allow_count = 0;
1559 int tx_type_allowed[16] = { TX_TYPE_INVALID, TX_TYPE_INVALID, TX_TYPE_INVALID,
1560 TX_TYPE_INVALID, TX_TYPE_INVALID, TX_TYPE_INVALID,
1561 TX_TYPE_INVALID, TX_TYPE_INVALID, TX_TYPE_INVALID,
1562 TX_TYPE_INVALID, TX_TYPE_INVALID, TX_TYPE_INVALID,
1563 TX_TYPE_INVALID, TX_TYPE_INVALID, TX_TYPE_INVALID,
1564 TX_TYPE_INVALID };
1565 float scores_2D[16] = {
1566 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1567 };
1568 for (int tx_idx = 0; tx_idx < TX_TYPES; tx_idx++) {
1569 const int allow_tx_type =
1570 check_bit_mask(*allowed_tx_mask, tx_type_table_2D[tx_idx]);
1571 if (!allow_tx_type) {
1572 continue;
1573 }
1574 if (scores_2D_raw[tx_idx] > max_score) {
1575 max_score = scores_2D_raw[tx_idx];
1576 max_score_i = tx_idx;
1577 }
1578 if (scores_2D_raw[tx_idx] >= score_thresh) {
1579 // Set allow mask based on score_thresh
1580 set_bit_mask(&allow_bitmask, tx_type_table_2D[tx_idx]);
1581
1582 // Accumulate score of allowed tx type
1583 sum_score += scores_2D_raw[tx_idx];
1584
1585 scores_2D[allow_count] = scores_2D_raw[tx_idx];
1586 tx_type_allowed[allow_count] = tx_type_table_2D[tx_idx];
1587 allow_count += 1;
1588 }
1589 }
1590 if (!check_bit_mask(allow_bitmask, tx_type_table_2D[max_score_i])) {
1591 // If even the tx_type with max score is pruned, this means that no other
1592 // tx_type is feasible. When this happens, we force enable max_score_i and
1593 // end the search.
1594 set_bit_mask(&allow_bitmask, tx_type_table_2D[max_score_i]);
1595 memcpy(txk_map, tx_type_table_2D, sizeof(tx_type_table_2D));
1596 *allowed_tx_mask = allow_bitmask;
1597 return;
1598 }
1599
1600 // Sort tx type probability of all types
1601 if (allow_count <= 8) {
1602 av1_sort_fi32_8(scores_2D, tx_type_allowed);
1603 } else {
1604 av1_sort_fi32_16(scores_2D, tx_type_allowed);
1605 }
1606
1607 // Enable more pruning based on tx type probability and number of allowed tx
1608 // types
1609 if (prune_2d_txfm_mode >= TX_TYPE_PRUNE_4) {
1610 float temp_score = 0.0;
1611 float score_ratio = 0.0;
1612 int tx_idx, tx_count = 0;
1613 const float inv_sum_score = 100 / sum_score;
1614 // Get allowed tx types based on sorted probability score and tx count
1615 for (tx_idx = 0; tx_idx < allow_count; tx_idx++) {
1616 // Skip the tx type which has more than 30% of cumulative
1617 // probability and allowed tx type count is more than 2
1618 if (score_ratio > 30.0 && tx_count >= 2) break;
1619
1620 assert(check_bit_mask(allow_bitmask, tx_type_allowed[tx_idx]));
1621 // Calculate cumulative probability
1622 temp_score += scores_2D[tx_idx];
1623
1624 // Calculate percentage of cumulative probability of allowed tx type
1625 score_ratio = temp_score * inv_sum_score;
1626 tx_count++;
1627 }
1628 // Set remaining tx types as pruned
1629 for (; tx_idx < allow_count; tx_idx++)
1630 unset_bit_mask(&allow_bitmask, tx_type_allowed[tx_idx]);
1631 }
1632
1633 memcpy(txk_map, tx_type_allowed, sizeof(tx_type_table_2D));
1634 *allowed_tx_mask = allow_bitmask;
1635 }
1636
get_dev(float mean,double x2_sum,int num)1637 static float get_dev(float mean, double x2_sum, int num) {
1638 const float e_x2 = (float)(x2_sum / num);
1639 const float diff = e_x2 - mean * mean;
1640 const float dev = (diff > 0) ? sqrtf(diff) : 0;
1641 return dev;
1642 }
1643
1644 // Writes the features required by the ML model to predict tx split based on
1645 // mean and standard deviation values of the block and sub-blocks.
1646 // Returns the number of elements written to the output array which is at most
1647 // 12 currently. Hence 'features' buffer should be able to accommodate at least
1648 // 12 elements.
get_mean_dev_features(const int16_t * data,int stride,int bw,int bh,float * features)1649 static AOM_INLINE int get_mean_dev_features(const int16_t *data, int stride,
1650 int bw, int bh, float *features) {
1651 const int16_t *const data_ptr = &data[0];
1652 const int subh = (bh >= bw) ? (bh >> 1) : bh;
1653 const int subw = (bw >= bh) ? (bw >> 1) : bw;
1654 const int num = bw * bh;
1655 const int sub_num = subw * subh;
1656 int feature_idx = 2;
1657 int total_x_sum = 0;
1658 int64_t total_x2_sum = 0;
1659 int num_sub_blks = 0;
1660 double mean2_sum = 0.0f;
1661 float dev_sum = 0.0f;
1662
1663 for (int row = 0; row < bh; row += subh) {
1664 for (int col = 0; col < bw; col += subw) {
1665 int x_sum;
1666 int64_t x2_sum;
1667 // TODO(any): Write a SIMD version. Clear registers.
1668 aom_get_blk_sse_sum(data_ptr + row * stride + col, stride, subw, subh,
1669 &x_sum, &x2_sum);
1670 total_x_sum += x_sum;
1671 total_x2_sum += x2_sum;
1672
1673 const float mean = (float)x_sum / sub_num;
1674 const float dev = get_dev(mean, (double)x2_sum, sub_num);
1675 features[feature_idx++] = mean;
1676 features[feature_idx++] = dev;
1677 mean2_sum += (double)(mean * mean);
1678 dev_sum += dev;
1679 num_sub_blks++;
1680 }
1681 }
1682
1683 const float lvl0_mean = (float)total_x_sum / num;
1684 features[0] = lvl0_mean;
1685 features[1] = get_dev(lvl0_mean, (double)total_x2_sum, num);
1686
1687 // Deviation of means.
1688 features[feature_idx++] = get_dev(lvl0_mean, mean2_sum, num_sub_blks);
1689 // Mean of deviations.
1690 features[feature_idx++] = dev_sum / num_sub_blks;
1691
1692 return feature_idx;
1693 }
1694
ml_predict_tx_split(MACROBLOCK * x,BLOCK_SIZE bsize,int blk_row,int blk_col,TX_SIZE tx_size)1695 static int ml_predict_tx_split(MACROBLOCK *x, BLOCK_SIZE bsize, int blk_row,
1696 int blk_col, TX_SIZE tx_size) {
1697 const NN_CONFIG *nn_config = av1_tx_split_nnconfig_map[tx_size];
1698 if (!nn_config) return -1;
1699
1700 const int diff_stride = block_size_wide[bsize];
1701 const int16_t *diff =
1702 x->plane[0].src_diff + 4 * blk_row * diff_stride + 4 * blk_col;
1703 const int bw = tx_size_wide[tx_size];
1704 const int bh = tx_size_high[tx_size];
1705
1706 float features[64] = { 0.0f };
1707 get_mean_dev_features(diff, diff_stride, bw, bh, features);
1708
1709 float score = 0.0f;
1710 av1_nn_predict(features, nn_config, 1, &score);
1711
1712 int int_score = (int)(score * 10000);
1713 return clamp(int_score, -80000, 80000);
1714 }
1715
1716 static INLINE uint16_t
get_tx_mask(const AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,const TXB_CTX * const txb_ctx,FAST_TX_SEARCH_MODE ftxs_mode,int64_t ref_best_rd,TX_TYPE * allowed_txk_types,int * txk_map)1717 get_tx_mask(const AV1_COMP *cpi, MACROBLOCK *x, int plane, int block,
1718 int blk_row, int blk_col, BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
1719 const TXB_CTX *const txb_ctx, FAST_TX_SEARCH_MODE ftxs_mode,
1720 int64_t ref_best_rd, TX_TYPE *allowed_txk_types, int *txk_map) {
1721 const AV1_COMMON *cm = &cpi->common;
1722 MACROBLOCKD *xd = &x->e_mbd;
1723 MB_MODE_INFO *mbmi = xd->mi[0];
1724 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
1725 const int is_inter = is_inter_block(mbmi);
1726 const int fast_tx_search = ftxs_mode & FTXS_DCT_AND_1D_DCT_ONLY;
1727 // if txk_allowed = TX_TYPES, >1 tx types are allowed, else, if txk_allowed <
1728 // TX_TYPES, only that specific tx type is allowed.
1729 TX_TYPE txk_allowed = TX_TYPES;
1730
1731 const FRAME_UPDATE_TYPE update_type =
1732 get_frame_update_type(&cpi->ppi->gf_group, cpi->gf_frame_index);
1733 int use_actual_frame_probs = 1;
1734 const int *tx_type_probs;
1735 #if CONFIG_FPMT_TEST
1736 use_actual_frame_probs =
1737 (cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) ? 0 : 1;
1738 if (!use_actual_frame_probs) {
1739 tx_type_probs =
1740 (int *)cpi->ppi->temp_frame_probs.tx_type_probs[update_type][tx_size];
1741 }
1742 #endif
1743 if (use_actual_frame_probs) {
1744 tx_type_probs = cpi->ppi->frame_probs.tx_type_probs[update_type][tx_size];
1745 }
1746
1747 if ((!is_inter && txfm_params->use_default_intra_tx_type) ||
1748 (is_inter && txfm_params->default_inter_tx_type_prob_thresh == 0)) {
1749 txk_allowed =
1750 get_default_tx_type(0, xd, tx_size, cpi->use_screen_content_tools);
1751 } else if (is_inter &&
1752 txfm_params->default_inter_tx_type_prob_thresh != INT_MAX) {
1753 if (tx_type_probs[DEFAULT_INTER_TX_TYPE] >
1754 txfm_params->default_inter_tx_type_prob_thresh) {
1755 txk_allowed = DEFAULT_INTER_TX_TYPE;
1756 } else {
1757 int force_tx_type = 0;
1758 int max_prob = 0;
1759 const int tx_type_prob_threshold =
1760 txfm_params->default_inter_tx_type_prob_thresh +
1761 PROB_THRESH_OFFSET_TX_TYPE;
1762 for (int i = 1; i < TX_TYPES; i++) { // find maximum probability.
1763 if (tx_type_probs[i] > max_prob) {
1764 max_prob = tx_type_probs[i];
1765 force_tx_type = i;
1766 }
1767 }
1768 if (max_prob > tx_type_prob_threshold) // force tx type with max prob.
1769 txk_allowed = force_tx_type;
1770 else if (x->rd_model == LOW_TXFM_RD) {
1771 if (plane == 0) txk_allowed = DCT_DCT;
1772 }
1773 }
1774 } else if (x->rd_model == LOW_TXFM_RD) {
1775 if (plane == 0) txk_allowed = DCT_DCT;
1776 }
1777
1778 const TxSetType tx_set_type = av1_get_ext_tx_set_type(
1779 tx_size, is_inter, cm->features.reduced_tx_set_used);
1780
1781 TX_TYPE uv_tx_type = DCT_DCT;
1782 if (plane) {
1783 // tx_type of PLANE_TYPE_UV should be the same as PLANE_TYPE_Y
1784 uv_tx_type = txk_allowed =
1785 av1_get_tx_type(xd, get_plane_type(plane), blk_row, blk_col, tx_size,
1786 cm->features.reduced_tx_set_used);
1787 }
1788 PREDICTION_MODE intra_dir =
1789 mbmi->filter_intra_mode_info.use_filter_intra
1790 ? fimode_to_intradir[mbmi->filter_intra_mode_info.filter_intra_mode]
1791 : mbmi->mode;
1792 uint16_t ext_tx_used_flag =
1793 cpi->sf.tx_sf.tx_type_search.use_reduced_intra_txset != 0 &&
1794 tx_set_type == EXT_TX_SET_DTT4_IDTX_1DDCT
1795 ? av1_reduced_intra_tx_used_flag[intra_dir]
1796 : av1_ext_tx_used_flag[tx_set_type];
1797
1798 if (cpi->sf.tx_sf.tx_type_search.use_reduced_intra_txset == 2)
1799 ext_tx_used_flag &= av1_derived_intra_tx_used_flag[intra_dir];
1800
1801 if (xd->lossless[mbmi->segment_id] || txsize_sqr_up_map[tx_size] > TX_32X32 ||
1802 ext_tx_used_flag == 0x0001 ||
1803 (is_inter && cpi->oxcf.txfm_cfg.use_inter_dct_only) ||
1804 (!is_inter && cpi->oxcf.txfm_cfg.use_intra_dct_only)) {
1805 txk_allowed = DCT_DCT;
1806 }
1807
1808 if (cpi->oxcf.txfm_cfg.enable_flip_idtx == 0)
1809 ext_tx_used_flag &= DCT_ADST_TX_MASK;
1810
1811 uint16_t allowed_tx_mask = 0; // 1: allow; 0: skip.
1812 if (txk_allowed < TX_TYPES) {
1813 allowed_tx_mask = 1 << txk_allowed;
1814 allowed_tx_mask &= ext_tx_used_flag;
1815 } else if (fast_tx_search) {
1816 allowed_tx_mask = 0x0c01; // V_DCT, H_DCT, DCT_DCT
1817 allowed_tx_mask &= ext_tx_used_flag;
1818 } else {
1819 assert(plane == 0);
1820 allowed_tx_mask = ext_tx_used_flag;
1821 int num_allowed = 0;
1822 int i;
1823
1824 if (cpi->sf.tx_sf.tx_type_search.prune_tx_type_using_stats) {
1825 static const int thresh_arr[2][7] = { { 10, 15, 15, 10, 15, 15, 15 },
1826 { 10, 17, 17, 10, 17, 17, 17 } };
1827 const int thresh =
1828 thresh_arr[cpi->sf.tx_sf.tx_type_search.prune_tx_type_using_stats - 1]
1829 [update_type];
1830 uint16_t prune = 0;
1831 int max_prob = -1;
1832 int max_idx = 0;
1833 for (i = 0; i < TX_TYPES; i++) {
1834 if (tx_type_probs[i] > max_prob && (allowed_tx_mask & (1 << i))) {
1835 max_prob = tx_type_probs[i];
1836 max_idx = i;
1837 }
1838 if (tx_type_probs[i] < thresh) prune |= (1 << i);
1839 }
1840 if ((prune >> max_idx) & 0x01) prune &= ~(1 << max_idx);
1841 allowed_tx_mask &= (~prune);
1842 }
1843 for (i = 0; i < TX_TYPES; i++) {
1844 if (allowed_tx_mask & (1 << i)) num_allowed++;
1845 }
1846 assert(num_allowed > 0);
1847
1848 if (num_allowed > 2 && cpi->sf.tx_sf.tx_type_search.prune_tx_type_est_rd) {
1849 int pf = prune_factors[txfm_params->prune_2d_txfm_mode];
1850 int mf = mul_factors[txfm_params->prune_2d_txfm_mode];
1851 if (num_allowed <= 7) {
1852 const uint16_t prune =
1853 prune_txk_type(cpi, x, plane, block, tx_size, blk_row, blk_col,
1854 plane_bsize, txk_map, allowed_tx_mask, pf, txb_ctx,
1855 cm->features.reduced_tx_set_used);
1856 allowed_tx_mask &= (~prune);
1857 } else {
1858 const int num_sel = (num_allowed * mf + 50) / 100;
1859 const uint16_t prune = prune_txk_type_separ(
1860 cpi, x, plane, block, tx_size, blk_row, blk_col, plane_bsize,
1861 txk_map, allowed_tx_mask, pf, txb_ctx,
1862 cm->features.reduced_tx_set_used, ref_best_rd, num_sel);
1863
1864 allowed_tx_mask &= (~prune);
1865 }
1866 } else {
1867 assert(num_allowed > 0);
1868 int allowed_tx_count =
1869 (txfm_params->prune_2d_txfm_mode >= TX_TYPE_PRUNE_4) ? 1 : 5;
1870 // !fast_tx_search && txk_end != txk_start && plane == 0
1871 if (txfm_params->prune_2d_txfm_mode >= TX_TYPE_PRUNE_1 && is_inter &&
1872 num_allowed > allowed_tx_count) {
1873 prune_tx_2D(x, plane_bsize, tx_size, blk_row, blk_col, tx_set_type,
1874 txfm_params->prune_2d_txfm_mode, txk_map, &allowed_tx_mask);
1875 }
1876 }
1877 }
1878
1879 // Need to have at least one transform type allowed.
1880 if (allowed_tx_mask == 0) {
1881 txk_allowed = (plane ? uv_tx_type : DCT_DCT);
1882 allowed_tx_mask = (1 << txk_allowed);
1883 }
1884
1885 assert(IMPLIES(txk_allowed < TX_TYPES, allowed_tx_mask == 1 << txk_allowed));
1886 *allowed_txk_types = txk_allowed;
1887 return allowed_tx_mask;
1888 }
1889
1890 #if CONFIG_RD_DEBUG
update_txb_coeff_cost(RD_STATS * rd_stats,int plane,int txb_coeff_cost)1891 static INLINE void update_txb_coeff_cost(RD_STATS *rd_stats, int plane,
1892 int txb_coeff_cost) {
1893 rd_stats->txb_coeff_cost[plane] += txb_coeff_cost;
1894 }
1895 #endif
1896
cost_coeffs(MACROBLOCK * x,int plane,int block,TX_SIZE tx_size,const TX_TYPE tx_type,const TXB_CTX * const txb_ctx,int reduced_tx_set_used)1897 static INLINE int cost_coeffs(MACROBLOCK *x, int plane, int block,
1898 TX_SIZE tx_size, const TX_TYPE tx_type,
1899 const TXB_CTX *const txb_ctx,
1900 int reduced_tx_set_used) {
1901 #if TXCOEFF_COST_TIMER
1902 struct aom_usec_timer timer;
1903 aom_usec_timer_start(&timer);
1904 #endif
1905 const int cost = av1_cost_coeffs_txb(x, plane, block, tx_size, tx_type,
1906 txb_ctx, reduced_tx_set_used);
1907 #if TXCOEFF_COST_TIMER
1908 AV1_COMMON *tmp_cm = (AV1_COMMON *)&cpi->common;
1909 aom_usec_timer_mark(&timer);
1910 const int64_t elapsed_time = aom_usec_timer_elapsed(&timer);
1911 tmp_cm->txcoeff_cost_timer += elapsed_time;
1912 ++tmp_cm->txcoeff_cost_count;
1913 #endif
1914 return cost;
1915 }
1916
skip_trellis_opt_based_on_satd(MACROBLOCK * x,QUANT_PARAM * quant_param,int plane,int block,TX_SIZE tx_size,int quant_b_adapt,int qstep,unsigned int coeff_opt_satd_threshold,int skip_trellis,int dc_only_blk)1917 static int skip_trellis_opt_based_on_satd(MACROBLOCK *x,
1918 QUANT_PARAM *quant_param, int plane,
1919 int block, TX_SIZE tx_size,
1920 int quant_b_adapt, int qstep,
1921 unsigned int coeff_opt_satd_threshold,
1922 int skip_trellis, int dc_only_blk) {
1923 if (skip_trellis || (coeff_opt_satd_threshold == UINT_MAX))
1924 return skip_trellis;
1925
1926 const struct macroblock_plane *const p = &x->plane[plane];
1927 const int block_offset = BLOCK_OFFSET(block);
1928 tran_low_t *const coeff_ptr = p->coeff + block_offset;
1929 const int n_coeffs = av1_get_max_eob(tx_size);
1930 const int shift = (MAX_TX_SCALE - av1_get_tx_scale(tx_size));
1931 int satd = (dc_only_blk) ? abs(coeff_ptr[0]) : aom_satd(coeff_ptr, n_coeffs);
1932 satd = RIGHT_SIGNED_SHIFT(satd, shift);
1933 satd >>= (x->e_mbd.bd - 8);
1934
1935 const int skip_block_trellis =
1936 ((uint64_t)satd >
1937 (uint64_t)coeff_opt_satd_threshold * qstep * sqrt_tx_pixels_2d[tx_size]);
1938
1939 av1_setup_quant(
1940 tx_size, !skip_block_trellis,
1941 skip_block_trellis
1942 ? (USE_B_QUANT_NO_TRELLIS ? AV1_XFORM_QUANT_B : AV1_XFORM_QUANT_FP)
1943 : AV1_XFORM_QUANT_FP,
1944 quant_b_adapt, quant_param);
1945
1946 return skip_block_trellis;
1947 }
1948
1949 // Predict DC only blocks if the residual variance is below a qstep based
1950 // threshold.For such blocks, transform type search is bypassed.
predict_dc_only_block(MACROBLOCK * x,int plane,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,int block,int blk_row,int blk_col,RD_STATS * best_rd_stats,int64_t * block_sse,unsigned int * block_mse_q8,int64_t * per_px_mean,int * dc_only_blk)1951 static INLINE void predict_dc_only_block(
1952 MACROBLOCK *x, int plane, BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
1953 int block, int blk_row, int blk_col, RD_STATS *best_rd_stats,
1954 int64_t *block_sse, unsigned int *block_mse_q8, int64_t *per_px_mean,
1955 int *dc_only_blk) {
1956 MACROBLOCKD *xd = &x->e_mbd;
1957 MB_MODE_INFO *mbmi = xd->mi[0];
1958 const int dequant_shift = (is_cur_buf_hbd(xd)) ? xd->bd - 5 : 3;
1959 const int qstep = x->plane[plane].dequant_QTX[1] >> dequant_shift;
1960 uint64_t block_var = UINT64_MAX;
1961 const int dc_qstep = x->plane[plane].dequant_QTX[0] >> 3;
1962 *block_sse = pixel_diff_stats(x, plane, blk_row, blk_col, plane_bsize,
1963 txsize_to_bsize[tx_size], block_mse_q8,
1964 per_px_mean, &block_var);
1965 assert((*block_mse_q8) != UINT_MAX);
1966 uint64_t var_threshold = (uint64_t)(1.8 * qstep * qstep);
1967 if (is_cur_buf_hbd(xd))
1968 block_var = ROUND_POWER_OF_TWO(block_var, (xd->bd - 8) * 2);
1969
1970 if (block_var >= var_threshold) return;
1971 const unsigned int predict_dc_level = x->txfm_search_params.predict_dc_level;
1972 assert(predict_dc_level != 0);
1973
1974 // Prediction of skip block if residual mean and variance are less
1975 // than qstep based threshold
1976 if ((llabs(*per_px_mean) * dc_coeff_scale[tx_size]) < (dc_qstep << 12)) {
1977 // If the normalized mean of residual block is less than the dc qstep and
1978 // the normalized block variance is less than ac qstep, then the block is
1979 // assumed to be a skip block and its rdcost is updated accordingly.
1980 best_rd_stats->skip_txfm = 1;
1981
1982 x->plane[plane].eobs[block] = 0;
1983
1984 if (is_cur_buf_hbd(xd))
1985 *block_sse = ROUND_POWER_OF_TWO((*block_sse), (xd->bd - 8) * 2);
1986
1987 best_rd_stats->dist = (*block_sse) << 4;
1988 best_rd_stats->sse = best_rd_stats->dist;
1989
1990 ENTROPY_CONTEXT ctxa[MAX_MIB_SIZE];
1991 ENTROPY_CONTEXT ctxl[MAX_MIB_SIZE];
1992 av1_get_entropy_contexts(plane_bsize, &xd->plane[plane], ctxa, ctxl);
1993 ENTROPY_CONTEXT *ta = ctxa;
1994 ENTROPY_CONTEXT *tl = ctxl;
1995 const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
1996 TXB_CTX txb_ctx_tmp;
1997 const PLANE_TYPE plane_type = get_plane_type(plane);
1998 get_txb_ctx(plane_bsize, tx_size, plane, ta, tl, &txb_ctx_tmp);
1999 const int zero_blk_rate = x->coeff_costs.coeff_costs[txs_ctx][plane_type]
2000 .txb_skip_cost[txb_ctx_tmp.txb_skip_ctx][1];
2001 best_rd_stats->rate = zero_blk_rate;
2002
2003 best_rd_stats->rdcost =
2004 RDCOST(x->rdmult, best_rd_stats->rate, best_rd_stats->sse);
2005
2006 x->plane[plane].txb_entropy_ctx[block] = 0;
2007 } else if (predict_dc_level > 1) {
2008 // Predict DC only blocks based on residual variance.
2009 // For chroma plane, this prediction is disabled for intra blocks.
2010 if ((plane == 0) || (plane > 0 && is_inter_block(mbmi))) *dc_only_blk = 1;
2011 }
2012 }
2013
2014 // Search for the best transform type for a given transform block.
2015 // This function can be used for both inter and intra, both luma and chroma.
search_tx_type(const AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,const TXB_CTX * const txb_ctx,FAST_TX_SEARCH_MODE ftxs_mode,int skip_trellis,int64_t ref_best_rd,RD_STATS * best_rd_stats)2016 static void search_tx_type(const AV1_COMP *cpi, MACROBLOCK *x, int plane,
2017 int block, int blk_row, int blk_col,
2018 BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
2019 const TXB_CTX *const txb_ctx,
2020 FAST_TX_SEARCH_MODE ftxs_mode, int skip_trellis,
2021 int64_t ref_best_rd, RD_STATS *best_rd_stats) {
2022 const AV1_COMMON *cm = &cpi->common;
2023 MACROBLOCKD *xd = &x->e_mbd;
2024 MB_MODE_INFO *mbmi = xd->mi[0];
2025 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
2026 int64_t best_rd = INT64_MAX;
2027 uint16_t best_eob = 0;
2028 TX_TYPE best_tx_type = DCT_DCT;
2029 int rate_cost = 0;
2030 struct macroblock_plane *const p = &x->plane[plane];
2031 tran_low_t *orig_dqcoeff = p->dqcoeff;
2032 tran_low_t *best_dqcoeff = x->dqcoeff_buf;
2033 const int tx_type_map_idx =
2034 plane ? 0 : blk_row * xd->tx_type_map_stride + blk_col;
2035 av1_invalid_rd_stats(best_rd_stats);
2036
2037 skip_trellis |= !is_trellis_used(cpi->optimize_seg_arr[xd->mi[0]->segment_id],
2038 DRY_RUN_NORMAL);
2039
2040 uint8_t best_txb_ctx = 0;
2041 // txk_allowed = TX_TYPES: >1 tx types are allowed
2042 // txk_allowed < TX_TYPES: only that specific tx type is allowed.
2043 TX_TYPE txk_allowed = TX_TYPES;
2044 int txk_map[TX_TYPES] = {
2045 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
2046 };
2047 const int dequant_shift = (is_cur_buf_hbd(xd)) ? xd->bd - 5 : 3;
2048 const int qstep = x->plane[plane].dequant_QTX[1] >> dequant_shift;
2049
2050 const uint8_t txw = tx_size_wide[tx_size];
2051 const uint8_t txh = tx_size_high[tx_size];
2052 int64_t block_sse;
2053 unsigned int block_mse_q8;
2054 int dc_only_blk = 0;
2055 const bool predict_dc_block =
2056 txfm_params->predict_dc_level >= 1 && txw != 64 && txh != 64;
2057 int64_t per_px_mean = INT64_MAX;
2058 if (predict_dc_block) {
2059 predict_dc_only_block(x, plane, plane_bsize, tx_size, block, blk_row,
2060 blk_col, best_rd_stats, &block_sse, &block_mse_q8,
2061 &per_px_mean, &dc_only_blk);
2062 if (best_rd_stats->skip_txfm == 1) {
2063 const TX_TYPE tx_type = DCT_DCT;
2064 if (plane == 0) xd->tx_type_map[tx_type_map_idx] = tx_type;
2065 return;
2066 }
2067 } else {
2068 block_sse = av1_pixel_diff_dist(x, plane, blk_row, blk_col, plane_bsize,
2069 txsize_to_bsize[tx_size], &block_mse_q8);
2070 assert(block_mse_q8 != UINT_MAX);
2071 }
2072
2073 // Bit mask to indicate which transform types are allowed in the RD search.
2074 uint16_t tx_mask;
2075
2076 // Use DCT_DCT transform for DC only block.
2077 if (dc_only_blk || cpi->sf.rt_sf.dct_only_palette_nonrd == 1)
2078 tx_mask = 1 << DCT_DCT;
2079 else
2080 tx_mask = get_tx_mask(cpi, x, plane, block, blk_row, blk_col, plane_bsize,
2081 tx_size, txb_ctx, ftxs_mode, ref_best_rd,
2082 &txk_allowed, txk_map);
2083 const uint16_t allowed_tx_mask = tx_mask;
2084
2085 if (is_cur_buf_hbd(xd)) {
2086 block_sse = ROUND_POWER_OF_TWO(block_sse, (xd->bd - 8) * 2);
2087 block_mse_q8 = ROUND_POWER_OF_TWO(block_mse_q8, (xd->bd - 8) * 2);
2088 }
2089 block_sse *= 16;
2090 // Use mse / qstep^2 based threshold logic to take decision of R-D
2091 // optimization of coeffs. For smaller residuals, coeff optimization
2092 // would be helpful. For larger residuals, R-D optimization may not be
2093 // effective.
2094 // TODO(any): Experiment with variance and mean based thresholds
2095 const int perform_block_coeff_opt =
2096 ((uint64_t)block_mse_q8 <=
2097 (uint64_t)txfm_params->coeff_opt_thresholds[0] * qstep * qstep);
2098 skip_trellis |= !perform_block_coeff_opt;
2099
2100 // Flag to indicate if distortion should be calculated in transform domain or
2101 // not during iterating through transform type candidates.
2102 // Transform domain distortion is accurate for higher residuals.
2103 // TODO(any): Experiment with variance and mean based thresholds
2104 int use_transform_domain_distortion =
2105 (txfm_params->use_transform_domain_distortion > 0) &&
2106 (block_mse_q8 >= txfm_params->tx_domain_dist_threshold) &&
2107 // Any 64-pt transforms only preserves half the coefficients.
2108 // Therefore transform domain distortion is not valid for these
2109 // transform sizes.
2110 (txsize_sqr_up_map[tx_size] != TX_64X64) &&
2111 // Use pixel domain distortion for DC only blocks
2112 !dc_only_blk;
2113 // Flag to indicate if an extra calculation of distortion in the pixel domain
2114 // should be performed at the end, after the best transform type has been
2115 // decided.
2116 int calc_pixel_domain_distortion_final =
2117 txfm_params->use_transform_domain_distortion == 1 &&
2118 use_transform_domain_distortion && x->rd_model != LOW_TXFM_RD;
2119 if (calc_pixel_domain_distortion_final &&
2120 (txk_allowed < TX_TYPES || allowed_tx_mask == 0x0001))
2121 calc_pixel_domain_distortion_final = use_transform_domain_distortion = 0;
2122
2123 const uint16_t *eobs_ptr = x->plane[plane].eobs;
2124
2125 TxfmParam txfm_param;
2126 QUANT_PARAM quant_param;
2127 int skip_trellis_based_on_satd[TX_TYPES] = { 0 };
2128 av1_setup_xform(cm, x, tx_size, DCT_DCT, &txfm_param);
2129 av1_setup_quant(tx_size, !skip_trellis,
2130 skip_trellis ? (USE_B_QUANT_NO_TRELLIS ? AV1_XFORM_QUANT_B
2131 : AV1_XFORM_QUANT_FP)
2132 : AV1_XFORM_QUANT_FP,
2133 cpi->oxcf.q_cfg.quant_b_adapt, &quant_param);
2134
2135 // Iterate through all transform type candidates.
2136 for (int idx = 0; idx < TX_TYPES; ++idx) {
2137 const TX_TYPE tx_type = (TX_TYPE)txk_map[idx];
2138 if (tx_type == TX_TYPE_INVALID || !check_bit_mask(allowed_tx_mask, tx_type))
2139 continue;
2140 txfm_param.tx_type = tx_type;
2141 if (av1_use_qmatrix(&cm->quant_params, xd, mbmi->segment_id)) {
2142 av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
2143 &quant_param);
2144 }
2145 if (plane == 0) xd->tx_type_map[tx_type_map_idx] = tx_type;
2146 RD_STATS this_rd_stats;
2147 av1_invalid_rd_stats(&this_rd_stats);
2148
2149 if (!dc_only_blk)
2150 av1_xform(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param);
2151 else
2152 av1_xform_dc_only(x, plane, block, &txfm_param, per_px_mean);
2153
2154 skip_trellis_based_on_satd[tx_type] = skip_trellis_opt_based_on_satd(
2155 x, &quant_param, plane, block, tx_size, cpi->oxcf.q_cfg.quant_b_adapt,
2156 qstep, txfm_params->coeff_opt_thresholds[1], skip_trellis, dc_only_blk);
2157
2158 av1_quant(x, plane, block, &txfm_param, &quant_param);
2159
2160 // Calculate rate cost of quantized coefficients.
2161 if (quant_param.use_optimize_b) {
2162 // TODO(aomedia:3209): update Trellis quantization to take into account
2163 // quantization matrices.
2164 av1_optimize_b(cpi, x, plane, block, tx_size, tx_type, txb_ctx,
2165 &rate_cost);
2166 } else {
2167 rate_cost = cost_coeffs(x, plane, block, tx_size, tx_type, txb_ctx,
2168 cm->features.reduced_tx_set_used);
2169 }
2170
2171 // If rd cost based on coeff rate alone is already more than best_rd,
2172 // terminate early.
2173 if (RDCOST(x->rdmult, rate_cost, 0) > best_rd) continue;
2174
2175 // Calculate distortion.
2176 if (eobs_ptr[block] == 0) {
2177 // When eob is 0, pixel domain distortion is more efficient and accurate.
2178 this_rd_stats.dist = this_rd_stats.sse = block_sse;
2179 } else if (dc_only_blk) {
2180 this_rd_stats.sse = block_sse;
2181 this_rd_stats.dist = dist_block_px_domain(
2182 cpi, x, plane, plane_bsize, block, blk_row, blk_col, tx_size);
2183 } else if (use_transform_domain_distortion) {
2184 const SCAN_ORDER *const scan_order =
2185 get_scan(txfm_param.tx_size, txfm_param.tx_type);
2186 dist_block_tx_domain(x, plane, block, tx_size, quant_param.qmatrix,
2187 scan_order->scan, &this_rd_stats.dist,
2188 &this_rd_stats.sse);
2189 } else {
2190 int64_t sse_diff = INT64_MAX;
2191 // high_energy threshold assumes that every pixel within a txfm block
2192 // has a residue energy of at least 25% of the maximum, i.e. 128 * 128
2193 // for 8 bit.
2194 const int64_t high_energy_thresh =
2195 ((int64_t)128 * 128 * tx_size_2d[tx_size]);
2196 const int is_high_energy = (block_sse >= high_energy_thresh);
2197 if (tx_size == TX_64X64 || is_high_energy) {
2198 // Because 3 out 4 quadrants of transform coefficients are forced to
2199 // zero, the inverse transform has a tendency to overflow. sse_diff
2200 // is effectively the energy of those 3 quadrants, here we use it
2201 // to decide if we should do pixel domain distortion. If the energy
2202 // is mostly in first quadrant, then it is unlikely that we have
2203 // overflow issue in inverse transform.
2204 const SCAN_ORDER *const scan_order =
2205 get_scan(txfm_param.tx_size, txfm_param.tx_type);
2206 dist_block_tx_domain(x, plane, block, tx_size, quant_param.qmatrix,
2207 scan_order->scan, &this_rd_stats.dist,
2208 &this_rd_stats.sse);
2209 sse_diff = block_sse - this_rd_stats.sse;
2210 }
2211 if (tx_size != TX_64X64 || !is_high_energy ||
2212 (sse_diff * 2) < this_rd_stats.sse) {
2213 const int64_t tx_domain_dist = this_rd_stats.dist;
2214 this_rd_stats.dist = dist_block_px_domain(
2215 cpi, x, plane, plane_bsize, block, blk_row, blk_col, tx_size);
2216 // For high energy blocks, occasionally, the pixel domain distortion
2217 // can be artificially low due to clamping at reconstruction stage
2218 // even when inverse transform output is hugely different from the
2219 // actual residue.
2220 if (is_high_energy && this_rd_stats.dist < tx_domain_dist)
2221 this_rd_stats.dist = tx_domain_dist;
2222 } else {
2223 assert(sse_diff < INT64_MAX);
2224 this_rd_stats.dist += sse_diff;
2225 }
2226 this_rd_stats.sse = block_sse;
2227 }
2228
2229 this_rd_stats.rate = rate_cost;
2230
2231 const int64_t rd =
2232 RDCOST(x->rdmult, this_rd_stats.rate, this_rd_stats.dist);
2233
2234 if (rd < best_rd) {
2235 best_rd = rd;
2236 *best_rd_stats = this_rd_stats;
2237 best_tx_type = tx_type;
2238 best_txb_ctx = x->plane[plane].txb_entropy_ctx[block];
2239 best_eob = x->plane[plane].eobs[block];
2240 // Swap dqcoeff buffers
2241 tran_low_t *const tmp_dqcoeff = best_dqcoeff;
2242 best_dqcoeff = p->dqcoeff;
2243 p->dqcoeff = tmp_dqcoeff;
2244 }
2245
2246 #if CONFIG_COLLECT_RD_STATS == 1
2247 if (plane == 0) {
2248 PrintTransformUnitStats(cpi, x, &this_rd_stats, blk_row, blk_col,
2249 plane_bsize, tx_size, tx_type, rd);
2250 }
2251 #endif // CONFIG_COLLECT_RD_STATS == 1
2252
2253 #if COLLECT_TX_SIZE_DATA
2254 // Generate small sample to restrict output size.
2255 static unsigned int seed = 21743;
2256 if (lcg_rand16(&seed) % 200 == 0) {
2257 FILE *fp = NULL;
2258
2259 if (within_border) {
2260 fp = fopen(av1_tx_size_data_output_file, "a");
2261 }
2262
2263 if (fp) {
2264 // Transform info and RD
2265 const int txb_w = tx_size_wide[tx_size];
2266 const int txb_h = tx_size_high[tx_size];
2267
2268 // Residue signal.
2269 const int diff_stride = block_size_wide[plane_bsize];
2270 struct macroblock_plane *const p = &x->plane[plane];
2271 const int16_t *src_diff =
2272 &p->src_diff[(blk_row * diff_stride + blk_col) * 4];
2273
2274 for (int r = 0; r < txb_h; ++r) {
2275 for (int c = 0; c < txb_w; ++c) {
2276 fprintf(fp, "%d,", src_diff[c]);
2277 }
2278 src_diff += diff_stride;
2279 }
2280
2281 fprintf(fp, "%d,%d,%d,%" PRId64, txb_w, txb_h, tx_type, rd);
2282 fprintf(fp, "\n");
2283 fclose(fp);
2284 }
2285 }
2286 #endif // COLLECT_TX_SIZE_DATA
2287
2288 // If the current best RD cost is much worse than the reference RD cost,
2289 // terminate early.
2290 if (cpi->sf.tx_sf.adaptive_txb_search_level) {
2291 if ((best_rd - (best_rd >> cpi->sf.tx_sf.adaptive_txb_search_level)) >
2292 ref_best_rd) {
2293 break;
2294 }
2295 }
2296
2297 // Terminate transform type search if the block has been quantized to
2298 // all zero.
2299 if (cpi->sf.tx_sf.tx_type_search.skip_tx_search && !best_eob) break;
2300 }
2301
2302 assert(best_rd != INT64_MAX);
2303
2304 best_rd_stats->skip_txfm = best_eob == 0;
2305 if (plane == 0) update_txk_array(xd, blk_row, blk_col, tx_size, best_tx_type);
2306 x->plane[plane].txb_entropy_ctx[block] = best_txb_ctx;
2307 x->plane[plane].eobs[block] = best_eob;
2308 skip_trellis = skip_trellis_based_on_satd[best_tx_type];
2309
2310 // Point dqcoeff to the quantized coefficients corresponding to the best
2311 // transform type, then we can skip transform and quantization, e.g. in the
2312 // final pixel domain distortion calculation and recon_intra().
2313 p->dqcoeff = best_dqcoeff;
2314
2315 if (calc_pixel_domain_distortion_final && best_eob) {
2316 best_rd_stats->dist = dist_block_px_domain(
2317 cpi, x, plane, plane_bsize, block, blk_row, blk_col, tx_size);
2318 best_rd_stats->sse = block_sse;
2319 }
2320
2321 // Intra mode needs decoded pixels such that the next transform block
2322 // can use them for prediction.
2323 recon_intra(cpi, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
2324 txb_ctx, skip_trellis, best_tx_type, 0, &rate_cost, best_eob);
2325 p->dqcoeff = orig_dqcoeff;
2326 }
2327
2328 // Pick transform type for a luma transform block of tx_size. Note this function
2329 // is used only for inter-predicted blocks.
tx_type_rd(const AV1_COMP * cpi,MACROBLOCK * x,TX_SIZE tx_size,int blk_row,int blk_col,int block,int plane_bsize,TXB_CTX * txb_ctx,RD_STATS * rd_stats,FAST_TX_SEARCH_MODE ftxs_mode,int64_t ref_rdcost)2330 static AOM_INLINE void tx_type_rd(const AV1_COMP *cpi, MACROBLOCK *x,
2331 TX_SIZE tx_size, int blk_row, int blk_col,
2332 int block, int plane_bsize, TXB_CTX *txb_ctx,
2333 RD_STATS *rd_stats,
2334 FAST_TX_SEARCH_MODE ftxs_mode,
2335 int64_t ref_rdcost) {
2336 assert(is_inter_block(x->e_mbd.mi[0]));
2337 RD_STATS this_rd_stats;
2338 const int skip_trellis = 0;
2339 search_tx_type(cpi, x, 0, block, blk_row, blk_col, plane_bsize, tx_size,
2340 txb_ctx, ftxs_mode, skip_trellis, ref_rdcost, &this_rd_stats);
2341
2342 av1_merge_rd_stats(rd_stats, &this_rd_stats);
2343 }
2344
try_tx_block_no_split(const AV1_COMP * cpi,MACROBLOCK * x,int blk_row,int blk_col,int block,TX_SIZE tx_size,int depth,BLOCK_SIZE plane_bsize,const ENTROPY_CONTEXT * ta,const ENTROPY_CONTEXT * tl,int txfm_partition_ctx,RD_STATS * rd_stats,int64_t ref_best_rd,FAST_TX_SEARCH_MODE ftxs_mode,TxCandidateInfo * no_split)2345 static AOM_INLINE void try_tx_block_no_split(
2346 const AV1_COMP *cpi, MACROBLOCK *x, int blk_row, int blk_col, int block,
2347 TX_SIZE tx_size, int depth, BLOCK_SIZE plane_bsize,
2348 const ENTROPY_CONTEXT *ta, const ENTROPY_CONTEXT *tl,
2349 int txfm_partition_ctx, RD_STATS *rd_stats, int64_t ref_best_rd,
2350 FAST_TX_SEARCH_MODE ftxs_mode, TxCandidateInfo *no_split) {
2351 MACROBLOCKD *const xd = &x->e_mbd;
2352 MB_MODE_INFO *const mbmi = xd->mi[0];
2353 struct macroblock_plane *const p = &x->plane[0];
2354 const int bw = mi_size_wide[plane_bsize];
2355 const ENTROPY_CONTEXT *const pta = ta + blk_col;
2356 const ENTROPY_CONTEXT *const ptl = tl + blk_row;
2357 const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
2358 TXB_CTX txb_ctx;
2359 get_txb_ctx(plane_bsize, tx_size, 0, pta, ptl, &txb_ctx);
2360 const int zero_blk_rate = x->coeff_costs.coeff_costs[txs_ctx][PLANE_TYPE_Y]
2361 .txb_skip_cost[txb_ctx.txb_skip_ctx][1];
2362 rd_stats->zero_rate = zero_blk_rate;
2363 const int index = av1_get_txb_size_index(plane_bsize, blk_row, blk_col);
2364 mbmi->inter_tx_size[index] = tx_size;
2365 tx_type_rd(cpi, x, tx_size, blk_row, blk_col, block, plane_bsize, &txb_ctx,
2366 rd_stats, ftxs_mode, ref_best_rd);
2367 assert(rd_stats->rate < INT_MAX);
2368
2369 const int pick_skip_txfm =
2370 !xd->lossless[mbmi->segment_id] &&
2371 (rd_stats->skip_txfm == 1 ||
2372 RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist) >=
2373 RDCOST(x->rdmult, zero_blk_rate, rd_stats->sse));
2374 if (pick_skip_txfm) {
2375 #if CONFIG_RD_DEBUG
2376 update_txb_coeff_cost(rd_stats, 0, zero_blk_rate - rd_stats->rate);
2377 #endif // CONFIG_RD_DEBUG
2378 rd_stats->rate = zero_blk_rate;
2379 rd_stats->dist = rd_stats->sse;
2380 p->eobs[block] = 0;
2381 update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
2382 }
2383 rd_stats->skip_txfm = pick_skip_txfm;
2384 set_blk_skip(x->txfm_search_info.blk_skip, 0, blk_row * bw + blk_col,
2385 pick_skip_txfm);
2386
2387 if (tx_size > TX_4X4 && depth < MAX_VARTX_DEPTH)
2388 rd_stats->rate += x->mode_costs.txfm_partition_cost[txfm_partition_ctx][0];
2389
2390 no_split->rd = RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist);
2391 no_split->txb_entropy_ctx = p->txb_entropy_ctx[block];
2392 no_split->tx_type =
2393 xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
2394 }
2395
try_tx_block_split(const AV1_COMP * cpi,MACROBLOCK * x,int blk_row,int blk_col,int block,TX_SIZE tx_size,int depth,BLOCK_SIZE plane_bsize,ENTROPY_CONTEXT * ta,ENTROPY_CONTEXT * tl,TXFM_CONTEXT * tx_above,TXFM_CONTEXT * tx_left,int txfm_partition_ctx,int64_t no_split_rd,int64_t ref_best_rd,FAST_TX_SEARCH_MODE ftxs_mode,RD_STATS * split_rd_stats)2396 static AOM_INLINE void try_tx_block_split(
2397 const AV1_COMP *cpi, MACROBLOCK *x, int blk_row, int blk_col, int block,
2398 TX_SIZE tx_size, int depth, BLOCK_SIZE plane_bsize, ENTROPY_CONTEXT *ta,
2399 ENTROPY_CONTEXT *tl, TXFM_CONTEXT *tx_above, TXFM_CONTEXT *tx_left,
2400 int txfm_partition_ctx, int64_t no_split_rd, int64_t ref_best_rd,
2401 FAST_TX_SEARCH_MODE ftxs_mode, RD_STATS *split_rd_stats) {
2402 assert(tx_size < TX_SIZES_ALL);
2403 MACROBLOCKD *const xd = &x->e_mbd;
2404 const int max_blocks_high = max_block_high(xd, plane_bsize, 0);
2405 const int max_blocks_wide = max_block_wide(xd, plane_bsize, 0);
2406 const int txb_width = tx_size_wide_unit[tx_size];
2407 const int txb_height = tx_size_high_unit[tx_size];
2408 // Transform size after splitting current block.
2409 const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
2410 const int sub_txb_width = tx_size_wide_unit[sub_txs];
2411 const int sub_txb_height = tx_size_high_unit[sub_txs];
2412 const int sub_step = sub_txb_width * sub_txb_height;
2413 const int nblks = (txb_height / sub_txb_height) * (txb_width / sub_txb_width);
2414 assert(nblks > 0);
2415 av1_init_rd_stats(split_rd_stats);
2416 split_rd_stats->rate =
2417 x->mode_costs.txfm_partition_cost[txfm_partition_ctx][1];
2418
2419 for (int r = 0, blk_idx = 0; r < txb_height; r += sub_txb_height) {
2420 const int offsetr = blk_row + r;
2421 if (offsetr >= max_blocks_high) break;
2422 for (int c = 0; c < txb_width; c += sub_txb_width, ++blk_idx) {
2423 assert(blk_idx < 4);
2424 const int offsetc = blk_col + c;
2425 if (offsetc >= max_blocks_wide) continue;
2426
2427 RD_STATS this_rd_stats;
2428 int this_cost_valid = 1;
2429 select_tx_block(cpi, x, offsetr, offsetc, block, sub_txs, depth + 1,
2430 plane_bsize, ta, tl, tx_above, tx_left, &this_rd_stats,
2431 no_split_rd / nblks, ref_best_rd - split_rd_stats->rdcost,
2432 &this_cost_valid, ftxs_mode);
2433 if (!this_cost_valid) {
2434 split_rd_stats->rdcost = INT64_MAX;
2435 return;
2436 }
2437 av1_merge_rd_stats(split_rd_stats, &this_rd_stats);
2438 split_rd_stats->rdcost =
2439 RDCOST(x->rdmult, split_rd_stats->rate, split_rd_stats->dist);
2440 if (split_rd_stats->rdcost > ref_best_rd) {
2441 split_rd_stats->rdcost = INT64_MAX;
2442 return;
2443 }
2444 block += sub_step;
2445 }
2446 }
2447 }
2448
get_var(float mean,double x2_sum,int num)2449 static float get_var(float mean, double x2_sum, int num) {
2450 const float e_x2 = (float)(x2_sum / num);
2451 const float diff = e_x2 - mean * mean;
2452 return diff;
2453 }
2454
get_blk_var_dev(const int16_t * data,int stride,int bw,int bh,float * dev_of_mean,float * var_of_vars)2455 static AOM_INLINE void get_blk_var_dev(const int16_t *data, int stride, int bw,
2456 int bh, float *dev_of_mean,
2457 float *var_of_vars) {
2458 const int16_t *const data_ptr = &data[0];
2459 const int subh = (bh >= bw) ? (bh >> 1) : bh;
2460 const int subw = (bw >= bh) ? (bw >> 1) : bw;
2461 const int num = bw * bh;
2462 const int sub_num = subw * subh;
2463 int total_x_sum = 0;
2464 int64_t total_x2_sum = 0;
2465 int blk_idx = 0;
2466 float var_sum = 0.0f;
2467 float mean_sum = 0.0f;
2468 double var2_sum = 0.0f;
2469 double mean2_sum = 0.0f;
2470
2471 for (int row = 0; row < bh; row += subh) {
2472 for (int col = 0; col < bw; col += subw) {
2473 int x_sum;
2474 int64_t x2_sum;
2475 aom_get_blk_sse_sum(data_ptr + row * stride + col, stride, subw, subh,
2476 &x_sum, &x2_sum);
2477 total_x_sum += x_sum;
2478 total_x2_sum += x2_sum;
2479
2480 const float mean = (float)x_sum / sub_num;
2481 const float var = get_var(mean, (double)x2_sum, sub_num);
2482 mean_sum += mean;
2483 mean2_sum += (double)(mean * mean);
2484 var_sum += var;
2485 var2_sum += var * var;
2486 blk_idx++;
2487 }
2488 }
2489
2490 const float lvl0_mean = (float)total_x_sum / num;
2491 const float block_var = get_var(lvl0_mean, (double)total_x2_sum, num);
2492 mean_sum += lvl0_mean;
2493 mean2_sum += (double)(lvl0_mean * lvl0_mean);
2494 var_sum += block_var;
2495 var2_sum += block_var * block_var;
2496 const float av_mean = mean_sum / 5;
2497
2498 if (blk_idx > 1) {
2499 // Deviation of means.
2500 *dev_of_mean = get_dev(av_mean, mean2_sum, (blk_idx + 1));
2501 // Variance of variances.
2502 const float mean_var = var_sum / (blk_idx + 1);
2503 *var_of_vars = get_var(mean_var, var2_sum, (blk_idx + 1));
2504 }
2505 }
2506
prune_tx_split_no_split(MACROBLOCK * x,BLOCK_SIZE bsize,int blk_row,int blk_col,TX_SIZE tx_size,int * try_no_split,int * try_split,int pruning_level)2507 static void prune_tx_split_no_split(MACROBLOCK *x, BLOCK_SIZE bsize,
2508 int blk_row, int blk_col, TX_SIZE tx_size,
2509 int *try_no_split, int *try_split,
2510 int pruning_level) {
2511 const int diff_stride = block_size_wide[bsize];
2512 const int16_t *diff =
2513 x->plane[0].src_diff + 4 * blk_row * diff_stride + 4 * blk_col;
2514 const int bw = tx_size_wide[tx_size];
2515 const int bh = tx_size_high[tx_size];
2516 float dev_of_means = 0.0f;
2517 float var_of_vars = 0.0f;
2518
2519 // This function calculates the deviation of means, and the variance of pixel
2520 // variances of the block as well as it's sub-blocks.
2521 get_blk_var_dev(diff, diff_stride, bw, bh, &dev_of_means, &var_of_vars);
2522 const int dc_q = x->plane[0].dequant_QTX[0] >> 3;
2523 const int ac_q = x->plane[0].dequant_QTX[1] >> 3;
2524 const int no_split_thresh_scales[4] = { 0, 24, 8, 8 };
2525 const int no_split_thresh_scale = no_split_thresh_scales[pruning_level];
2526 const int split_thresh_scales[4] = { 0, 24, 10, 8 };
2527 const int split_thresh_scale = split_thresh_scales[pruning_level];
2528
2529 if ((dev_of_means <= dc_q) &&
2530 (split_thresh_scale * var_of_vars <= ac_q * ac_q)) {
2531 *try_split = 0;
2532 }
2533 if ((dev_of_means > no_split_thresh_scale * dc_q) &&
2534 (var_of_vars > no_split_thresh_scale * ac_q * ac_q)) {
2535 *try_no_split = 0;
2536 }
2537 }
2538
2539 // Search for the best transform partition(recursive)/type for a given
2540 // inter-predicted luma block. The obtained transform selection will be saved
2541 // in xd->mi[0], the corresponding RD stats will be saved in rd_stats.
select_tx_block(const AV1_COMP * cpi,MACROBLOCK * x,int blk_row,int blk_col,int block,TX_SIZE tx_size,int depth,BLOCK_SIZE plane_bsize,ENTROPY_CONTEXT * ta,ENTROPY_CONTEXT * tl,TXFM_CONTEXT * tx_above,TXFM_CONTEXT * tx_left,RD_STATS * rd_stats,int64_t prev_level_rd,int64_t ref_best_rd,int * is_cost_valid,FAST_TX_SEARCH_MODE ftxs_mode)2542 static AOM_INLINE void select_tx_block(
2543 const AV1_COMP *cpi, MACROBLOCK *x, int blk_row, int blk_col, int block,
2544 TX_SIZE tx_size, int depth, BLOCK_SIZE plane_bsize, ENTROPY_CONTEXT *ta,
2545 ENTROPY_CONTEXT *tl, TXFM_CONTEXT *tx_above, TXFM_CONTEXT *tx_left,
2546 RD_STATS *rd_stats, int64_t prev_level_rd, int64_t ref_best_rd,
2547 int *is_cost_valid, FAST_TX_SEARCH_MODE ftxs_mode) {
2548 assert(tx_size < TX_SIZES_ALL);
2549 av1_init_rd_stats(rd_stats);
2550 if (ref_best_rd < 0) {
2551 *is_cost_valid = 0;
2552 return;
2553 }
2554
2555 MACROBLOCKD *const xd = &x->e_mbd;
2556 assert(blk_row < max_block_high(xd, plane_bsize, 0) &&
2557 blk_col < max_block_wide(xd, plane_bsize, 0));
2558 MB_MODE_INFO *const mbmi = xd->mi[0];
2559 const int ctx = txfm_partition_context(tx_above + blk_col, tx_left + blk_row,
2560 mbmi->bsize, tx_size);
2561 struct macroblock_plane *const p = &x->plane[0];
2562
2563 int try_no_split = (cpi->oxcf.txfm_cfg.enable_tx64 ||
2564 txsize_sqr_up_map[tx_size] != TX_64X64) &&
2565 (cpi->oxcf.txfm_cfg.enable_rect_tx ||
2566 tx_size_wide[tx_size] == tx_size_high[tx_size]);
2567 int try_split = tx_size > TX_4X4 && depth < MAX_VARTX_DEPTH;
2568 TxCandidateInfo no_split = { INT64_MAX, 0, TX_TYPES };
2569
2570 // Prune tx_split and no-split based on sub-block properties.
2571 if (tx_size != TX_4X4 && try_split == 1 && try_no_split == 1 &&
2572 cpi->sf.tx_sf.prune_tx_size_level > 0) {
2573 prune_tx_split_no_split(x, plane_bsize, blk_row, blk_col, tx_size,
2574 &try_no_split, &try_split,
2575 cpi->sf.tx_sf.prune_tx_size_level);
2576 }
2577
2578 if (cpi->sf.rt_sf.skip_tx_no_split_var_based_partition) {
2579 if (x->try_merge_partition && try_split && p->eobs[block]) try_no_split = 0;
2580 }
2581
2582 // Try using current block as a single transform block without split.
2583 if (try_no_split) {
2584 try_tx_block_no_split(cpi, x, blk_row, blk_col, block, tx_size, depth,
2585 plane_bsize, ta, tl, ctx, rd_stats, ref_best_rd,
2586 ftxs_mode, &no_split);
2587
2588 // Speed features for early termination.
2589 const int search_level = cpi->sf.tx_sf.adaptive_txb_search_level;
2590 if (search_level) {
2591 if ((no_split.rd - (no_split.rd >> (1 + search_level))) > ref_best_rd) {
2592 *is_cost_valid = 0;
2593 return;
2594 }
2595 if (no_split.rd - (no_split.rd >> (2 + search_level)) > prev_level_rd) {
2596 try_split = 0;
2597 }
2598 }
2599 if (cpi->sf.tx_sf.txb_split_cap) {
2600 if (p->eobs[block] == 0) try_split = 0;
2601 }
2602 }
2603
2604 // ML based speed feature to skip searching for split transform blocks.
2605 if (x->e_mbd.bd == 8 && try_split &&
2606 !(ref_best_rd == INT64_MAX && no_split.rd == INT64_MAX)) {
2607 const int threshold = cpi->sf.tx_sf.tx_type_search.ml_tx_split_thresh;
2608 if (threshold >= 0) {
2609 const int split_score =
2610 ml_predict_tx_split(x, plane_bsize, blk_row, blk_col, tx_size);
2611 if (split_score < -threshold) try_split = 0;
2612 }
2613 }
2614
2615 RD_STATS split_rd_stats;
2616 split_rd_stats.rdcost = INT64_MAX;
2617 // Try splitting current block into smaller transform blocks.
2618 if (try_split) {
2619 try_tx_block_split(cpi, x, blk_row, blk_col, block, tx_size, depth,
2620 plane_bsize, ta, tl, tx_above, tx_left, ctx, no_split.rd,
2621 AOMMIN(no_split.rd, ref_best_rd), ftxs_mode,
2622 &split_rd_stats);
2623 }
2624
2625 if (no_split.rd < split_rd_stats.rdcost) {
2626 ENTROPY_CONTEXT *pta = ta + blk_col;
2627 ENTROPY_CONTEXT *ptl = tl + blk_row;
2628 p->txb_entropy_ctx[block] = no_split.txb_entropy_ctx;
2629 av1_set_txb_context(x, 0, block, tx_size, pta, ptl);
2630 txfm_partition_update(tx_above + blk_col, tx_left + blk_row, tx_size,
2631 tx_size);
2632 for (int idy = 0; idy < tx_size_high_unit[tx_size]; ++idy) {
2633 for (int idx = 0; idx < tx_size_wide_unit[tx_size]; ++idx) {
2634 const int index =
2635 av1_get_txb_size_index(plane_bsize, blk_row + idy, blk_col + idx);
2636 mbmi->inter_tx_size[index] = tx_size;
2637 }
2638 }
2639 mbmi->tx_size = tx_size;
2640 update_txk_array(xd, blk_row, blk_col, tx_size, no_split.tx_type);
2641 const int bw = mi_size_wide[plane_bsize];
2642 set_blk_skip(x->txfm_search_info.blk_skip, 0, blk_row * bw + blk_col,
2643 rd_stats->skip_txfm);
2644 } else {
2645 *rd_stats = split_rd_stats;
2646 if (split_rd_stats.rdcost == INT64_MAX) *is_cost_valid = 0;
2647 }
2648 }
2649
choose_largest_tx_size(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,int64_t ref_best_rd,BLOCK_SIZE bs)2650 static AOM_INLINE void choose_largest_tx_size(const AV1_COMP *const cpi,
2651 MACROBLOCK *x, RD_STATS *rd_stats,
2652 int64_t ref_best_rd,
2653 BLOCK_SIZE bs) {
2654 MACROBLOCKD *const xd = &x->e_mbd;
2655 MB_MODE_INFO *const mbmi = xd->mi[0];
2656 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
2657 mbmi->tx_size = tx_size_from_tx_mode(bs, txfm_params->tx_mode_search_type);
2658
2659 // If tx64 is not enabled, we need to go down to the next available size
2660 if (!cpi->oxcf.txfm_cfg.enable_tx64 && cpi->oxcf.txfm_cfg.enable_rect_tx) {
2661 static const TX_SIZE tx_size_max_32[TX_SIZES_ALL] = {
2662 TX_4X4, // 4x4 transform
2663 TX_8X8, // 8x8 transform
2664 TX_16X16, // 16x16 transform
2665 TX_32X32, // 32x32 transform
2666 TX_32X32, // 64x64 transform
2667 TX_4X8, // 4x8 transform
2668 TX_8X4, // 8x4 transform
2669 TX_8X16, // 8x16 transform
2670 TX_16X8, // 16x8 transform
2671 TX_16X32, // 16x32 transform
2672 TX_32X16, // 32x16 transform
2673 TX_32X32, // 32x64 transform
2674 TX_32X32, // 64x32 transform
2675 TX_4X16, // 4x16 transform
2676 TX_16X4, // 16x4 transform
2677 TX_8X32, // 8x32 transform
2678 TX_32X8, // 32x8 transform
2679 TX_16X32, // 16x64 transform
2680 TX_32X16, // 64x16 transform
2681 };
2682 mbmi->tx_size = tx_size_max_32[mbmi->tx_size];
2683 } else if (cpi->oxcf.txfm_cfg.enable_tx64 &&
2684 !cpi->oxcf.txfm_cfg.enable_rect_tx) {
2685 static const TX_SIZE tx_size_max_square[TX_SIZES_ALL] = {
2686 TX_4X4, // 4x4 transform
2687 TX_8X8, // 8x8 transform
2688 TX_16X16, // 16x16 transform
2689 TX_32X32, // 32x32 transform
2690 TX_64X64, // 64x64 transform
2691 TX_4X4, // 4x8 transform
2692 TX_4X4, // 8x4 transform
2693 TX_8X8, // 8x16 transform
2694 TX_8X8, // 16x8 transform
2695 TX_16X16, // 16x32 transform
2696 TX_16X16, // 32x16 transform
2697 TX_32X32, // 32x64 transform
2698 TX_32X32, // 64x32 transform
2699 TX_4X4, // 4x16 transform
2700 TX_4X4, // 16x4 transform
2701 TX_8X8, // 8x32 transform
2702 TX_8X8, // 32x8 transform
2703 TX_16X16, // 16x64 transform
2704 TX_16X16, // 64x16 transform
2705 };
2706 mbmi->tx_size = tx_size_max_square[mbmi->tx_size];
2707 } else if (!cpi->oxcf.txfm_cfg.enable_tx64 &&
2708 !cpi->oxcf.txfm_cfg.enable_rect_tx) {
2709 static const TX_SIZE tx_size_max_32_square[TX_SIZES_ALL] = {
2710 TX_4X4, // 4x4 transform
2711 TX_8X8, // 8x8 transform
2712 TX_16X16, // 16x16 transform
2713 TX_32X32, // 32x32 transform
2714 TX_32X32, // 64x64 transform
2715 TX_4X4, // 4x8 transform
2716 TX_4X4, // 8x4 transform
2717 TX_8X8, // 8x16 transform
2718 TX_8X8, // 16x8 transform
2719 TX_16X16, // 16x32 transform
2720 TX_16X16, // 32x16 transform
2721 TX_32X32, // 32x64 transform
2722 TX_32X32, // 64x32 transform
2723 TX_4X4, // 4x16 transform
2724 TX_4X4, // 16x4 transform
2725 TX_8X8, // 8x32 transform
2726 TX_8X8, // 32x8 transform
2727 TX_16X16, // 16x64 transform
2728 TX_16X16, // 64x16 transform
2729 };
2730
2731 mbmi->tx_size = tx_size_max_32_square[mbmi->tx_size];
2732 }
2733
2734 const int skip_ctx = av1_get_skip_txfm_context(xd);
2735 const int no_skip_txfm_rate = x->mode_costs.skip_txfm_cost[skip_ctx][0];
2736 const int skip_txfm_rate = x->mode_costs.skip_txfm_cost[skip_ctx][1];
2737 // Skip RDcost is used only for Inter blocks
2738 const int64_t skip_txfm_rd =
2739 is_inter_block(mbmi) ? RDCOST(x->rdmult, skip_txfm_rate, 0) : INT64_MAX;
2740 const int64_t no_skip_txfm_rd = RDCOST(x->rdmult, no_skip_txfm_rate, 0);
2741 const int skip_trellis = 0;
2742 av1_txfm_rd_in_plane(x, cpi, rd_stats, ref_best_rd,
2743 AOMMIN(no_skip_txfm_rd, skip_txfm_rd), AOM_PLANE_Y, bs,
2744 mbmi->tx_size, FTXS_NONE, skip_trellis);
2745 }
2746
choose_smallest_tx_size(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,int64_t ref_best_rd,BLOCK_SIZE bs)2747 static AOM_INLINE void choose_smallest_tx_size(const AV1_COMP *const cpi,
2748 MACROBLOCK *x,
2749 RD_STATS *rd_stats,
2750 int64_t ref_best_rd,
2751 BLOCK_SIZE bs) {
2752 MACROBLOCKD *const xd = &x->e_mbd;
2753 MB_MODE_INFO *const mbmi = xd->mi[0];
2754
2755 mbmi->tx_size = TX_4X4;
2756 // TODO(any) : Pass this_rd based on skip/non-skip cost
2757 const int skip_trellis = 0;
2758 av1_txfm_rd_in_plane(x, cpi, rd_stats, ref_best_rd, 0, 0, bs, mbmi->tx_size,
2759 FTXS_NONE, skip_trellis);
2760 }
2761
2762 #if !CONFIG_REALTIME_ONLY
ml_predict_intra_tx_depth_prune(MACROBLOCK * x,int blk_row,int blk_col,BLOCK_SIZE bsize,TX_SIZE tx_size)2763 static void ml_predict_intra_tx_depth_prune(MACROBLOCK *x, int blk_row,
2764 int blk_col, BLOCK_SIZE bsize,
2765 TX_SIZE tx_size) {
2766 const MACROBLOCKD *const xd = &x->e_mbd;
2767 const MB_MODE_INFO *const mbmi = xd->mi[0];
2768
2769 // Disable the pruning logic using NN model for the following cases:
2770 // 1) Lossless coding as only 4x4 transform is evaluated in this case
2771 // 2) When transform and current block sizes do not match as the features are
2772 // obtained over the current block
2773 // 3) When operating bit-depth is not 8-bit as the input features are not
2774 // scaled according to bit-depth.
2775 if (xd->lossless[mbmi->segment_id] || txsize_to_bsize[tx_size] != bsize ||
2776 xd->bd != 8)
2777 return;
2778
2779 // Currently NN model based pruning is supported only when largest transform
2780 // size is 8x8
2781 if (tx_size != TX_8X8) return;
2782
2783 // Neural network model is a sequential neural net and was trained using SGD
2784 // optimizer. The model can be further improved in terms of speed/quality by
2785 // considering the following experiments:
2786 // 1) Generate ML model by training with balanced data for different learning
2787 // rates and optimizers.
2788 // 2) Experiment with ML model by adding features related to the statistics of
2789 // top and left pixels to capture the accuracy of reconstructed neighbouring
2790 // pixels for 4x4 blocks numbered 1, 2, 3 in 8x8 block, source variance of 4x4
2791 // sub-blocks, etc.
2792 // 3) Generate ML models for transform blocks other than 8x8.
2793 const NN_CONFIG *const nn_config = &av1_intra_tx_split_nnconfig_8x8;
2794 const float *const intra_tx_prune_thresh = av1_intra_tx_prune_nn_thresh_8x8;
2795
2796 float features[NUM_INTRA_TX_SPLIT_FEATURES] = { 0.0f };
2797 const int diff_stride = block_size_wide[bsize];
2798
2799 const int16_t *diff = x->plane[0].src_diff + MI_SIZE * blk_row * diff_stride +
2800 MI_SIZE * blk_col;
2801 const int bw = tx_size_wide[tx_size];
2802 const int bh = tx_size_high[tx_size];
2803
2804 int feature_idx = get_mean_dev_features(diff, diff_stride, bw, bh, features);
2805
2806 features[feature_idx++] = log1pf((float)x->source_variance);
2807
2808 const int dc_q = av1_dc_quant_QTX(x->qindex, 0, xd->bd) >> (xd->bd - 8);
2809 const float log_dc_q_square = log1pf((float)(dc_q * dc_q) / 256.0f);
2810 features[feature_idx++] = log_dc_q_square;
2811 assert(feature_idx == NUM_INTRA_TX_SPLIT_FEATURES);
2812 for (int i = 0; i < NUM_INTRA_TX_SPLIT_FEATURES; i++) {
2813 features[i] = (features[i] - av1_intra_tx_split_8x8_mean[i]) /
2814 av1_intra_tx_split_8x8_std[i];
2815 }
2816
2817 float score;
2818 av1_nn_predict(features, nn_config, 1, &score);
2819
2820 TxfmSearchParams *const txfm_params = &x->txfm_search_params;
2821 if (score <= intra_tx_prune_thresh[0])
2822 txfm_params->nn_prune_depths_for_intra_tx = TX_PRUNE_SPLIT;
2823 else if (score > intra_tx_prune_thresh[1])
2824 txfm_params->nn_prune_depths_for_intra_tx = TX_PRUNE_LARGEST;
2825 }
2826 #endif // !CONFIG_REALTIME_ONLY
2827
2828 // Search for the best uniform transform size and type for current coding block.
choose_tx_size_type_from_rd(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,int64_t ref_best_rd,BLOCK_SIZE bs)2829 static AOM_INLINE void choose_tx_size_type_from_rd(const AV1_COMP *const cpi,
2830 MACROBLOCK *x,
2831 RD_STATS *rd_stats,
2832 int64_t ref_best_rd,
2833 BLOCK_SIZE bs) {
2834 av1_invalid_rd_stats(rd_stats);
2835
2836 MACROBLOCKD *const xd = &x->e_mbd;
2837 MB_MODE_INFO *const mbmi = xd->mi[0];
2838 TxfmSearchParams *const txfm_params = &x->txfm_search_params;
2839 const TX_SIZE max_rect_tx_size = max_txsize_rect_lookup[bs];
2840 const int tx_select = txfm_params->tx_mode_search_type == TX_MODE_SELECT;
2841 int start_tx;
2842 // The split depth can be at most MAX_TX_DEPTH, so the init_depth controls
2843 // how many times of splitting is allowed during the RD search.
2844 int init_depth;
2845
2846 if (tx_select) {
2847 start_tx = max_rect_tx_size;
2848 init_depth = get_search_init_depth(mi_size_wide[bs], mi_size_high[bs],
2849 is_inter_block(mbmi), &cpi->sf,
2850 txfm_params->tx_size_search_method);
2851 if (init_depth == MAX_TX_DEPTH && !cpi->oxcf.txfm_cfg.enable_tx64 &&
2852 txsize_sqr_up_map[start_tx] == TX_64X64) {
2853 start_tx = sub_tx_size_map[start_tx];
2854 }
2855 } else {
2856 const TX_SIZE chosen_tx_size =
2857 tx_size_from_tx_mode(bs, txfm_params->tx_mode_search_type);
2858 start_tx = chosen_tx_size;
2859 init_depth = MAX_TX_DEPTH;
2860 }
2861
2862 const int skip_trellis = 0;
2863 uint8_t best_txk_type_map[MAX_MIB_SIZE * MAX_MIB_SIZE];
2864 uint8_t best_blk_skip[MAX_MIB_SIZE * MAX_MIB_SIZE];
2865 TX_SIZE best_tx_size = max_rect_tx_size;
2866 int64_t best_rd = INT64_MAX;
2867 const int num_blks = bsize_to_num_blk(bs);
2868 x->rd_model = FULL_TXFM_RD;
2869 int64_t rd[MAX_TX_DEPTH + 1] = { INT64_MAX, INT64_MAX, INT64_MAX };
2870 TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2871 for (int tx_size = start_tx, depth = init_depth; depth <= MAX_TX_DEPTH;
2872 depth++, tx_size = sub_tx_size_map[tx_size]) {
2873 if ((!cpi->oxcf.txfm_cfg.enable_tx64 &&
2874 txsize_sqr_up_map[tx_size] == TX_64X64) ||
2875 (!cpi->oxcf.txfm_cfg.enable_rect_tx &&
2876 tx_size_wide[tx_size] != tx_size_high[tx_size])) {
2877 continue;
2878 }
2879
2880 #if !CONFIG_REALTIME_ONLY
2881 if (txfm_params->nn_prune_depths_for_intra_tx == TX_PRUNE_SPLIT) break;
2882
2883 // Set the flag to enable the evaluation of NN classifier to prune transform
2884 // depths. As the features are based on intra residual information of
2885 // largest transform, the evaluation of NN model is enabled only for this
2886 // case.
2887 txfm_params->enable_nn_prune_intra_tx_depths =
2888 (cpi->sf.tx_sf.prune_intra_tx_depths_using_nn && tx_size == start_tx);
2889 #endif
2890
2891 RD_STATS this_rd_stats;
2892 // When the speed feature use_rd_based_breakout_for_intra_tx_search is
2893 // enabled, use the known minimum best_rd for early termination.
2894 const int64_t rd_thresh =
2895 cpi->sf.tx_sf.use_rd_based_breakout_for_intra_tx_search
2896 ? AOMMIN(ref_best_rd, best_rd)
2897 : ref_best_rd;
2898 rd[depth] = av1_uniform_txfm_yrd(cpi, x, &this_rd_stats, rd_thresh, bs,
2899 tx_size, FTXS_NONE, skip_trellis);
2900 if (rd[depth] < best_rd) {
2901 av1_copy_array(best_blk_skip, txfm_info->blk_skip, num_blks);
2902 av1_copy_array(best_txk_type_map, xd->tx_type_map, num_blks);
2903 best_tx_size = tx_size;
2904 best_rd = rd[depth];
2905 *rd_stats = this_rd_stats;
2906 }
2907 if (tx_size == TX_4X4) break;
2908 // If we are searching three depths, prune the smallest size depending
2909 // on rd results for the first two depths for low contrast blocks.
2910 if (depth > init_depth && depth != MAX_TX_DEPTH &&
2911 x->source_variance < 256) {
2912 if (rd[depth - 1] != INT64_MAX && rd[depth] > rd[depth - 1]) break;
2913 }
2914 }
2915
2916 if (rd_stats->rate != INT_MAX) {
2917 mbmi->tx_size = best_tx_size;
2918 av1_copy_array(xd->tx_type_map, best_txk_type_map, num_blks);
2919 av1_copy_array(txfm_info->blk_skip, best_blk_skip, num_blks);
2920 }
2921
2922 #if !CONFIG_REALTIME_ONLY
2923 // Reset the flags to avoid any unintentional evaluation of NN model and
2924 // consumption of prune depths.
2925 txfm_params->enable_nn_prune_intra_tx_depths = false;
2926 txfm_params->nn_prune_depths_for_intra_tx = TX_PRUNE_NONE;
2927 #endif
2928 }
2929
2930 // Search for the best transform type for the given transform block in the
2931 // given plane/channel, and calculate the corresponding RD cost.
block_rd_txfm(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)2932 static AOM_INLINE void block_rd_txfm(int plane, int block, int blk_row,
2933 int blk_col, BLOCK_SIZE plane_bsize,
2934 TX_SIZE tx_size, void *arg) {
2935 struct rdcost_block_args *args = arg;
2936 if (args->exit_early) {
2937 args->incomplete_exit = 1;
2938 return;
2939 }
2940
2941 MACROBLOCK *const x = args->x;
2942 MACROBLOCKD *const xd = &x->e_mbd;
2943 const int is_inter = is_inter_block(xd->mi[0]);
2944 const AV1_COMP *cpi = args->cpi;
2945 ENTROPY_CONTEXT *a = args->t_above + blk_col;
2946 ENTROPY_CONTEXT *l = args->t_left + blk_row;
2947 const AV1_COMMON *cm = &cpi->common;
2948 RD_STATS this_rd_stats;
2949 av1_init_rd_stats(&this_rd_stats);
2950
2951 if (!is_inter) {
2952 av1_predict_intra_block_facade(cm, xd, plane, blk_col, blk_row, tx_size);
2953 av1_subtract_txb(x, plane, plane_bsize, blk_col, blk_row, tx_size);
2954 #if !CONFIG_REALTIME_ONLY
2955 const TxfmSearchParams *const txfm_params = &x->txfm_search_params;
2956 if (txfm_params->enable_nn_prune_intra_tx_depths) {
2957 ml_predict_intra_tx_depth_prune(x, blk_row, blk_col, plane_bsize,
2958 tx_size);
2959 if (txfm_params->nn_prune_depths_for_intra_tx == TX_PRUNE_LARGEST) {
2960 av1_invalid_rd_stats(&args->rd_stats);
2961 args->exit_early = 1;
2962 return;
2963 }
2964 }
2965 #endif
2966 }
2967
2968 TXB_CTX txb_ctx;
2969 get_txb_ctx(plane_bsize, tx_size, plane, a, l, &txb_ctx);
2970 search_tx_type(cpi, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
2971 &txb_ctx, args->ftxs_mode, args->skip_trellis,
2972 args->best_rd - args->current_rd, &this_rd_stats);
2973
2974 if (plane == AOM_PLANE_Y && xd->cfl.store_y) {
2975 assert(!is_inter || plane_bsize < BLOCK_8X8);
2976 cfl_store_tx(xd, blk_row, blk_col, tx_size, plane_bsize);
2977 }
2978
2979 #if CONFIG_RD_DEBUG
2980 update_txb_coeff_cost(&this_rd_stats, plane, this_rd_stats.rate);
2981 #endif // CONFIG_RD_DEBUG
2982 av1_set_txb_context(x, plane, block, tx_size, a, l);
2983
2984 const int blk_idx =
2985 blk_row * (block_size_wide[plane_bsize] >> MI_SIZE_LOG2) + blk_col;
2986
2987 TxfmSearchInfo *txfm_info = &x->txfm_search_info;
2988 if (plane == 0)
2989 set_blk_skip(txfm_info->blk_skip, plane, blk_idx,
2990 x->plane[plane].eobs[block] == 0);
2991 else
2992 set_blk_skip(txfm_info->blk_skip, plane, blk_idx, 0);
2993
2994 int64_t rd;
2995 if (is_inter) {
2996 const int64_t no_skip_txfm_rd =
2997 RDCOST(x->rdmult, this_rd_stats.rate, this_rd_stats.dist);
2998 const int64_t skip_txfm_rd = RDCOST(x->rdmult, 0, this_rd_stats.sse);
2999 rd = AOMMIN(no_skip_txfm_rd, skip_txfm_rd);
3000 this_rd_stats.skip_txfm &= !x->plane[plane].eobs[block];
3001 } else {
3002 // Signal non-skip_txfm for Intra blocks
3003 rd = RDCOST(x->rdmult, this_rd_stats.rate, this_rd_stats.dist);
3004 this_rd_stats.skip_txfm = 0;
3005 }
3006
3007 av1_merge_rd_stats(&args->rd_stats, &this_rd_stats);
3008
3009 args->current_rd += rd;
3010 if (args->current_rd > args->best_rd) args->exit_early = 1;
3011 }
3012
av1_estimate_txfm_yrd(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,int64_t ref_best_rd,BLOCK_SIZE bs,TX_SIZE tx_size)3013 int64_t av1_estimate_txfm_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
3014 RD_STATS *rd_stats, int64_t ref_best_rd,
3015 BLOCK_SIZE bs, TX_SIZE tx_size) {
3016 MACROBLOCKD *const xd = &x->e_mbd;
3017 MB_MODE_INFO *const mbmi = xd->mi[0];
3018 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3019 const ModeCosts *mode_costs = &x->mode_costs;
3020 const int is_inter = is_inter_block(mbmi);
3021 const int tx_select = txfm_params->tx_mode_search_type == TX_MODE_SELECT &&
3022 block_signals_txsize(mbmi->bsize);
3023 int tx_size_rate = 0;
3024 if (tx_select) {
3025 const int ctx = txfm_partition_context(
3026 xd->above_txfm_context, xd->left_txfm_context, mbmi->bsize, tx_size);
3027 tx_size_rate = mode_costs->txfm_partition_cost[ctx][0];
3028 }
3029 const int skip_ctx = av1_get_skip_txfm_context(xd);
3030 const int no_skip_txfm_rate = mode_costs->skip_txfm_cost[skip_ctx][0];
3031 const int skip_txfm_rate = mode_costs->skip_txfm_cost[skip_ctx][1];
3032 const int64_t skip_txfm_rd = RDCOST(x->rdmult, skip_txfm_rate, 0);
3033 const int64_t no_this_rd =
3034 RDCOST(x->rdmult, no_skip_txfm_rate + tx_size_rate, 0);
3035 mbmi->tx_size = tx_size;
3036
3037 const uint8_t txw_unit = tx_size_wide_unit[tx_size];
3038 const uint8_t txh_unit = tx_size_high_unit[tx_size];
3039 const int step = txw_unit * txh_unit;
3040 const int max_blocks_wide = max_block_wide(xd, bs, 0);
3041 const int max_blocks_high = max_block_high(xd, bs, 0);
3042
3043 struct rdcost_block_args args;
3044 av1_zero(args);
3045 args.x = x;
3046 args.cpi = cpi;
3047 args.best_rd = ref_best_rd;
3048 args.current_rd = AOMMIN(no_this_rd, skip_txfm_rd);
3049 av1_init_rd_stats(&args.rd_stats);
3050 av1_get_entropy_contexts(bs, &xd->plane[0], args.t_above, args.t_left);
3051 int i = 0;
3052 for (int blk_row = 0; blk_row < max_blocks_high && !args.incomplete_exit;
3053 blk_row += txh_unit) {
3054 for (int blk_col = 0; blk_col < max_blocks_wide; blk_col += txw_unit) {
3055 RD_STATS this_rd_stats;
3056 av1_init_rd_stats(&this_rd_stats);
3057
3058 if (args.exit_early) {
3059 args.incomplete_exit = 1;
3060 break;
3061 }
3062
3063 ENTROPY_CONTEXT *a = args.t_above + blk_col;
3064 ENTROPY_CONTEXT *l = args.t_left + blk_row;
3065 TXB_CTX txb_ctx;
3066 get_txb_ctx(bs, tx_size, 0, a, l, &txb_ctx);
3067
3068 TxfmParam txfm_param;
3069 QUANT_PARAM quant_param;
3070 av1_setup_xform(&cpi->common, x, tx_size, DCT_DCT, &txfm_param);
3071 av1_setup_quant(tx_size, 0, AV1_XFORM_QUANT_B, 0, &quant_param);
3072
3073 av1_xform(x, 0, i, blk_row, blk_col, bs, &txfm_param);
3074 av1_quant(x, 0, i, &txfm_param, &quant_param);
3075
3076 this_rd_stats.rate =
3077 cost_coeffs(x, 0, i, tx_size, txfm_param.tx_type, &txb_ctx, 0);
3078
3079 const SCAN_ORDER *const scan_order =
3080 get_scan(txfm_param.tx_size, txfm_param.tx_type);
3081 dist_block_tx_domain(x, 0, i, tx_size, quant_param.qmatrix,
3082 scan_order->scan, &this_rd_stats.dist,
3083 &this_rd_stats.sse);
3084
3085 const int64_t no_skip_txfm_rd =
3086 RDCOST(x->rdmult, this_rd_stats.rate, this_rd_stats.dist);
3087 const int64_t skip_rd = RDCOST(x->rdmult, 0, this_rd_stats.sse);
3088
3089 this_rd_stats.skip_txfm &= !x->plane[0].eobs[i];
3090
3091 av1_merge_rd_stats(&args.rd_stats, &this_rd_stats);
3092 args.current_rd += AOMMIN(no_skip_txfm_rd, skip_rd);
3093
3094 if (args.current_rd > ref_best_rd) {
3095 args.exit_early = 1;
3096 break;
3097 }
3098
3099 av1_set_txb_context(x, 0, i, tx_size, a, l);
3100 i += step;
3101 }
3102 }
3103
3104 if (args.incomplete_exit) av1_invalid_rd_stats(&args.rd_stats);
3105
3106 *rd_stats = args.rd_stats;
3107 if (rd_stats->rate == INT_MAX) return INT64_MAX;
3108
3109 int64_t rd;
3110 // rdstats->rate should include all the rate except skip/non-skip cost as the
3111 // same is accounted in the caller functions after rd evaluation of all
3112 // planes. However the decisions should be done after considering the
3113 // skip/non-skip header cost
3114 if (rd_stats->skip_txfm && is_inter) {
3115 rd = RDCOST(x->rdmult, skip_txfm_rate, rd_stats->sse);
3116 } else {
3117 // Intra blocks are always signalled as non-skip
3118 rd = RDCOST(x->rdmult, rd_stats->rate + no_skip_txfm_rate + tx_size_rate,
3119 rd_stats->dist);
3120 rd_stats->rate += tx_size_rate;
3121 }
3122 // Check if forcing the block to skip transform leads to smaller RD cost.
3123 if (is_inter && !rd_stats->skip_txfm && !xd->lossless[mbmi->segment_id]) {
3124 int64_t temp_skip_txfm_rd =
3125 RDCOST(x->rdmult, skip_txfm_rate, rd_stats->sse);
3126 if (temp_skip_txfm_rd <= rd) {
3127 rd = temp_skip_txfm_rd;
3128 rd_stats->rate = 0;
3129 rd_stats->dist = rd_stats->sse;
3130 rd_stats->skip_txfm = 1;
3131 }
3132 }
3133
3134 return rd;
3135 }
3136
av1_uniform_txfm_yrd(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,int64_t ref_best_rd,BLOCK_SIZE bs,TX_SIZE tx_size,FAST_TX_SEARCH_MODE ftxs_mode,int skip_trellis)3137 int64_t av1_uniform_txfm_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
3138 RD_STATS *rd_stats, int64_t ref_best_rd,
3139 BLOCK_SIZE bs, TX_SIZE tx_size,
3140 FAST_TX_SEARCH_MODE ftxs_mode, int skip_trellis) {
3141 assert(IMPLIES(is_rect_tx(tx_size), is_rect_tx_allowed_bsize(bs)));
3142 MACROBLOCKD *const xd = &x->e_mbd;
3143 MB_MODE_INFO *const mbmi = xd->mi[0];
3144 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3145 const ModeCosts *mode_costs = &x->mode_costs;
3146 const int is_inter = is_inter_block(mbmi);
3147 const int tx_select = txfm_params->tx_mode_search_type == TX_MODE_SELECT &&
3148 block_signals_txsize(mbmi->bsize);
3149 int tx_size_rate = 0;
3150 if (tx_select) {
3151 const int ctx = txfm_partition_context(
3152 xd->above_txfm_context, xd->left_txfm_context, mbmi->bsize, tx_size);
3153 tx_size_rate = is_inter ? mode_costs->txfm_partition_cost[ctx][0]
3154 : tx_size_cost(x, bs, tx_size);
3155 }
3156 const int skip_ctx = av1_get_skip_txfm_context(xd);
3157 const int no_skip_txfm_rate = mode_costs->skip_txfm_cost[skip_ctx][0];
3158 const int skip_txfm_rate = mode_costs->skip_txfm_cost[skip_ctx][1];
3159 const int64_t skip_txfm_rd =
3160 is_inter ? RDCOST(x->rdmult, skip_txfm_rate, 0) : INT64_MAX;
3161 const int64_t no_this_rd =
3162 RDCOST(x->rdmult, no_skip_txfm_rate + tx_size_rate, 0);
3163
3164 mbmi->tx_size = tx_size;
3165 av1_txfm_rd_in_plane(x, cpi, rd_stats, ref_best_rd,
3166 AOMMIN(no_this_rd, skip_txfm_rd), AOM_PLANE_Y, bs,
3167 tx_size, ftxs_mode, skip_trellis);
3168 if (rd_stats->rate == INT_MAX) return INT64_MAX;
3169
3170 int64_t rd;
3171 // rdstats->rate should include all the rate except skip/non-skip cost as the
3172 // same is accounted in the caller functions after rd evaluation of all
3173 // planes. However the decisions should be done after considering the
3174 // skip/non-skip header cost
3175 if (rd_stats->skip_txfm && is_inter) {
3176 rd = RDCOST(x->rdmult, skip_txfm_rate, rd_stats->sse);
3177 } else {
3178 // Intra blocks are always signalled as non-skip
3179 rd = RDCOST(x->rdmult, rd_stats->rate + no_skip_txfm_rate + tx_size_rate,
3180 rd_stats->dist);
3181 rd_stats->rate += tx_size_rate;
3182 }
3183 // Check if forcing the block to skip transform leads to smaller RD cost.
3184 if (is_inter && !rd_stats->skip_txfm && !xd->lossless[mbmi->segment_id]) {
3185 int64_t temp_skip_txfm_rd =
3186 RDCOST(x->rdmult, skip_txfm_rate, rd_stats->sse);
3187 if (temp_skip_txfm_rd <= rd) {
3188 rd = temp_skip_txfm_rd;
3189 rd_stats->rate = 0;
3190 rd_stats->dist = rd_stats->sse;
3191 rd_stats->skip_txfm = 1;
3192 }
3193 }
3194
3195 return rd;
3196 }
3197
3198 // Search for the best transform type for a luma inter-predicted block, given
3199 // the transform block partitions.
3200 // This function is used only when some speed features are enabled.
tx_block_yrd(const AV1_COMP * cpi,MACROBLOCK * x,int blk_row,int blk_col,int block,TX_SIZE tx_size,BLOCK_SIZE plane_bsize,int depth,ENTROPY_CONTEXT * above_ctx,ENTROPY_CONTEXT * left_ctx,TXFM_CONTEXT * tx_above,TXFM_CONTEXT * tx_left,int64_t ref_best_rd,RD_STATS * rd_stats,FAST_TX_SEARCH_MODE ftxs_mode)3201 static AOM_INLINE void tx_block_yrd(
3202 const AV1_COMP *cpi, MACROBLOCK *x, int blk_row, int blk_col, int block,
3203 TX_SIZE tx_size, BLOCK_SIZE plane_bsize, int depth,
3204 ENTROPY_CONTEXT *above_ctx, ENTROPY_CONTEXT *left_ctx,
3205 TXFM_CONTEXT *tx_above, TXFM_CONTEXT *tx_left, int64_t ref_best_rd,
3206 RD_STATS *rd_stats, FAST_TX_SEARCH_MODE ftxs_mode) {
3207 assert(tx_size < TX_SIZES_ALL);
3208 MACROBLOCKD *const xd = &x->e_mbd;
3209 MB_MODE_INFO *const mbmi = xd->mi[0];
3210 assert(is_inter_block(mbmi));
3211 const int max_blocks_high = max_block_high(xd, plane_bsize, 0);
3212 const int max_blocks_wide = max_block_wide(xd, plane_bsize, 0);
3213
3214 if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
3215
3216 const TX_SIZE plane_tx_size = mbmi->inter_tx_size[av1_get_txb_size_index(
3217 plane_bsize, blk_row, blk_col)];
3218 const int ctx = txfm_partition_context(tx_above + blk_col, tx_left + blk_row,
3219 mbmi->bsize, tx_size);
3220
3221 av1_init_rd_stats(rd_stats);
3222 if (tx_size == plane_tx_size) {
3223 ENTROPY_CONTEXT *ta = above_ctx + blk_col;
3224 ENTROPY_CONTEXT *tl = left_ctx + blk_row;
3225 const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
3226 TXB_CTX txb_ctx;
3227 get_txb_ctx(plane_bsize, tx_size, 0, ta, tl, &txb_ctx);
3228
3229 const int zero_blk_rate =
3230 x->coeff_costs.coeff_costs[txs_ctx][get_plane_type(0)]
3231 .txb_skip_cost[txb_ctx.txb_skip_ctx][1];
3232 rd_stats->zero_rate = zero_blk_rate;
3233 tx_type_rd(cpi, x, tx_size, blk_row, blk_col, block, plane_bsize, &txb_ctx,
3234 rd_stats, ftxs_mode, ref_best_rd);
3235 const int mi_width = mi_size_wide[plane_bsize];
3236 TxfmSearchInfo *txfm_info = &x->txfm_search_info;
3237 if (RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist) >=
3238 RDCOST(x->rdmult, zero_blk_rate, rd_stats->sse) ||
3239 rd_stats->skip_txfm == 1) {
3240 rd_stats->rate = zero_blk_rate;
3241 rd_stats->dist = rd_stats->sse;
3242 rd_stats->skip_txfm = 1;
3243 set_blk_skip(txfm_info->blk_skip, 0, blk_row * mi_width + blk_col, 1);
3244 x->plane[0].eobs[block] = 0;
3245 x->plane[0].txb_entropy_ctx[block] = 0;
3246 update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
3247 } else {
3248 rd_stats->skip_txfm = 0;
3249 set_blk_skip(txfm_info->blk_skip, 0, blk_row * mi_width + blk_col, 0);
3250 }
3251 if (tx_size > TX_4X4 && depth < MAX_VARTX_DEPTH)
3252 rd_stats->rate += x->mode_costs.txfm_partition_cost[ctx][0];
3253 av1_set_txb_context(x, 0, block, tx_size, ta, tl);
3254 txfm_partition_update(tx_above + blk_col, tx_left + blk_row, tx_size,
3255 tx_size);
3256 } else {
3257 const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
3258 const int txb_width = tx_size_wide_unit[sub_txs];
3259 const int txb_height = tx_size_high_unit[sub_txs];
3260 const int step = txb_height * txb_width;
3261 const int row_end =
3262 AOMMIN(tx_size_high_unit[tx_size], max_blocks_high - blk_row);
3263 const int col_end =
3264 AOMMIN(tx_size_wide_unit[tx_size], max_blocks_wide - blk_col);
3265 RD_STATS pn_rd_stats;
3266 int64_t this_rd = 0;
3267 assert(txb_width > 0 && txb_height > 0);
3268
3269 for (int row = 0; row < row_end; row += txb_height) {
3270 const int offsetr = blk_row + row;
3271 for (int col = 0; col < col_end; col += txb_width) {
3272 const int offsetc = blk_col + col;
3273
3274 av1_init_rd_stats(&pn_rd_stats);
3275 tx_block_yrd(cpi, x, offsetr, offsetc, block, sub_txs, plane_bsize,
3276 depth + 1, above_ctx, left_ctx, tx_above, tx_left,
3277 ref_best_rd - this_rd, &pn_rd_stats, ftxs_mode);
3278 if (pn_rd_stats.rate == INT_MAX) {
3279 av1_invalid_rd_stats(rd_stats);
3280 return;
3281 }
3282 av1_merge_rd_stats(rd_stats, &pn_rd_stats);
3283 this_rd += RDCOST(x->rdmult, pn_rd_stats.rate, pn_rd_stats.dist);
3284 block += step;
3285 }
3286 }
3287
3288 if (tx_size > TX_4X4 && depth < MAX_VARTX_DEPTH)
3289 rd_stats->rate += x->mode_costs.txfm_partition_cost[ctx][1];
3290 }
3291 }
3292
3293 // search for tx type with tx sizes already decided for a inter-predicted luma
3294 // partition block. It's used only when some speed features are enabled.
3295 // Return value 0: early termination triggered, no valid rd cost available;
3296 // 1: rd cost values are valid.
inter_block_yrd(const AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bsize,int64_t ref_best_rd,FAST_TX_SEARCH_MODE ftxs_mode)3297 static int inter_block_yrd(const AV1_COMP *cpi, MACROBLOCK *x,
3298 RD_STATS *rd_stats, BLOCK_SIZE bsize,
3299 int64_t ref_best_rd, FAST_TX_SEARCH_MODE ftxs_mode) {
3300 if (ref_best_rd < 0) {
3301 av1_invalid_rd_stats(rd_stats);
3302 return 0;
3303 }
3304
3305 av1_init_rd_stats(rd_stats);
3306
3307 MACROBLOCKD *const xd = &x->e_mbd;
3308 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3309 const struct macroblockd_plane *const pd = &xd->plane[0];
3310 const int mi_width = mi_size_wide[bsize];
3311 const int mi_height = mi_size_high[bsize];
3312 const TX_SIZE max_tx_size = get_vartx_max_txsize(xd, bsize, 0);
3313 const int bh = tx_size_high_unit[max_tx_size];
3314 const int bw = tx_size_wide_unit[max_tx_size];
3315 const int step = bw * bh;
3316 const int init_depth = get_search_init_depth(
3317 mi_width, mi_height, 1, &cpi->sf, txfm_params->tx_size_search_method);
3318 ENTROPY_CONTEXT ctxa[MAX_MIB_SIZE];
3319 ENTROPY_CONTEXT ctxl[MAX_MIB_SIZE];
3320 TXFM_CONTEXT tx_above[MAX_MIB_SIZE];
3321 TXFM_CONTEXT tx_left[MAX_MIB_SIZE];
3322 av1_get_entropy_contexts(bsize, pd, ctxa, ctxl);
3323 memcpy(tx_above, xd->above_txfm_context, sizeof(TXFM_CONTEXT) * mi_width);
3324 memcpy(tx_left, xd->left_txfm_context, sizeof(TXFM_CONTEXT) * mi_height);
3325
3326 int64_t this_rd = 0;
3327 for (int idy = 0, block = 0; idy < mi_height; idy += bh) {
3328 for (int idx = 0; idx < mi_width; idx += bw) {
3329 RD_STATS pn_rd_stats;
3330 av1_init_rd_stats(&pn_rd_stats);
3331 tx_block_yrd(cpi, x, idy, idx, block, max_tx_size, bsize, init_depth,
3332 ctxa, ctxl, tx_above, tx_left, ref_best_rd - this_rd,
3333 &pn_rd_stats, ftxs_mode);
3334 if (pn_rd_stats.rate == INT_MAX) {
3335 av1_invalid_rd_stats(rd_stats);
3336 return 0;
3337 }
3338 av1_merge_rd_stats(rd_stats, &pn_rd_stats);
3339 this_rd +=
3340 AOMMIN(RDCOST(x->rdmult, pn_rd_stats.rate, pn_rd_stats.dist),
3341 RDCOST(x->rdmult, pn_rd_stats.zero_rate, pn_rd_stats.sse));
3342 block += step;
3343 }
3344 }
3345
3346 const int skip_ctx = av1_get_skip_txfm_context(xd);
3347 const int no_skip_txfm_rate = x->mode_costs.skip_txfm_cost[skip_ctx][0];
3348 const int skip_txfm_rate = x->mode_costs.skip_txfm_cost[skip_ctx][1];
3349 const int64_t skip_txfm_rd = RDCOST(x->rdmult, skip_txfm_rate, rd_stats->sse);
3350 this_rd =
3351 RDCOST(x->rdmult, rd_stats->rate + no_skip_txfm_rate, rd_stats->dist);
3352 if (skip_txfm_rd < this_rd) {
3353 this_rd = skip_txfm_rd;
3354 rd_stats->rate = 0;
3355 rd_stats->dist = rd_stats->sse;
3356 rd_stats->skip_txfm = 1;
3357 }
3358
3359 const int is_cost_valid = this_rd > ref_best_rd;
3360 if (!is_cost_valid) {
3361 // reset cost value
3362 av1_invalid_rd_stats(rd_stats);
3363 }
3364 return is_cost_valid;
3365 }
3366
3367 // Search for the best transform size and type for current inter-predicted
3368 // luma block with recursive transform block partitioning. The obtained
3369 // transform selection will be saved in xd->mi[0], the corresponding RD stats
3370 // will be saved in rd_stats. The returned value is the corresponding RD cost.
select_tx_size_and_type(const AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bsize,int64_t ref_best_rd)3371 static int64_t select_tx_size_and_type(const AV1_COMP *cpi, MACROBLOCK *x,
3372 RD_STATS *rd_stats, BLOCK_SIZE bsize,
3373 int64_t ref_best_rd) {
3374 MACROBLOCKD *const xd = &x->e_mbd;
3375 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3376 assert(is_inter_block(xd->mi[0]));
3377 assert(bsize < BLOCK_SIZES_ALL);
3378 const int fast_tx_search = txfm_params->tx_size_search_method > USE_FULL_RD;
3379 int64_t rd_thresh = ref_best_rd;
3380 if (rd_thresh == 0) {
3381 av1_invalid_rd_stats(rd_stats);
3382 return INT64_MAX;
3383 }
3384 if (fast_tx_search && rd_thresh < INT64_MAX) {
3385 if (INT64_MAX - rd_thresh > (rd_thresh >> 3)) rd_thresh += (rd_thresh >> 3);
3386 }
3387 assert(rd_thresh > 0);
3388 const FAST_TX_SEARCH_MODE ftxs_mode =
3389 fast_tx_search ? FTXS_DCT_AND_1D_DCT_ONLY : FTXS_NONE;
3390 const struct macroblockd_plane *const pd = &xd->plane[0];
3391 assert(bsize < BLOCK_SIZES_ALL);
3392 const int mi_width = mi_size_wide[bsize];
3393 const int mi_height = mi_size_high[bsize];
3394 ENTROPY_CONTEXT ctxa[MAX_MIB_SIZE];
3395 ENTROPY_CONTEXT ctxl[MAX_MIB_SIZE];
3396 TXFM_CONTEXT tx_above[MAX_MIB_SIZE];
3397 TXFM_CONTEXT tx_left[MAX_MIB_SIZE];
3398 av1_get_entropy_contexts(bsize, pd, ctxa, ctxl);
3399 memcpy(tx_above, xd->above_txfm_context, sizeof(TXFM_CONTEXT) * mi_width);
3400 memcpy(tx_left, xd->left_txfm_context, sizeof(TXFM_CONTEXT) * mi_height);
3401 const int init_depth = get_search_init_depth(
3402 mi_width, mi_height, 1, &cpi->sf, txfm_params->tx_size_search_method);
3403 const TX_SIZE max_tx_size = max_txsize_rect_lookup[bsize];
3404 const int bh = tx_size_high_unit[max_tx_size];
3405 const int bw = tx_size_wide_unit[max_tx_size];
3406 const int step = bw * bh;
3407 const int skip_ctx = av1_get_skip_txfm_context(xd);
3408 const int no_skip_txfm_cost = x->mode_costs.skip_txfm_cost[skip_ctx][0];
3409 const int skip_txfm_cost = x->mode_costs.skip_txfm_cost[skip_ctx][1];
3410 int64_t skip_txfm_rd = RDCOST(x->rdmult, skip_txfm_cost, 0);
3411 int64_t no_skip_txfm_rd = RDCOST(x->rdmult, no_skip_txfm_cost, 0);
3412 int block = 0;
3413
3414 av1_init_rd_stats(rd_stats);
3415 for (int idy = 0; idy < max_block_high(xd, bsize, 0); idy += bh) {
3416 for (int idx = 0; idx < max_block_wide(xd, bsize, 0); idx += bw) {
3417 const int64_t best_rd_sofar =
3418 (rd_thresh == INT64_MAX)
3419 ? INT64_MAX
3420 : (rd_thresh - (AOMMIN(skip_txfm_rd, no_skip_txfm_rd)));
3421 int is_cost_valid = 1;
3422 RD_STATS pn_rd_stats;
3423 // Search for the best transform block size and type for the sub-block.
3424 select_tx_block(cpi, x, idy, idx, block, max_tx_size, init_depth, bsize,
3425 ctxa, ctxl, tx_above, tx_left, &pn_rd_stats, INT64_MAX,
3426 best_rd_sofar, &is_cost_valid, ftxs_mode);
3427 if (!is_cost_valid || pn_rd_stats.rate == INT_MAX) {
3428 av1_invalid_rd_stats(rd_stats);
3429 return INT64_MAX;
3430 }
3431 av1_merge_rd_stats(rd_stats, &pn_rd_stats);
3432 skip_txfm_rd = RDCOST(x->rdmult, skip_txfm_cost, rd_stats->sse);
3433 no_skip_txfm_rd =
3434 RDCOST(x->rdmult, rd_stats->rate + no_skip_txfm_cost, rd_stats->dist);
3435 block += step;
3436 }
3437 }
3438
3439 if (rd_stats->rate == INT_MAX) return INT64_MAX;
3440
3441 rd_stats->skip_txfm = (skip_txfm_rd <= no_skip_txfm_rd);
3442
3443 // If fast_tx_search is true, only DCT and 1D DCT were tested in
3444 // select_inter_block_yrd() above. Do a better search for tx type with
3445 // tx sizes already decided.
3446 if (fast_tx_search && cpi->sf.tx_sf.refine_fast_tx_search_results) {
3447 if (!inter_block_yrd(cpi, x, rd_stats, bsize, ref_best_rd, FTXS_NONE))
3448 return INT64_MAX;
3449 }
3450
3451 int64_t final_rd;
3452 if (rd_stats->skip_txfm) {
3453 final_rd = RDCOST(x->rdmult, skip_txfm_cost, rd_stats->sse);
3454 } else {
3455 final_rd =
3456 RDCOST(x->rdmult, rd_stats->rate + no_skip_txfm_cost, rd_stats->dist);
3457 if (!xd->lossless[xd->mi[0]->segment_id]) {
3458 final_rd =
3459 AOMMIN(final_rd, RDCOST(x->rdmult, skip_txfm_cost, rd_stats->sse));
3460 }
3461 }
3462
3463 return final_rd;
3464 }
3465
3466 // Return 1 to terminate transform search early. The decision is made based on
3467 // the comparison with the reference RD cost and the model-estimated RD cost.
model_based_tx_search_prune(const AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int64_t ref_best_rd)3468 static AOM_INLINE int model_based_tx_search_prune(const AV1_COMP *cpi,
3469 MACROBLOCK *x,
3470 BLOCK_SIZE bsize,
3471 int64_t ref_best_rd) {
3472 const int level = cpi->sf.tx_sf.model_based_prune_tx_search_level;
3473 assert(level >= 0 && level <= 2);
3474 int model_rate;
3475 int64_t model_dist;
3476 uint8_t model_skip;
3477 MACROBLOCKD *const xd = &x->e_mbd;
3478 model_rd_sb_fn[MODELRD_TYPE_TX_SEARCH_PRUNE](
3479 cpi, bsize, x, xd, 0, 0, &model_rate, &model_dist, &model_skip, NULL,
3480 NULL, NULL, NULL);
3481 if (model_skip) return 0;
3482 const int64_t model_rd = RDCOST(x->rdmult, model_rate, model_dist);
3483 // TODO(debargha, urvang): Improve the model and make the check below
3484 // tighter.
3485 static const int prune_factor_by8[] = { 3, 5 };
3486 const int factor = prune_factor_by8[level - 1];
3487 return ((model_rd * factor) >> 3) > ref_best_rd;
3488 }
3489
av1_pick_recursive_tx_size_type_yrd(const AV1_COMP * cpi,MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bsize,int64_t ref_best_rd)3490 void av1_pick_recursive_tx_size_type_yrd(const AV1_COMP *cpi, MACROBLOCK *x,
3491 RD_STATS *rd_stats, BLOCK_SIZE bsize,
3492 int64_t ref_best_rd) {
3493 MACROBLOCKD *const xd = &x->e_mbd;
3494 const TxfmSearchParams *txfm_params = &x->txfm_search_params;
3495 assert(is_inter_block(xd->mi[0]));
3496
3497 av1_invalid_rd_stats(rd_stats);
3498
3499 // If modeled RD cost is a lot worse than the best so far, terminate early.
3500 if (cpi->sf.tx_sf.model_based_prune_tx_search_level &&
3501 ref_best_rd != INT64_MAX) {
3502 if (model_based_tx_search_prune(cpi, x, bsize, ref_best_rd)) return;
3503 }
3504
3505 // Hashing based speed feature. If the hash of the prediction residue block is
3506 // found in the hash table, use previous search results and terminate early.
3507 uint32_t hash = 0;
3508 MB_RD_RECORD *mb_rd_record = NULL;
3509 const int mi_row = x->e_mbd.mi_row;
3510 const int mi_col = x->e_mbd.mi_col;
3511 const int within_border =
3512 mi_row >= xd->tile.mi_row_start &&
3513 (mi_row + mi_size_high[bsize] < xd->tile.mi_row_end) &&
3514 mi_col >= xd->tile.mi_col_start &&
3515 (mi_col + mi_size_wide[bsize] < xd->tile.mi_col_end);
3516 const int is_mb_rd_hash_enabled =
3517 (within_border && cpi->sf.rd_sf.use_mb_rd_hash);
3518 const int n4 = bsize_to_num_blk(bsize);
3519 if (is_mb_rd_hash_enabled) {
3520 hash = get_block_residue_hash(x, bsize);
3521 mb_rd_record = x->txfm_search_info.mb_rd_record;
3522 const int match_index = find_mb_rd_info(mb_rd_record, ref_best_rd, hash);
3523 if (match_index != -1) {
3524 MB_RD_INFO *mb_rd_info = &mb_rd_record->mb_rd_info[match_index];
3525 fetch_mb_rd_info(n4, mb_rd_info, rd_stats, x);
3526 return;
3527 }
3528 }
3529
3530 // If we predict that skip is the optimal RD decision - set the respective
3531 // context and terminate early.
3532 int64_t dist;
3533 if (txfm_params->skip_txfm_level &&
3534 predict_skip_txfm(x, bsize, &dist,
3535 cpi->common.features.reduced_tx_set_used)) {
3536 set_skip_txfm(x, rd_stats, bsize, dist);
3537 // Save the RD search results into mb_rd_record.
3538 if (is_mb_rd_hash_enabled)
3539 save_mb_rd_info(n4, hash, x, rd_stats, mb_rd_record);
3540 return;
3541 }
3542 #if CONFIG_SPEED_STATS
3543 ++x->txfm_search_info.tx_search_count;
3544 #endif // CONFIG_SPEED_STATS
3545
3546 const int64_t rd =
3547 select_tx_size_and_type(cpi, x, rd_stats, bsize, ref_best_rd);
3548
3549 if (rd == INT64_MAX) {
3550 // We should always find at least one candidate unless ref_best_rd is less
3551 // than INT64_MAX (in which case, all the calls to select_tx_size_fix_type
3552 // might have failed to find something better)
3553 assert(ref_best_rd != INT64_MAX);
3554 av1_invalid_rd_stats(rd_stats);
3555 return;
3556 }
3557
3558 // Save the RD search results into mb_rd_record.
3559 if (is_mb_rd_hash_enabled) {
3560 assert(mb_rd_record != NULL);
3561 save_mb_rd_info(n4, hash, x, rd_stats, mb_rd_record);
3562 }
3563 }
3564
av1_pick_uniform_tx_size_type_yrd(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bs,int64_t ref_best_rd)3565 void av1_pick_uniform_tx_size_type_yrd(const AV1_COMP *const cpi, MACROBLOCK *x,
3566 RD_STATS *rd_stats, BLOCK_SIZE bs,
3567 int64_t ref_best_rd) {
3568 MACROBLOCKD *const xd = &x->e_mbd;
3569 MB_MODE_INFO *const mbmi = xd->mi[0];
3570 const TxfmSearchParams *tx_params = &x->txfm_search_params;
3571 assert(bs == mbmi->bsize);
3572 const int is_inter = is_inter_block(mbmi);
3573 const int mi_row = xd->mi_row;
3574 const int mi_col = xd->mi_col;
3575
3576 av1_init_rd_stats(rd_stats);
3577
3578 // Hashing based speed feature for inter blocks. If the hash of the residue
3579 // block is found in the table, use previously saved search results and
3580 // terminate early.
3581 uint32_t hash = 0;
3582 MB_RD_RECORD *mb_rd_record = NULL;
3583 const int num_blks = bsize_to_num_blk(bs);
3584 if (is_inter && cpi->sf.rd_sf.use_mb_rd_hash) {
3585 const int within_border =
3586 mi_row >= xd->tile.mi_row_start &&
3587 (mi_row + mi_size_high[bs] < xd->tile.mi_row_end) &&
3588 mi_col >= xd->tile.mi_col_start &&
3589 (mi_col + mi_size_wide[bs] < xd->tile.mi_col_end);
3590 if (within_border) {
3591 hash = get_block_residue_hash(x, bs);
3592 mb_rd_record = x->txfm_search_info.mb_rd_record;
3593 const int match_index = find_mb_rd_info(mb_rd_record, ref_best_rd, hash);
3594 if (match_index != -1) {
3595 MB_RD_INFO *mb_rd_info = &mb_rd_record->mb_rd_info[match_index];
3596 fetch_mb_rd_info(num_blks, mb_rd_info, rd_stats, x);
3597 return;
3598 }
3599 }
3600 }
3601
3602 // If we predict that skip is the optimal RD decision - set the respective
3603 // context and terminate early.
3604 int64_t dist;
3605 if (tx_params->skip_txfm_level && is_inter &&
3606 !xd->lossless[mbmi->segment_id] &&
3607 predict_skip_txfm(x, bs, &dist,
3608 cpi->common.features.reduced_tx_set_used)) {
3609 // Populate rdstats as per skip decision
3610 set_skip_txfm(x, rd_stats, bs, dist);
3611 // Save the RD search results into mb_rd_record.
3612 if (mb_rd_record) {
3613 save_mb_rd_info(num_blks, hash, x, rd_stats, mb_rd_record);
3614 }
3615 return;
3616 }
3617
3618 if (xd->lossless[mbmi->segment_id]) {
3619 // Lossless mode can only pick the smallest (4x4) transform size.
3620 choose_smallest_tx_size(cpi, x, rd_stats, ref_best_rd, bs);
3621 } else if (tx_params->tx_size_search_method == USE_LARGESTALL) {
3622 choose_largest_tx_size(cpi, x, rd_stats, ref_best_rd, bs);
3623 } else {
3624 choose_tx_size_type_from_rd(cpi, x, rd_stats, ref_best_rd, bs);
3625 }
3626
3627 // Save the RD search results into mb_rd_record for possible reuse in future.
3628 if (mb_rd_record) {
3629 save_mb_rd_info(num_blks, hash, x, rd_stats, mb_rd_record);
3630 }
3631 }
3632
av1_txfm_uvrd(const AV1_COMP * const cpi,MACROBLOCK * x,RD_STATS * rd_stats,BLOCK_SIZE bsize,int64_t ref_best_rd)3633 int av1_txfm_uvrd(const AV1_COMP *const cpi, MACROBLOCK *x, RD_STATS *rd_stats,
3634 BLOCK_SIZE bsize, int64_t ref_best_rd) {
3635 av1_init_rd_stats(rd_stats);
3636 if (ref_best_rd < 0) return 0;
3637 if (!x->e_mbd.is_chroma_ref) return 1;
3638
3639 MACROBLOCKD *const xd = &x->e_mbd;
3640 MB_MODE_INFO *const mbmi = xd->mi[0];
3641 struct macroblockd_plane *const pd = &xd->plane[AOM_PLANE_U];
3642 const int is_inter = is_inter_block(mbmi);
3643 int64_t this_rd = 0, skip_txfm_rd = 0;
3644 const BLOCK_SIZE plane_bsize =
3645 get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
3646
3647 if (is_inter) {
3648 for (int plane = 1; plane < MAX_MB_PLANE; ++plane)
3649 av1_subtract_plane(x, plane_bsize, plane);
3650 }
3651
3652 const int skip_trellis = 0;
3653 const TX_SIZE uv_tx_size = av1_get_tx_size(AOM_PLANE_U, xd);
3654 int is_cost_valid = 1;
3655 for (int plane = 1; plane < MAX_MB_PLANE; ++plane) {
3656 RD_STATS this_rd_stats;
3657 int64_t chroma_ref_best_rd = ref_best_rd;
3658 // For inter blocks, refined ref_best_rd is used for early exit
3659 // For intra blocks, even though current rd crosses ref_best_rd, early
3660 // exit is not recommended as current rd is used for gating subsequent
3661 // modes as well (say, for angular modes)
3662 // TODO(any): Extend the early exit mechanism for intra modes as well
3663 if (cpi->sf.inter_sf.perform_best_rd_based_gating_for_chroma && is_inter &&
3664 chroma_ref_best_rd != INT64_MAX)
3665 chroma_ref_best_rd = ref_best_rd - AOMMIN(this_rd, skip_txfm_rd);
3666 av1_txfm_rd_in_plane(x, cpi, &this_rd_stats, chroma_ref_best_rd, 0, plane,
3667 plane_bsize, uv_tx_size, FTXS_NONE, skip_trellis);
3668 if (this_rd_stats.rate == INT_MAX) {
3669 is_cost_valid = 0;
3670 break;
3671 }
3672 av1_merge_rd_stats(rd_stats, &this_rd_stats);
3673 this_rd = RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist);
3674 skip_txfm_rd = RDCOST(x->rdmult, 0, rd_stats->sse);
3675 if (AOMMIN(this_rd, skip_txfm_rd) > ref_best_rd) {
3676 is_cost_valid = 0;
3677 break;
3678 }
3679 }
3680
3681 if (!is_cost_valid) {
3682 // reset cost value
3683 av1_invalid_rd_stats(rd_stats);
3684 }
3685
3686 return is_cost_valid;
3687 }
3688
av1_txfm_rd_in_plane(MACROBLOCK * x,const AV1_COMP * cpi,RD_STATS * rd_stats,int64_t ref_best_rd,int64_t current_rd,int plane,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,FAST_TX_SEARCH_MODE ftxs_mode,int skip_trellis)3689 void av1_txfm_rd_in_plane(MACROBLOCK *x, const AV1_COMP *cpi,
3690 RD_STATS *rd_stats, int64_t ref_best_rd,
3691 int64_t current_rd, int plane, BLOCK_SIZE plane_bsize,
3692 TX_SIZE tx_size, FAST_TX_SEARCH_MODE ftxs_mode,
3693 int skip_trellis) {
3694 assert(IMPLIES(plane == 0, x->e_mbd.mi[0]->tx_size == tx_size));
3695
3696 if (!cpi->oxcf.txfm_cfg.enable_tx64 &&
3697 txsize_sqr_up_map[tx_size] == TX_64X64) {
3698 av1_invalid_rd_stats(rd_stats);
3699 return;
3700 }
3701
3702 if (current_rd > ref_best_rd) {
3703 av1_invalid_rd_stats(rd_stats);
3704 return;
3705 }
3706
3707 MACROBLOCKD *const xd = &x->e_mbd;
3708 const struct macroblockd_plane *const pd = &xd->plane[plane];
3709 struct rdcost_block_args args;
3710 av1_zero(args);
3711 args.x = x;
3712 args.cpi = cpi;
3713 args.best_rd = ref_best_rd;
3714 args.current_rd = current_rd;
3715 args.ftxs_mode = ftxs_mode;
3716 args.skip_trellis = skip_trellis;
3717 av1_init_rd_stats(&args.rd_stats);
3718
3719 av1_get_entropy_contexts(plane_bsize, pd, args.t_above, args.t_left);
3720 av1_foreach_transformed_block_in_plane(xd, plane_bsize, plane, block_rd_txfm,
3721 &args);
3722
3723 MB_MODE_INFO *const mbmi = xd->mi[0];
3724 const int is_inter = is_inter_block(mbmi);
3725 const int invalid_rd = is_inter ? args.incomplete_exit : args.exit_early;
3726
3727 if (invalid_rd) {
3728 av1_invalid_rd_stats(rd_stats);
3729 } else {
3730 *rd_stats = args.rd_stats;
3731 }
3732 }
3733
av1_txfm_search(const AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,RD_STATS * rd_stats,RD_STATS * rd_stats_y,RD_STATS * rd_stats_uv,int mode_rate,int64_t ref_best_rd)3734 int av1_txfm_search(const AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
3735 RD_STATS *rd_stats, RD_STATS *rd_stats_y,
3736 RD_STATS *rd_stats_uv, int mode_rate, int64_t ref_best_rd) {
3737 MACROBLOCKD *const xd = &x->e_mbd;
3738 TxfmSearchParams *txfm_params = &x->txfm_search_params;
3739 const int skip_ctx = av1_get_skip_txfm_context(xd);
3740 const int skip_txfm_cost[2] = { x->mode_costs.skip_txfm_cost[skip_ctx][0],
3741 x->mode_costs.skip_txfm_cost[skip_ctx][1] };
3742 const int64_t min_header_rate =
3743 mode_rate + AOMMIN(skip_txfm_cost[0], skip_txfm_cost[1]);
3744 // Account for minimum skip and non_skip rd.
3745 // Eventually either one of them will be added to mode_rate
3746 const int64_t min_header_rd_possible = RDCOST(x->rdmult, min_header_rate, 0);
3747 if (min_header_rd_possible > ref_best_rd) {
3748 av1_invalid_rd_stats(rd_stats_y);
3749 return 0;
3750 }
3751
3752 const AV1_COMMON *cm = &cpi->common;
3753 MB_MODE_INFO *const mbmi = xd->mi[0];
3754 const int64_t mode_rd = RDCOST(x->rdmult, mode_rate, 0);
3755 const int64_t rd_thresh =
3756 ref_best_rd == INT64_MAX ? INT64_MAX : ref_best_rd - mode_rd;
3757 av1_init_rd_stats(rd_stats);
3758 av1_init_rd_stats(rd_stats_y);
3759 rd_stats->rate = mode_rate;
3760
3761 // cost and distortion
3762 av1_subtract_plane(x, bsize, 0);
3763 if (txfm_params->tx_mode_search_type == TX_MODE_SELECT &&
3764 !xd->lossless[mbmi->segment_id]) {
3765 av1_pick_recursive_tx_size_type_yrd(cpi, x, rd_stats_y, bsize, rd_thresh);
3766 #if CONFIG_COLLECT_RD_STATS == 2
3767 PrintPredictionUnitStats(cpi, tile_data, x, rd_stats_y, bsize);
3768 #endif // CONFIG_COLLECT_RD_STATS == 2
3769 } else {
3770 av1_pick_uniform_tx_size_type_yrd(cpi, x, rd_stats_y, bsize, rd_thresh);
3771 memset(mbmi->inter_tx_size, mbmi->tx_size, sizeof(mbmi->inter_tx_size));
3772 for (int i = 0; i < xd->height * xd->width; ++i)
3773 set_blk_skip(x->txfm_search_info.blk_skip, 0, i, rd_stats_y->skip_txfm);
3774 }
3775
3776 if (rd_stats_y->rate == INT_MAX) return 0;
3777
3778 av1_merge_rd_stats(rd_stats, rd_stats_y);
3779
3780 const int64_t non_skip_txfm_rdcosty =
3781 RDCOST(x->rdmult, rd_stats->rate + skip_txfm_cost[0], rd_stats->dist);
3782 const int64_t skip_txfm_rdcosty =
3783 RDCOST(x->rdmult, mode_rate + skip_txfm_cost[1], rd_stats->sse);
3784 const int64_t min_rdcosty = AOMMIN(non_skip_txfm_rdcosty, skip_txfm_rdcosty);
3785 if (min_rdcosty > ref_best_rd) return 0;
3786
3787 av1_init_rd_stats(rd_stats_uv);
3788 const int num_planes = av1_num_planes(cm);
3789 if (num_planes > 1) {
3790 int64_t ref_best_chroma_rd = ref_best_rd;
3791 // Calculate best rd cost possible for chroma
3792 if (cpi->sf.inter_sf.perform_best_rd_based_gating_for_chroma &&
3793 (ref_best_chroma_rd != INT64_MAX)) {
3794 ref_best_chroma_rd = (ref_best_chroma_rd -
3795 AOMMIN(non_skip_txfm_rdcosty, skip_txfm_rdcosty));
3796 }
3797 const int is_cost_valid_uv =
3798 av1_txfm_uvrd(cpi, x, rd_stats_uv, bsize, ref_best_chroma_rd);
3799 if (!is_cost_valid_uv) return 0;
3800 av1_merge_rd_stats(rd_stats, rd_stats_uv);
3801 }
3802
3803 int choose_skip_txfm = rd_stats->skip_txfm;
3804 if (!choose_skip_txfm && !xd->lossless[mbmi->segment_id]) {
3805 const int64_t rdcost_no_skip_txfm = RDCOST(
3806 x->rdmult, rd_stats_y->rate + rd_stats_uv->rate + skip_txfm_cost[0],
3807 rd_stats->dist);
3808 const int64_t rdcost_skip_txfm =
3809 RDCOST(x->rdmult, skip_txfm_cost[1], rd_stats->sse);
3810 if (rdcost_no_skip_txfm >= rdcost_skip_txfm) choose_skip_txfm = 1;
3811 }
3812 if (choose_skip_txfm) {
3813 rd_stats_y->rate = 0;
3814 rd_stats_uv->rate = 0;
3815 rd_stats->rate = mode_rate + skip_txfm_cost[1];
3816 rd_stats->dist = rd_stats->sse;
3817 rd_stats_y->dist = rd_stats_y->sse;
3818 rd_stats_uv->dist = rd_stats_uv->sse;
3819 mbmi->skip_txfm = 1;
3820 if (rd_stats->skip_txfm) {
3821 const int64_t tmprd = RDCOST(x->rdmult, rd_stats->rate, rd_stats->dist);
3822 if (tmprd > ref_best_rd) return 0;
3823 }
3824 } else {
3825 rd_stats->rate += skip_txfm_cost[0];
3826 mbmi->skip_txfm = 0;
3827 }
3828
3829 return 1;
3830 }
3831