• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2017, 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/encoder/encodetxb.h"
13 
14 #include "aom_ports/mem.h"
15 #include "av1/common/blockd.h"
16 #include "av1/common/idct.h"
17 #include "av1/common/pred_common.h"
18 #include "av1/common/scan.h"
19 #include "av1/encoder/bitstream.h"
20 #include "av1/encoder/cost.h"
21 #include "av1/encoder/encodeframe.h"
22 #include "av1/encoder/hash.h"
23 #include "av1/encoder/rdopt.h"
24 #include "av1/encoder/tokenize.h"
25 
av1_alloc_txb_buf(AV1_COMP * cpi)26 void av1_alloc_txb_buf(AV1_COMP *cpi) {
27   AV1_COMMON *cm = &cpi->common;
28   CoeffBufferPool *coeff_buf_pool = &cpi->coeff_buffer_pool;
29   const int num_sb_rows =
30       CEIL_POWER_OF_TWO(cm->mi_params.mi_rows, cm->seq_params->mib_size_log2);
31   const int num_sb_cols =
32       CEIL_POWER_OF_TWO(cm->mi_params.mi_cols, cm->seq_params->mib_size_log2);
33   const int size = num_sb_rows * num_sb_cols;
34   const int num_planes = av1_num_planes(cm);
35   const int subsampling_x = cm->seq_params->subsampling_x;
36   const int subsampling_y = cm->seq_params->subsampling_y;
37   const int luma_max_sb_square =
38       1 << num_pels_log2_lookup[cm->seq_params->sb_size];
39   const int chroma_max_sb_square =
40       luma_max_sb_square >> (subsampling_x + subsampling_y);
41   const int num_tcoeffs =
42       size * (luma_max_sb_square + (num_planes - 1) * chroma_max_sb_square);
43   const int txb_unit_size = TX_SIZE_W_MIN * TX_SIZE_H_MIN;
44 
45   av1_free_txb_buf(cpi);
46   // TODO(jingning): This should be further reduced.
47   CHECK_MEM_ERROR(cm, cpi->coeff_buffer_base,
48                   aom_malloc(sizeof(*cpi->coeff_buffer_base) * size));
49   CHECK_MEM_ERROR(
50       cm, coeff_buf_pool->tcoeff,
51       aom_memalign(32, sizeof(*coeff_buf_pool->tcoeff) * num_tcoeffs));
52   CHECK_MEM_ERROR(
53       cm, coeff_buf_pool->eobs,
54       aom_malloc(sizeof(*coeff_buf_pool->eobs) * num_tcoeffs / txb_unit_size));
55   CHECK_MEM_ERROR(cm, coeff_buf_pool->entropy_ctx,
56                   aom_malloc(sizeof(*coeff_buf_pool->entropy_ctx) *
57                              num_tcoeffs / txb_unit_size));
58 
59   tran_low_t *tcoeff_ptr = coeff_buf_pool->tcoeff;
60   uint16_t *eob_ptr = coeff_buf_pool->eobs;
61   uint8_t *entropy_ctx_ptr = coeff_buf_pool->entropy_ctx;
62   for (int i = 0; i < size; i++) {
63     for (int plane = 0; plane < num_planes; plane++) {
64       const int max_sb_square =
65           (plane == AOM_PLANE_Y) ? luma_max_sb_square : chroma_max_sb_square;
66       cpi->coeff_buffer_base[i].tcoeff[plane] = tcoeff_ptr;
67       cpi->coeff_buffer_base[i].eobs[plane] = eob_ptr;
68       cpi->coeff_buffer_base[i].entropy_ctx[plane] = entropy_ctx_ptr;
69       tcoeff_ptr += max_sb_square;
70       eob_ptr += max_sb_square / txb_unit_size;
71       entropy_ctx_ptr += max_sb_square / txb_unit_size;
72     }
73   }
74 }
75 
av1_free_txb_buf(AV1_COMP * cpi)76 void av1_free_txb_buf(AV1_COMP *cpi) {
77   CoeffBufferPool *coeff_buf_pool = &cpi->coeff_buffer_pool;
78   aom_free(cpi->coeff_buffer_base);
79   cpi->coeff_buffer_base = NULL;
80   aom_free(coeff_buf_pool->tcoeff);
81   coeff_buf_pool->tcoeff = NULL;
82   aom_free(coeff_buf_pool->eobs);
83   coeff_buf_pool->eobs = NULL;
84   aom_free(coeff_buf_pool->entropy_ctx);
85   coeff_buf_pool->entropy_ctx = NULL;
86 }
87 
write_golomb(aom_writer * w,int level)88 static void write_golomb(aom_writer *w, int level) {
89   int x = level + 1;
90   int i = x;
91   int length = 0;
92 
93   while (i) {
94     i >>= 1;
95     ++length;
96   }
97   assert(length > 0);
98 
99   for (i = 0; i < length - 1; ++i) aom_write_bit(w, 0);
100 
101   for (i = length - 1; i >= 0; --i) aom_write_bit(w, (x >> i) & 0x01);
102 }
103 
104 static const int8_t eob_to_pos_small[33] = {
105   0, 1, 2,                                        // 0-2
106   3, 3,                                           // 3-4
107   4, 4, 4, 4,                                     // 5-8
108   5, 5, 5, 5, 5, 5, 5, 5,                         // 9-16
109   6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6  // 17-32
110 };
111 
112 static const int8_t eob_to_pos_large[17] = {
113   6,                               // place holder
114   7,                               // 33-64
115   8,  8,                           // 65-128
116   9,  9,  9,  9,                   // 129-256
117   10, 10, 10, 10, 10, 10, 10, 10,  // 257-512
118   11                               // 513-
119 };
120 
av1_get_eob_pos_token(const int eob,int * const extra)121 int av1_get_eob_pos_token(const int eob, int *const extra) {
122   int t;
123 
124   if (eob < 33) {
125     t = eob_to_pos_small[eob];
126   } else {
127     const int e = AOMMIN((eob - 1) >> 5, 16);
128     t = eob_to_pos_large[e];
129   }
130 
131   *extra = eob - av1_eob_group_start[t];
132 
133   return t;
134 }
135 
136 #if CONFIG_ENTROPY_STATS
av1_update_eob_context(int cdf_idx,int eob,TX_SIZE tx_size,TX_CLASS tx_class,PLANE_TYPE plane,FRAME_CONTEXT * ec_ctx,FRAME_COUNTS * counts,uint8_t allow_update_cdf)137 void av1_update_eob_context(int cdf_idx, int eob, TX_SIZE tx_size,
138                             TX_CLASS tx_class, PLANE_TYPE plane,
139                             FRAME_CONTEXT *ec_ctx, FRAME_COUNTS *counts,
140                             uint8_t allow_update_cdf) {
141 #else
142 void av1_update_eob_context(int eob, TX_SIZE tx_size, TX_CLASS tx_class,
143                             PLANE_TYPE plane, FRAME_CONTEXT *ec_ctx,
144                             uint8_t allow_update_cdf) {
145 #endif
146   int eob_extra;
147   const int eob_pt = av1_get_eob_pos_token(eob, &eob_extra);
148   TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
149 
150   const int eob_multi_size = txsize_log2_minus4[tx_size];
151   const int eob_multi_ctx = (tx_class == TX_CLASS_2D) ? 0 : 1;
152 
153   switch (eob_multi_size) {
154     case 0:
155 #if CONFIG_ENTROPY_STATS
156       ++counts->eob_multi16[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
157 #endif
158       if (allow_update_cdf)
159         update_cdf(ec_ctx->eob_flag_cdf16[plane][eob_multi_ctx], eob_pt - 1, 5);
160       break;
161     case 1:
162 #if CONFIG_ENTROPY_STATS
163       ++counts->eob_multi32[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
164 #endif
165       if (allow_update_cdf)
166         update_cdf(ec_ctx->eob_flag_cdf32[plane][eob_multi_ctx], eob_pt - 1, 6);
167       break;
168     case 2:
169 #if CONFIG_ENTROPY_STATS
170       ++counts->eob_multi64[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
171 #endif
172       if (allow_update_cdf)
173         update_cdf(ec_ctx->eob_flag_cdf64[plane][eob_multi_ctx], eob_pt - 1, 7);
174       break;
175     case 3:
176 #if CONFIG_ENTROPY_STATS
177       ++counts->eob_multi128[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
178 #endif
179       if (allow_update_cdf) {
180         update_cdf(ec_ctx->eob_flag_cdf128[plane][eob_multi_ctx], eob_pt - 1,
181                    8);
182       }
183       break;
184     case 4:
185 #if CONFIG_ENTROPY_STATS
186       ++counts->eob_multi256[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
187 #endif
188       if (allow_update_cdf) {
189         update_cdf(ec_ctx->eob_flag_cdf256[plane][eob_multi_ctx], eob_pt - 1,
190                    9);
191       }
192       break;
193     case 5:
194 #if CONFIG_ENTROPY_STATS
195       ++counts->eob_multi512[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
196 #endif
197       if (allow_update_cdf) {
198         update_cdf(ec_ctx->eob_flag_cdf512[plane][eob_multi_ctx], eob_pt - 1,
199                    10);
200       }
201       break;
202     case 6:
203     default:
204 #if CONFIG_ENTROPY_STATS
205       ++counts->eob_multi1024[cdf_idx][plane][eob_multi_ctx][eob_pt - 1];
206 #endif
207       if (allow_update_cdf) {
208         update_cdf(ec_ctx->eob_flag_cdf1024[plane][eob_multi_ctx], eob_pt - 1,
209                    11);
210       }
211       break;
212   }
213 
214   if (av1_eob_offset_bits[eob_pt] > 0) {
215     int eob_ctx = eob_pt - 3;
216     int eob_shift = av1_eob_offset_bits[eob_pt] - 1;
217     int bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
218 #if CONFIG_ENTROPY_STATS
219     counts->eob_extra[cdf_idx][txs_ctx][plane][eob_pt][bit]++;
220 #endif  // CONFIG_ENTROPY_STATS
221     if (allow_update_cdf)
222       update_cdf(ec_ctx->eob_extra_cdf[txs_ctx][plane][eob_ctx], bit, 2);
223   }
224 }
225 
226 static INLINE int get_nz_map_ctx(const uint8_t *const levels,
227                                  const int coeff_idx, const int bhl,
228                                  const int width, const int scan_idx,
229                                  const int is_eob, const TX_SIZE tx_size,
230                                  const TX_CLASS tx_class) {
231   if (is_eob) {
232     if (scan_idx == 0) return 0;
233     if (scan_idx <= (width << bhl) / 8) return 1;
234     if (scan_idx <= (width << bhl) / 4) return 2;
235     return 3;
236   }
237   const int stats =
238       get_nz_mag(levels + get_padded_idx(coeff_idx, bhl), bhl, tx_class);
239   return get_nz_map_ctx_from_stats(stats, coeff_idx, bhl, tx_size, tx_class);
240 }
241 
242 void av1_txb_init_levels_c(const tran_low_t *const coeff, const int width,
243                            const int height, uint8_t *const levels) {
244   const int stride = height + TX_PAD_HOR;
245   uint8_t *ls = levels;
246 
247   memset(levels + stride * width, 0,
248          sizeof(*levels) * (TX_PAD_BOTTOM * stride + TX_PAD_END));
249 
250   for (int i = 0; i < width; i++) {
251     for (int j = 0; j < height; j++) {
252       *ls++ = (uint8_t)clamp(abs(coeff[i * height + j]), 0, INT8_MAX);
253     }
254     for (int j = 0; j < TX_PAD_HOR; j++) {
255       *ls++ = 0;
256     }
257   }
258 }
259 
260 void av1_get_nz_map_contexts_c(const uint8_t *const levels,
261                                const int16_t *const scan, const uint16_t eob,
262                                const TX_SIZE tx_size, const TX_CLASS tx_class,
263                                int8_t *const coeff_contexts) {
264   const int bhl = get_txb_bhl(tx_size);
265   const int width = get_txb_wide(tx_size);
266   for (int i = 0; i < eob; ++i) {
267     const int pos = scan[i];
268     coeff_contexts[pos] = get_nz_map_ctx(levels, pos, bhl, width, i,
269                                          i == eob - 1, tx_size, tx_class);
270   }
271 }
272 
273 void av1_write_coeffs_txb(const AV1_COMMON *const cm, MACROBLOCK *const x,
274                           aom_writer *w, int blk_row, int blk_col, int plane,
275                           int block, TX_SIZE tx_size) {
276   MACROBLOCKD *xd = &x->e_mbd;
277   const CB_COEFF_BUFFER *cb_coef_buff = x->cb_coef_buff;
278   const PLANE_TYPE plane_type = get_plane_type(plane);
279   const int txb_offset = x->mbmi_ext_frame->cb_offset[plane_type] /
280                          (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
281   const uint16_t *eob_txb = cb_coef_buff->eobs[plane] + txb_offset;
282   const uint16_t eob = eob_txb[block];
283   const uint8_t *entropy_ctx = cb_coef_buff->entropy_ctx[plane] + txb_offset;
284   const int txb_skip_ctx = entropy_ctx[block] & TXB_SKIP_CTX_MASK;
285   const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
286   FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
287   aom_write_symbol(w, eob == 0, ec_ctx->txb_skip_cdf[txs_ctx][txb_skip_ctx], 2);
288   if (eob == 0) return;
289 
290   const TX_TYPE tx_type =
291       av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
292                       cm->features.reduced_tx_set_used);
293   // Only y plane's tx_type is transmitted
294   if (plane == 0) {
295     av1_write_tx_type(cm, xd, tx_type, tx_size, w);
296   }
297 
298   int eob_extra;
299   const int eob_pt = av1_get_eob_pos_token(eob, &eob_extra);
300   const int eob_multi_size = txsize_log2_minus4[tx_size];
301   const TX_CLASS tx_class = tx_type_to_class[tx_type];
302   const int eob_multi_ctx = (tx_class == TX_CLASS_2D) ? 0 : 1;
303   switch (eob_multi_size) {
304     case 0:
305       aom_write_symbol(w, eob_pt - 1,
306                        ec_ctx->eob_flag_cdf16[plane_type][eob_multi_ctx], 5);
307       break;
308     case 1:
309       aom_write_symbol(w, eob_pt - 1,
310                        ec_ctx->eob_flag_cdf32[plane_type][eob_multi_ctx], 6);
311       break;
312     case 2:
313       aom_write_symbol(w, eob_pt - 1,
314                        ec_ctx->eob_flag_cdf64[plane_type][eob_multi_ctx], 7);
315       break;
316     case 3:
317       aom_write_symbol(w, eob_pt - 1,
318                        ec_ctx->eob_flag_cdf128[plane_type][eob_multi_ctx], 8);
319       break;
320     case 4:
321       aom_write_symbol(w, eob_pt - 1,
322                        ec_ctx->eob_flag_cdf256[plane_type][eob_multi_ctx], 9);
323       break;
324     case 5:
325       aom_write_symbol(w, eob_pt - 1,
326                        ec_ctx->eob_flag_cdf512[plane_type][eob_multi_ctx], 10);
327       break;
328     default:
329       aom_write_symbol(w, eob_pt - 1,
330                        ec_ctx->eob_flag_cdf1024[plane_type][eob_multi_ctx], 11);
331       break;
332   }
333 
334   const int eob_offset_bits = av1_eob_offset_bits[eob_pt];
335   if (eob_offset_bits > 0) {
336     const int eob_ctx = eob_pt - 3;
337     int eob_shift = eob_offset_bits - 1;
338     int bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
339     aom_write_symbol(w, bit,
340                      ec_ctx->eob_extra_cdf[txs_ctx][plane_type][eob_ctx], 2);
341     for (int i = 1; i < eob_offset_bits; i++) {
342       eob_shift = eob_offset_bits - 1 - i;
343       bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
344       aom_write_bit(w, bit);
345     }
346   }
347 
348   const int width = get_txb_wide(tx_size);
349   const int height = get_txb_high(tx_size);
350   uint8_t levels_buf[TX_PAD_2D];
351   uint8_t *const levels = set_levels(levels_buf, height);
352   const tran_low_t *tcoeff_txb =
353       cb_coef_buff->tcoeff[plane] + x->mbmi_ext_frame->cb_offset[plane_type];
354   const tran_low_t *tcoeff = tcoeff_txb + BLOCK_OFFSET(block);
355   av1_txb_init_levels(tcoeff, width, height, levels);
356   const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
357   const int16_t *const scan = scan_order->scan;
358   DECLARE_ALIGNED(16, int8_t, coeff_contexts[MAX_TX_SQUARE]);
359   av1_get_nz_map_contexts(levels, scan, eob, tx_size, tx_class, coeff_contexts);
360 
361   const int bhl = get_txb_bhl(tx_size);
362   for (int c = eob - 1; c >= 0; --c) {
363     const int pos = scan[c];
364     const int coeff_ctx = coeff_contexts[pos];
365     const tran_low_t v = tcoeff[pos];
366     const tran_low_t level = abs(v);
367 
368     if (c == eob - 1) {
369       aom_write_symbol(
370           w, AOMMIN(level, 3) - 1,
371           ec_ctx->coeff_base_eob_cdf[txs_ctx][plane_type][coeff_ctx], 3);
372     } else {
373       aom_write_symbol(w, AOMMIN(level, 3),
374                        ec_ctx->coeff_base_cdf[txs_ctx][plane_type][coeff_ctx],
375                        4);
376     }
377     if (level > NUM_BASE_LEVELS) {
378       // level is above 1.
379       const int base_range = level - 1 - NUM_BASE_LEVELS;
380       const int br_ctx = get_br_ctx(levels, pos, bhl, tx_class);
381       aom_cdf_prob *cdf =
382           ec_ctx->coeff_br_cdf[AOMMIN(txs_ctx, TX_32X32)][plane_type][br_ctx];
383       for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
384         const int k = AOMMIN(base_range - idx, BR_CDF_SIZE - 1);
385         aom_write_symbol(w, k, cdf, BR_CDF_SIZE);
386         if (k < BR_CDF_SIZE - 1) break;
387       }
388     }
389   }
390 
391   // Loop to code all signs in the transform block,
392   // starting with the sign of DC (if applicable)
393   for (int c = 0; c < eob; ++c) {
394     const tran_low_t v = tcoeff[scan[c]];
395     const tran_low_t level = abs(v);
396     const int sign = (v < 0) ? 1 : 0;
397     if (level) {
398       if (c == 0) {
399         const int dc_sign_ctx =
400             (entropy_ctx[block] >> DC_SIGN_CTX_SHIFT) & DC_SIGN_CTX_MASK;
401         aom_write_symbol(w, sign, ec_ctx->dc_sign_cdf[plane_type][dc_sign_ctx],
402                          2);
403       } else {
404         aom_write_bit(w, sign);
405       }
406       if (level > COEFF_BASE_RANGE + NUM_BASE_LEVELS)
407         write_golomb(w, level - COEFF_BASE_RANGE - 1 - NUM_BASE_LEVELS);
408     }
409   }
410 }
411 
412 void av1_write_intra_coeffs_mb(const AV1_COMMON *const cm, MACROBLOCK *x,
413                                aom_writer *w, BLOCK_SIZE bsize) {
414   MACROBLOCKD *xd = &x->e_mbd;
415   const int num_planes = av1_num_planes(cm);
416   int block[MAX_MB_PLANE] = { 0 };
417   int row, col;
418   assert(bsize == get_plane_block_size(bsize, xd->plane[0].subsampling_x,
419                                        xd->plane[0].subsampling_y));
420   const int max_blocks_wide = max_block_wide(xd, bsize, 0);
421   const int max_blocks_high = max_block_high(xd, bsize, 0);
422   const BLOCK_SIZE max_unit_bsize = BLOCK_64X64;
423   int mu_blocks_wide = mi_size_wide[max_unit_bsize];
424   int mu_blocks_high = mi_size_high[max_unit_bsize];
425   mu_blocks_wide = AOMMIN(max_blocks_wide, mu_blocks_wide);
426   mu_blocks_high = AOMMIN(max_blocks_high, mu_blocks_high);
427 
428   for (row = 0; row < max_blocks_high; row += mu_blocks_high) {
429     for (col = 0; col < max_blocks_wide; col += mu_blocks_wide) {
430       for (int plane = 0; plane < num_planes; ++plane) {
431         if (plane && !xd->is_chroma_ref) break;
432         const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
433         const int stepr = tx_size_high_unit[tx_size];
434         const int stepc = tx_size_wide_unit[tx_size];
435         const int step = stepr * stepc;
436         const struct macroblockd_plane *const pd = &xd->plane[plane];
437         const int unit_height = ROUND_POWER_OF_TWO(
438             AOMMIN(mu_blocks_high + row, max_blocks_high), pd->subsampling_y);
439         const int unit_width = ROUND_POWER_OF_TWO(
440             AOMMIN(mu_blocks_wide + col, max_blocks_wide), pd->subsampling_x);
441         for (int blk_row = row >> pd->subsampling_y; blk_row < unit_height;
442              blk_row += stepr) {
443           for (int blk_col = col >> pd->subsampling_x; blk_col < unit_width;
444                blk_col += stepc) {
445             av1_write_coeffs_txb(cm, x, w, blk_row, blk_col, plane,
446                                  block[plane], tx_size);
447             block[plane] += step;
448           }
449         }
450       }
451     }
452   }
453 }
454 
455 uint8_t av1_get_txb_entropy_context(const tran_low_t *qcoeff,
456                                     const SCAN_ORDER *scan_order, int eob) {
457   const int16_t *const scan = scan_order->scan;
458   int cul_level = 0;
459   int c;
460 
461   if (eob == 0) return 0;
462   for (c = 0; c < eob; ++c) {
463     cul_level += abs(qcoeff[scan[c]]);
464     if (cul_level > COEFF_CONTEXT_MASK) break;
465   }
466 
467   cul_level = AOMMIN(COEFF_CONTEXT_MASK, cul_level);
468   set_dc_sign(&cul_level, qcoeff[0]);
469 
470   return (uint8_t)cul_level;
471 }
472 
473 static void update_tx_type_count(const AV1_COMP *cpi, const AV1_COMMON *cm,
474                                  MACROBLOCKD *xd, int blk_row, int blk_col,
475                                  int plane, TX_SIZE tx_size,
476                                  FRAME_COUNTS *counts,
477                                  uint8_t allow_update_cdf) {
478   MB_MODE_INFO *mbmi = xd->mi[0];
479   int is_inter = is_inter_block(mbmi);
480   const int reduced_tx_set_used = cm->features.reduced_tx_set_used;
481   FRAME_CONTEXT *fc = xd->tile_ctx;
482 #if !CONFIG_ENTROPY_STATS
483   (void)counts;
484 #endif  // !CONFIG_ENTROPY_STATS
485 
486   // Only y plane's tx_type is updated
487   if (plane > 0) return;
488   const TX_TYPE tx_type = av1_get_tx_type(xd, PLANE_TYPE_Y, blk_row, blk_col,
489                                           tx_size, reduced_tx_set_used);
490   if (is_inter) {
491     if (cpi->oxcf.txfm_cfg.use_inter_dct_only) {
492       assert(tx_type == DCT_DCT);
493     }
494   } else {
495     if (cpi->oxcf.txfm_cfg.use_intra_dct_only) {
496       assert(tx_type == DCT_DCT);
497     } else if (cpi->oxcf.txfm_cfg.use_intra_default_tx_only) {
498       const TX_TYPE default_type = get_default_tx_type(
499           PLANE_TYPE_Y, xd, tx_size, cpi->use_screen_content_tools);
500       (void)default_type;
501       // TODO(kyslov): We don't always respect use_intra_default_tx_only flag in
502       // NonRD and REALTIME case. Specifically we ignore it in hybrid inta mode
503       // search, when picking up intra mode in nonRD inter mode search and in RD
504       // REALTIME mode when we limit TX type usage.
505       // We need to fix txfm cfg for these cases. Meanwhile relieving the
506       // assert.
507       assert(tx_type == default_type || cpi->sf.rt_sf.use_nonrd_pick_mode ||
508              cpi->oxcf.mode == REALTIME);
509     }
510   }
511 
512   if (get_ext_tx_types(tx_size, is_inter, reduced_tx_set_used) > 1 &&
513       cm->quant_params.base_qindex > 0 && !mbmi->skip_txfm &&
514       !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) {
515     const int eset = get_ext_tx_set(tx_size, is_inter, reduced_tx_set_used);
516     if (eset > 0) {
517       const TxSetType tx_set_type =
518           av1_get_ext_tx_set_type(tx_size, is_inter, reduced_tx_set_used);
519       if (is_inter) {
520         if (allow_update_cdf) {
521           update_cdf(fc->inter_ext_tx_cdf[eset][txsize_sqr_map[tx_size]],
522                      av1_ext_tx_ind[tx_set_type][tx_type],
523                      av1_num_ext_tx_set[tx_set_type]);
524         }
525 #if CONFIG_ENTROPY_STATS
526         ++counts->inter_ext_tx[eset][txsize_sqr_map[tx_size]]
527                               [av1_ext_tx_ind[tx_set_type][tx_type]];
528 #endif  // CONFIG_ENTROPY_STATS
529       } else {
530         PREDICTION_MODE intra_dir;
531         if (mbmi->filter_intra_mode_info.use_filter_intra)
532           intra_dir = fimode_to_intradir[mbmi->filter_intra_mode_info
533                                              .filter_intra_mode];
534         else
535           intra_dir = mbmi->mode;
536 #if CONFIG_ENTROPY_STATS
537         ++counts->intra_ext_tx[eset][txsize_sqr_map[tx_size]][intra_dir]
538                               [av1_ext_tx_ind[tx_set_type][tx_type]];
539 #endif  // CONFIG_ENTROPY_STATS
540         if (allow_update_cdf) {
541           update_cdf(
542               fc->intra_ext_tx_cdf[eset][txsize_sqr_map[tx_size]][intra_dir],
543               av1_ext_tx_ind[tx_set_type][tx_type],
544               av1_num_ext_tx_set[tx_set_type]);
545         }
546       }
547     }
548   }
549 }
550 
551 void av1_update_and_record_txb_context(int plane, int block, int blk_row,
552                                        int blk_col, BLOCK_SIZE plane_bsize,
553                                        TX_SIZE tx_size, void *arg) {
554   struct tokenize_b_args *const args = arg;
555   const AV1_COMP *cpi = args->cpi;
556   const AV1_COMMON *cm = &cpi->common;
557   ThreadData *const td = args->td;
558   MACROBLOCK *const x = &td->mb;
559   MACROBLOCKD *const xd = &x->e_mbd;
560   struct macroblock_plane *p = &x->plane[plane];
561   struct macroblockd_plane *pd = &xd->plane[plane];
562   const int eob = p->eobs[block];
563   const int block_offset = BLOCK_OFFSET(block);
564   tran_low_t *qcoeff = p->qcoeff + block_offset;
565   const PLANE_TYPE plane_type = pd->plane_type;
566   const TX_TYPE tx_type =
567       av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
568                       cm->features.reduced_tx_set_used);
569   const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
570   tran_low_t *tcoeff;
571   assert(args->dry_run != DRY_RUN_COSTCOEFFS);
572   if (args->dry_run == OUTPUT_ENABLED) {
573     MB_MODE_INFO *mbmi = xd->mi[0];
574     TXB_CTX txb_ctx;
575     get_txb_ctx(plane_bsize, tx_size, plane,
576                 pd->above_entropy_context + blk_col,
577                 pd->left_entropy_context + blk_row, &txb_ctx);
578     const int bhl = get_txb_bhl(tx_size);
579     const int width = get_txb_wide(tx_size);
580     const int height = get_txb_high(tx_size);
581     const uint8_t allow_update_cdf = args->allow_update_cdf;
582     const TX_SIZE txsize_ctx = get_txsize_entropy_ctx(tx_size);
583     FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
584 #if CONFIG_ENTROPY_STATS
585     int cdf_idx = cm->coef_cdf_category;
586     ++td->counts->txb_skip[cdf_idx][txsize_ctx][txb_ctx.txb_skip_ctx][eob == 0];
587 #endif  // CONFIG_ENTROPY_STATS
588     if (allow_update_cdf) {
589       update_cdf(ec_ctx->txb_skip_cdf[txsize_ctx][txb_ctx.txb_skip_ctx],
590                  eob == 0, 2);
591     }
592 
593     CB_COEFF_BUFFER *cb_coef_buff = x->cb_coef_buff;
594     const int txb_offset = x->mbmi_ext_frame->cb_offset[plane_type] /
595                            (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
596     uint16_t *eob_txb = cb_coef_buff->eobs[plane] + txb_offset;
597     uint8_t *const entropy_ctx = cb_coef_buff->entropy_ctx[plane] + txb_offset;
598     entropy_ctx[block] = txb_ctx.txb_skip_ctx;
599     eob_txb[block] = eob;
600 
601     if (eob == 0) {
602       av1_set_entropy_contexts(xd, pd, plane, plane_bsize, tx_size, 0, blk_col,
603                                blk_row);
604       return;
605     }
606     const int segment_id = mbmi->segment_id;
607     const int seg_eob = av1_get_tx_eob(&cpi->common.seg, segment_id, tx_size);
608     tran_low_t *tcoeff_txb =
609         cb_coef_buff->tcoeff[plane] + x->mbmi_ext_frame->cb_offset[plane_type];
610     tcoeff = tcoeff_txb + block_offset;
611     memcpy(tcoeff, qcoeff, sizeof(*tcoeff) * seg_eob);
612 
613     uint8_t levels_buf[TX_PAD_2D];
614     uint8_t *const levels = set_levels(levels_buf, height);
615     av1_txb_init_levels(tcoeff, width, height, levels);
616     update_tx_type_count(cpi, cm, xd, blk_row, blk_col, plane, tx_size,
617                          td->counts, allow_update_cdf);
618 
619     const TX_CLASS tx_class = tx_type_to_class[tx_type];
620     const int16_t *const scan = scan_order->scan;
621 
622     // record tx type usage
623     td->rd_counts.tx_type_used[tx_size][tx_type]++;
624 
625 #if CONFIG_ENTROPY_STATS
626     av1_update_eob_context(cdf_idx, eob, tx_size, tx_class, plane_type, ec_ctx,
627                            td->counts, allow_update_cdf);
628 #else
629     av1_update_eob_context(eob, tx_size, tx_class, plane_type, ec_ctx,
630                            allow_update_cdf);
631 #endif
632 
633     DECLARE_ALIGNED(16, int8_t, coeff_contexts[MAX_TX_SQUARE]);
634     av1_get_nz_map_contexts(levels, scan, eob, tx_size, tx_class,
635                             coeff_contexts);
636 
637     for (int c = eob - 1; c >= 0; --c) {
638       const int pos = scan[c];
639       const int coeff_ctx = coeff_contexts[pos];
640       const tran_low_t v = qcoeff[pos];
641       const tran_low_t level = abs(v);
642       /* abs_sum_level is needed to decide the job scheduling order of
643        * pack bitstream multi-threading. This data is not needed if
644        * multi-threading is disabled. */
645       if (cpi->mt_info.pack_bs_mt_enabled) td->abs_sum_level += level;
646 
647       if (allow_update_cdf) {
648         if (c == eob - 1) {
649           assert(coeff_ctx < 4);
650           update_cdf(
651               ec_ctx->coeff_base_eob_cdf[txsize_ctx][plane_type][coeff_ctx],
652               AOMMIN(level, 3) - 1, 3);
653         } else {
654           update_cdf(ec_ctx->coeff_base_cdf[txsize_ctx][plane_type][coeff_ctx],
655                      AOMMIN(level, 3), 4);
656         }
657       }
658       if (c == eob - 1) {
659         assert(coeff_ctx < 4);
660 #if CONFIG_ENTROPY_STATS
661         ++td->counts->coeff_base_eob_multi[cdf_idx][txsize_ctx][plane_type]
662                                           [coeff_ctx][AOMMIN(level, 3) - 1];
663       } else {
664         ++td->counts->coeff_base_multi[cdf_idx][txsize_ctx][plane_type]
665                                       [coeff_ctx][AOMMIN(level, 3)];
666 #endif
667       }
668       if (level > NUM_BASE_LEVELS) {
669         const int base_range = level - 1 - NUM_BASE_LEVELS;
670         const int br_ctx = get_br_ctx(levels, pos, bhl, tx_class);
671         for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
672           const int k = AOMMIN(base_range - idx, BR_CDF_SIZE - 1);
673           if (allow_update_cdf) {
674             update_cdf(ec_ctx->coeff_br_cdf[AOMMIN(txsize_ctx, TX_32X32)]
675                                            [plane_type][br_ctx],
676                        k, BR_CDF_SIZE);
677           }
678           for (int lps = 0; lps < BR_CDF_SIZE - 1; lps++) {
679 #if CONFIG_ENTROPY_STATS
680             ++td->counts->coeff_lps[AOMMIN(txsize_ctx, TX_32X32)][plane_type]
681                                    [lps][br_ctx][lps == k];
682 #endif  // CONFIG_ENTROPY_STATS
683             if (lps == k) break;
684           }
685 #if CONFIG_ENTROPY_STATS
686           ++td->counts->coeff_lps_multi[cdf_idx][AOMMIN(txsize_ctx, TX_32X32)]
687                                        [plane_type][br_ctx][k];
688 #endif
689           if (k < BR_CDF_SIZE - 1) break;
690         }
691       }
692     }
693     // Update the context needed to code the DC sign (if applicable)
694     if (tcoeff[0] != 0) {
695       const int dc_sign = (tcoeff[0] < 0) ? 1 : 0;
696       const int dc_sign_ctx = txb_ctx.dc_sign_ctx;
697 #if CONFIG_ENTROPY_STATS
698       ++td->counts->dc_sign[plane_type][dc_sign_ctx][dc_sign];
699 #endif  // CONFIG_ENTROPY_STATS
700       if (allow_update_cdf)
701         update_cdf(ec_ctx->dc_sign_cdf[plane_type][dc_sign_ctx], dc_sign, 2);
702       entropy_ctx[block] |= dc_sign_ctx << DC_SIGN_CTX_SHIFT;
703     }
704   } else {
705     tcoeff = qcoeff;
706   }
707   const uint8_t cul_level =
708       av1_get_txb_entropy_context(tcoeff, scan_order, eob);
709   av1_set_entropy_contexts(xd, pd, plane, plane_bsize, tx_size, cul_level,
710                            blk_col, blk_row);
711 }
712 
713 void av1_record_txb_context(int plane, int block, int blk_row, int blk_col,
714                             BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
715                             void *arg) {
716   struct tokenize_b_args *const args = arg;
717   const AV1_COMP *cpi = args->cpi;
718   const AV1_COMMON *cm = &cpi->common;
719   ThreadData *const td = args->td;
720   MACROBLOCK *const x = &td->mb;
721   MACROBLOCKD *const xd = &x->e_mbd;
722   struct macroblock_plane *p = &x->plane[plane];
723   struct macroblockd_plane *pd = &xd->plane[plane];
724   const int eob = p->eobs[block];
725   const int block_offset = BLOCK_OFFSET(block);
726   tran_low_t *qcoeff = p->qcoeff + block_offset;
727   const PLANE_TYPE plane_type = pd->plane_type;
728   const TX_TYPE tx_type =
729       av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
730                       cm->features.reduced_tx_set_used);
731   const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
732   tran_low_t *tcoeff;
733   assert(args->dry_run != DRY_RUN_COSTCOEFFS);
734   if (args->dry_run == OUTPUT_ENABLED) {
735     MB_MODE_INFO *mbmi = xd->mi[0];
736     TXB_CTX txb_ctx;
737     get_txb_ctx(plane_bsize, tx_size, plane,
738                 pd->above_entropy_context + blk_col,
739                 pd->left_entropy_context + blk_row, &txb_ctx);
740 #if CONFIG_ENTROPY_STATS
741     const TX_SIZE txsize_ctx = get_txsize_entropy_ctx(tx_size);
742     const int bhl = get_txb_bhl(tx_size);
743     const int width = get_txb_wide(tx_size);
744     const int height = get_txb_high(tx_size);
745     int cdf_idx = cm->coef_cdf_category;
746     ++td->counts->txb_skip[cdf_idx][txsize_ctx][txb_ctx.txb_skip_ctx][eob == 0];
747 #endif  // CONFIG_ENTROPY_STATS
748 
749     CB_COEFF_BUFFER *cb_coef_buff = x->cb_coef_buff;
750     const int txb_offset = x->mbmi_ext_frame->cb_offset[plane_type] /
751                            (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
752     uint16_t *eob_txb = cb_coef_buff->eobs[plane] + txb_offset;
753     uint8_t *const entropy_ctx = cb_coef_buff->entropy_ctx[plane] + txb_offset;
754     entropy_ctx[block] = txb_ctx.txb_skip_ctx;
755     eob_txb[block] = eob;
756 
757     if (eob == 0) {
758       av1_set_entropy_contexts(xd, pd, plane, plane_bsize, tx_size, 0, blk_col,
759                                blk_row);
760       return;
761     }
762     const int segment_id = mbmi->segment_id;
763     const int seg_eob = av1_get_tx_eob(&cpi->common.seg, segment_id, tx_size);
764     tran_low_t *tcoeff_txb =
765         cb_coef_buff->tcoeff[plane] + x->mbmi_ext_frame->cb_offset[plane_type];
766     tcoeff = tcoeff_txb + block_offset;
767     memcpy(tcoeff, qcoeff, sizeof(*tcoeff) * seg_eob);
768 
769 #if CONFIG_ENTROPY_STATS
770     uint8_t levels_buf[TX_PAD_2D];
771     uint8_t *const levels = set_levels(levels_buf, height);
772     av1_txb_init_levels(tcoeff, width, height, levels);
773     update_tx_type_count(cpi, cm, xd, blk_row, blk_col, plane, tx_size,
774                          td->counts, 0 /*allow_update_cdf*/);
775 
776     const TX_CLASS tx_class = tx_type_to_class[tx_type];
777     const bool do_coeff_scan = true;
778 #else
779     const bool do_coeff_scan = cpi->mt_info.pack_bs_mt_enabled;
780 #endif
781     const int16_t *const scan = scan_order->scan;
782 
783     // record tx type usage
784     td->rd_counts.tx_type_used[tx_size][tx_type]++;
785 
786 #if CONFIG_ENTROPY_STATS
787     FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
788     av1_update_eob_context(cdf_idx, eob, tx_size, tx_class, plane_type, ec_ctx,
789                            td->counts, 0 /*allow_update_cdf*/);
790 
791     DECLARE_ALIGNED(16, int8_t, coeff_contexts[MAX_TX_SQUARE]);
792     av1_get_nz_map_contexts(levels, scan, eob, tx_size, tx_class,
793                             coeff_contexts);
794 #endif
795 
796     for (int c = eob - 1; (c >= 0) && do_coeff_scan; --c) {
797       const int pos = scan[c];
798       const tran_low_t v = qcoeff[pos];
799       const tran_low_t level = abs(v);
800       /* abs_sum_level is needed to decide the job scheduling order of
801        * pack bitstream multi-threading. This data is not needed if
802        * multi-threading is disabled. */
803       if (cpi->mt_info.pack_bs_mt_enabled) td->abs_sum_level += level;
804 
805 #if CONFIG_ENTROPY_STATS
806       const int coeff_ctx = coeff_contexts[pos];
807       if (c == eob - 1) {
808         assert(coeff_ctx < 4);
809         ++td->counts->coeff_base_eob_multi[cdf_idx][txsize_ctx][plane_type]
810                                           [coeff_ctx][AOMMIN(level, 3) - 1];
811       } else {
812         ++td->counts->coeff_base_multi[cdf_idx][txsize_ctx][plane_type]
813                                       [coeff_ctx][AOMMIN(level, 3)];
814       }
815       if (level > NUM_BASE_LEVELS) {
816         const int base_range = level - 1 - NUM_BASE_LEVELS;
817         const int br_ctx = get_br_ctx(levels, pos, bhl, tx_class);
818         for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
819           const int k = AOMMIN(base_range - idx, BR_CDF_SIZE - 1);
820           for (int lps = 0; lps < BR_CDF_SIZE - 1; lps++) {
821             ++td->counts->coeff_lps[AOMMIN(txsize_ctx, TX_32X32)][plane_type]
822                                    [lps][br_ctx][lps == k];
823             if (lps == k) break;
824           }
825           ++td->counts->coeff_lps_multi[cdf_idx][AOMMIN(txsize_ctx, TX_32X32)]
826                                        [plane_type][br_ctx][k];
827           if (k < BR_CDF_SIZE - 1) break;
828         }
829       }
830 #endif
831     }
832     // Update the context needed to code the DC sign (if applicable)
833     if (tcoeff[0] != 0) {
834       const int dc_sign_ctx = txb_ctx.dc_sign_ctx;
835 #if CONFIG_ENTROPY_STATS
836       const int dc_sign = (tcoeff[0] < 0) ? 1 : 0;
837       ++td->counts->dc_sign[plane_type][dc_sign_ctx][dc_sign];
838 #endif  // CONFIG_ENTROPY_STATS
839       entropy_ctx[block] |= dc_sign_ctx << DC_SIGN_CTX_SHIFT;
840     }
841   } else {
842     tcoeff = qcoeff;
843   }
844   const uint8_t cul_level =
845       av1_get_txb_entropy_context(tcoeff, scan_order, eob);
846   av1_set_entropy_contexts(xd, pd, plane, plane_bsize, tx_size, cul_level,
847                            blk_col, blk_row);
848 }
849 
850 void av1_update_intra_mb_txb_context(const AV1_COMP *cpi, ThreadData *td,
851                                      RUN_TYPE dry_run, BLOCK_SIZE bsize,
852                                      uint8_t allow_update_cdf) {
853   const AV1_COMMON *const cm = &cpi->common;
854   const int num_planes = av1_num_planes(cm);
855   MACROBLOCK *const x = &td->mb;
856   MACROBLOCKD *const xd = &x->e_mbd;
857   MB_MODE_INFO *const mbmi = xd->mi[0];
858   struct tokenize_b_args arg = { cpi, td, 0, allow_update_cdf, dry_run };
859   if (mbmi->skip_txfm) {
860     av1_reset_entropy_context(xd, bsize, num_planes);
861     return;
862   }
863   const foreach_transformed_block_visitor visit =
864       allow_update_cdf ? av1_update_and_record_txb_context
865                        : av1_record_txb_context;
866 
867   for (int plane = 0; plane < num_planes; ++plane) {
868     if (plane && !xd->is_chroma_ref) break;
869     const struct macroblockd_plane *const pd = &xd->plane[plane];
870     const int ss_x = pd->subsampling_x;
871     const int ss_y = pd->subsampling_y;
872     const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, ss_x, ss_y);
873     av1_foreach_transformed_block_in_plane(xd, plane_bsize, plane, visit, &arg);
874   }
875 }
876 
877 CB_COEFF_BUFFER *av1_get_cb_coeff_buffer(const struct AV1_COMP *cpi, int mi_row,
878                                          int mi_col) {
879   const AV1_COMMON *const cm = &cpi->common;
880   const int mib_size_log2 = cm->seq_params->mib_size_log2;
881   const int stride =
882       CEIL_POWER_OF_TWO(cm->mi_params.mi_cols, cm->seq_params->mib_size_log2);
883   const int offset =
884       (mi_row >> mib_size_log2) * stride + (mi_col >> mib_size_log2);
885   return cpi->coeff_buffer_base + offset;
886 }
887