• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include "config/aom_config.h"
13 #include "config/av1_rtcd.h"
14 #include "config/aom_dsp_rtcd.h"
15 
16 #include "aom_dsp/bitwriter.h"
17 #include "aom_dsp/quantize.h"
18 #include "aom_mem/aom_mem.h"
19 #include "aom_ports/mem.h"
20 
21 #if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
22 #include "aom_util/debug_util.h"
23 #endif  // CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
24 
25 #include "av1/common/cfl.h"
26 #include "av1/common/idct.h"
27 #include "av1/common/reconinter.h"
28 #include "av1/common/reconintra.h"
29 #include "av1/common/scan.h"
30 
31 #include "av1/encoder/av1_quantize.h"
32 #include "av1/encoder/encodemb.h"
33 #include "av1/encoder/hybrid_fwd_txfm.h"
34 #include "av1/encoder/txb_rdopt.h"
35 #include "av1/encoder/rd.h"
36 #include "av1/encoder/rdopt.h"
37 
av1_subtract_block(BitDepthInfo bd_info,int rows,int cols,int16_t * diff,ptrdiff_t diff_stride,const uint8_t * src8,ptrdiff_t src_stride,const uint8_t * pred8,ptrdiff_t pred_stride)38 void av1_subtract_block(BitDepthInfo bd_info, int rows, int cols, int16_t *diff,
39                         ptrdiff_t diff_stride, const uint8_t *src8,
40                         ptrdiff_t src_stride, const uint8_t *pred8,
41                         ptrdiff_t pred_stride) {
42   assert(rows >= 4 && cols >= 4);
43 #if CONFIG_AV1_HIGHBITDEPTH
44   if (bd_info.use_highbitdepth_buf) {
45     aom_highbd_subtract_block(rows, cols, diff, diff_stride, src8, src_stride,
46                               pred8, pred_stride, bd_info.bit_depth);
47     return;
48   }
49 #endif
50   (void)bd_info;
51   aom_subtract_block(rows, cols, diff, diff_stride, src8, src_stride, pred8,
52                      pred_stride);
53 }
54 
av1_subtract_txb(MACROBLOCK * x,int plane,BLOCK_SIZE plane_bsize,int blk_col,int blk_row,TX_SIZE tx_size)55 void av1_subtract_txb(MACROBLOCK *x, int plane, BLOCK_SIZE plane_bsize,
56                       int blk_col, int blk_row, TX_SIZE tx_size) {
57   MACROBLOCKD *const xd = &x->e_mbd;
58   const BitDepthInfo bd_info = get_bit_depth_info(xd);
59   struct macroblock_plane *const p = &x->plane[plane];
60   const struct macroblockd_plane *const pd = &x->e_mbd.plane[plane];
61   const int diff_stride = block_size_wide[plane_bsize];
62   const int src_stride = p->src.stride;
63   const int dst_stride = pd->dst.stride;
64   const int tx1d_width = tx_size_wide[tx_size];
65   const int tx1d_height = tx_size_high[tx_size];
66   uint8_t *dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
67   uint8_t *src = &p->src.buf[(blk_row * src_stride + blk_col) << MI_SIZE_LOG2];
68   int16_t *src_diff =
69       &p->src_diff[(blk_row * diff_stride + blk_col) << MI_SIZE_LOG2];
70   av1_subtract_block(bd_info, tx1d_height, tx1d_width, src_diff, diff_stride,
71                      src, src_stride, dst, dst_stride);
72 }
73 
av1_subtract_plane(MACROBLOCK * x,BLOCK_SIZE plane_bsize,int plane)74 void av1_subtract_plane(MACROBLOCK *x, BLOCK_SIZE plane_bsize, int plane) {
75   struct macroblock_plane *const p = &x->plane[plane];
76   const struct macroblockd_plane *const pd = &x->e_mbd.plane[plane];
77   assert(plane_bsize < BLOCK_SIZES_ALL);
78   const int bw = block_size_wide[plane_bsize];
79   const int bh = block_size_high[plane_bsize];
80   const MACROBLOCKD *xd = &x->e_mbd;
81   const BitDepthInfo bd_info = get_bit_depth_info(xd);
82 
83   av1_subtract_block(bd_info, bh, bw, p->src_diff, bw, p->src.buf,
84                      p->src.stride, pd->dst.buf, pd->dst.stride);
85 }
86 
av1_optimize_b(const struct AV1_COMP * cpi,MACROBLOCK * x,int plane,int block,TX_SIZE tx_size,TX_TYPE tx_type,const TXB_CTX * const txb_ctx,int * rate_cost)87 int av1_optimize_b(const struct AV1_COMP *cpi, MACROBLOCK *x, int plane,
88                    int block, TX_SIZE tx_size, TX_TYPE tx_type,
89                    const TXB_CTX *const txb_ctx, int *rate_cost) {
90   MACROBLOCKD *const xd = &x->e_mbd;
91   struct macroblock_plane *const p = &x->plane[plane];
92   const int eob = p->eobs[block];
93   const int segment_id = xd->mi[0]->segment_id;
94 
95   if (eob == 0 || !cpi->optimize_seg_arr[segment_id] ||
96       xd->lossless[segment_id]) {
97     *rate_cost = av1_cost_skip_txb(&x->coeff_costs, txb_ctx, plane, tx_size);
98     return eob;
99   }
100 
101   return av1_optimize_txb(cpi, x, plane, block, tx_size, tx_type, txb_ctx,
102                           rate_cost, cpi->oxcf.algo_cfg.sharpness);
103 }
104 
105 // Hyper-parameters for dropout optimization, based on following logics.
106 // TODO(yjshen): These settings are tuned by experiments. They may still be
107 // optimized for better performance.
108 // (1) Coefficients which are large enough will ALWAYS be kept.
109 const tran_low_t DROPOUT_COEFF_MAX = 2;  // Max dropout-able coefficient.
110 // (2) Continuous coefficients will ALWAYS be kept. Here rigorous continuity is
111 //     NOT required. For example, `5 0 0 0 7` is treated as two continuous
112 //     coefficients if three zeros do not fulfill the dropout condition.
113 const int DROPOUT_CONTINUITY_MAX = 2;  // Max dropout-able continuous coeff.
114 // (3) Dropout operation is NOT applicable to blocks with large or small
115 //     quantization index.
116 const int DROPOUT_Q_MAX = 128;
117 const int DROPOUT_Q_MIN = 16;
118 // (4) Recall that dropout optimization will forcibly set some quantized
119 //     coefficients to zero. The key logic on determining whether a coefficient
120 //     should be dropped is to check the number of continuous zeros before AND
121 //     after this coefficient. The exact number of zeros for judgement depends
122 //     on block size and quantization index. More concretely, block size
123 //     determines the base number of zeros, while quantization index determines
124 //     the multiplier. Intuitively, larger block requires more zeros and larger
125 //     quantization index also requires more zeros (more information is lost
126 //     when using larger quantization index).
127 const int DROPOUT_BEFORE_BASE_MAX = 32;  // Max base number for leading zeros.
128 const int DROPOUT_BEFORE_BASE_MIN = 16;  // Min base number for leading zeros.
129 const int DROPOUT_AFTER_BASE_MAX = 32;   // Max base number for trailing zeros.
130 const int DROPOUT_AFTER_BASE_MIN = 16;   // Min base number for trailing zeros.
131 const int DROPOUT_MULTIPLIER_MAX = 8;    // Max multiplier on number of zeros.
132 const int DROPOUT_MULTIPLIER_MIN = 2;    // Min multiplier on number of zeros.
133 const int DROPOUT_MULTIPLIER_Q_BASE = 32;  // Base Q to compute multiplier.
134 
av1_dropout_qcoeff(MACROBLOCK * mb,int plane,int block,TX_SIZE tx_size,TX_TYPE tx_type,int qindex)135 void av1_dropout_qcoeff(MACROBLOCK *mb, int plane, int block, TX_SIZE tx_size,
136                         TX_TYPE tx_type, int qindex) {
137   const int tx_width = tx_size_wide[tx_size];
138   const int tx_height = tx_size_high[tx_size];
139 
140   // Early return if `qindex` is out of range.
141   if (qindex > DROPOUT_Q_MAX || qindex < DROPOUT_Q_MIN) {
142     return;
143   }
144 
145   // Compute number of zeros used for dropout judgement.
146   const int base_size = AOMMAX(tx_width, tx_height);
147   const int multiplier = CLIP(qindex / DROPOUT_MULTIPLIER_Q_BASE,
148                               DROPOUT_MULTIPLIER_MIN, DROPOUT_MULTIPLIER_MAX);
149   const int dropout_num_before =
150       multiplier *
151       CLIP(base_size, DROPOUT_BEFORE_BASE_MIN, DROPOUT_BEFORE_BASE_MAX);
152   const int dropout_num_after =
153       multiplier *
154       CLIP(base_size, DROPOUT_AFTER_BASE_MIN, DROPOUT_AFTER_BASE_MAX);
155 
156   av1_dropout_qcoeff_num(mb, plane, block, tx_size, tx_type, dropout_num_before,
157                          dropout_num_after);
158 }
159 
av1_dropout_qcoeff_num(MACROBLOCK * mb,int plane,int block,TX_SIZE tx_size,TX_TYPE tx_type,int dropout_num_before,int dropout_num_after)160 void av1_dropout_qcoeff_num(MACROBLOCK *mb, int plane, int block,
161                             TX_SIZE tx_size, TX_TYPE tx_type,
162                             int dropout_num_before, int dropout_num_after) {
163   const struct macroblock_plane *const p = &mb->plane[plane];
164   tran_low_t *const qcoeff = p->qcoeff + BLOCK_OFFSET(block);
165   tran_low_t *const dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
166   const int max_eob = av1_get_max_eob(tx_size);
167   const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
168 
169   // Early return if there are not enough non-zero coefficients.
170   if (p->eobs[block] == 0 || p->eobs[block] <= dropout_num_before) {
171     return;
172   }
173 
174   int count_zeros_before = 0;
175   int count_zeros_after = 0;
176   int count_nonzeros = 0;
177   // Index of the first non-zero coefficient after sufficient number of
178   // continuous zeros. If equals to `-1`, it means number of leading zeros
179   // hasn't reach `dropout_num_before`.
180   int idx = -1;
181   int eob = 0;  // New end of block.
182 
183   for (int i = 0; i < p->eobs[block]; ++i) {
184     const int scan_idx = scan_order->scan[i];
185     if (abs(qcoeff[scan_idx]) > DROPOUT_COEFF_MAX) {
186       // Keep large coefficients.
187       count_zeros_before = 0;
188       count_zeros_after = 0;
189       idx = -1;
190       eob = i + 1;
191     } else if (qcoeff[scan_idx] == 0) {  // Count zeros.
192       if (idx == -1) {
193         ++count_zeros_before;
194       } else {
195         ++count_zeros_after;
196       }
197     } else {  // Count non-zeros.
198       if (count_zeros_before >= dropout_num_before) {
199         idx = (idx == -1) ? i : idx;
200         ++count_nonzeros;
201       } else {
202         count_zeros_before = 0;
203         eob = i + 1;
204       }
205     }
206 
207     // Handle continuity.
208     if (count_nonzeros > DROPOUT_CONTINUITY_MAX) {
209       count_zeros_before = 0;
210       count_zeros_after = 0;
211       count_nonzeros = 0;
212       idx = -1;
213       eob = i + 1;
214     }
215 
216     // Handle the trailing zeros after original end of block.
217     if (idx != -1 && i == p->eobs[block] - 1) {
218       count_zeros_after += (max_eob - p->eobs[block]);
219     }
220 
221     // Set redundant coefficients to zeros if needed.
222     if (count_zeros_after >= dropout_num_after) {
223       for (int j = idx; j <= i; ++j) {
224         qcoeff[scan_order->scan[j]] = 0;
225         dqcoeff[scan_order->scan[j]] = 0;
226       }
227       count_zeros_before += (i - idx + 1);
228       count_zeros_after = 0;
229       count_nonzeros = 0;
230     } else if (i == p->eobs[block] - 1) {
231       eob = i + 1;
232     }
233   }
234 
235   if (eob != p->eobs[block]) {
236     p->eobs[block] = eob;
237     p->txb_entropy_ctx[block] =
238         av1_get_txb_entropy_context(qcoeff, scan_order, eob);
239   }
240 }
241 
242 // Settings for optimization type. NOTE: To set optimization type for all intra
243 // frames, both `KEY_BLOCK_OPT_TYPE` and `INTRA_BLOCK_OPT_TYPE` should be set.
244 // TODO(yjshen): These settings are hard-coded and look okay for now. They
245 // should be made configurable later.
246 // Blocks of key frames ONLY.
247 const OPT_TYPE KEY_BLOCK_OPT_TYPE = TRELLIS_DROPOUT_OPT;
248 // Blocks of intra frames (key frames EXCLUSIVE).
249 const OPT_TYPE INTRA_BLOCK_OPT_TYPE = TRELLIS_DROPOUT_OPT;
250 // Blocks of inter frames. (NOTE: Dropout optimization is DISABLED by default
251 // if trellis optimization is on for inter frames.)
252 const OPT_TYPE INTER_BLOCK_OPT_TYPE = TRELLIS_DROPOUT_OPT;
253 
254 enum {
255   QUANT_FUNC_LOWBD = 0,
256   QUANT_FUNC_HIGHBD = 1,
257   QUANT_FUNC_TYPES = 2
258 } UENUM1BYTE(QUANT_FUNC);
259 
260 #if CONFIG_AV1_HIGHBITDEPTH
261 static AV1_QUANT_FACADE
262     quant_func_list[AV1_XFORM_QUANT_TYPES][QUANT_FUNC_TYPES] = {
263       { av1_quantize_fp_facade, av1_highbd_quantize_fp_facade },
264       { av1_quantize_b_facade, av1_highbd_quantize_b_facade },
265       { av1_quantize_dc_facade, av1_highbd_quantize_dc_facade },
266       { NULL, NULL }
267     };
268 #else
269 static AV1_QUANT_FACADE quant_func_list[AV1_XFORM_QUANT_TYPES] = {
270   av1_quantize_fp_facade, av1_quantize_b_facade, av1_quantize_dc_facade, NULL
271 };
272 #endif
273 
274 // Computes the transform for DC only blocks
av1_xform_dc_only(MACROBLOCK * x,int plane,int block,TxfmParam * txfm_param,int64_t per_px_mean)275 void av1_xform_dc_only(MACROBLOCK *x, int plane, int block,
276                        TxfmParam *txfm_param, int64_t per_px_mean) {
277   assert(per_px_mean != INT64_MAX);
278   const struct macroblock_plane *const p = &x->plane[plane];
279   const int block_offset = BLOCK_OFFSET(block);
280   tran_low_t *const coeff = p->coeff + block_offset;
281   const int n_coeffs = av1_get_max_eob(txfm_param->tx_size);
282   memset(coeff, 0, sizeof(*coeff) * n_coeffs);
283   coeff[0] =
284       (tran_low_t)((per_px_mean * dc_coeff_scale[txfm_param->tx_size]) >> 12);
285 }
286 
av1_xform_quant(MACROBLOCK * x,int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TxfmParam * txfm_param,QUANT_PARAM * qparam)287 void av1_xform_quant(MACROBLOCK *x, int plane, int block, int blk_row,
288                      int blk_col, BLOCK_SIZE plane_bsize, TxfmParam *txfm_param,
289                      QUANT_PARAM *qparam) {
290   av1_xform(x, plane, block, blk_row, blk_col, plane_bsize, txfm_param);
291   av1_quant(x, plane, block, txfm_param, qparam);
292 }
293 
av1_xform(MACROBLOCK * x,int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TxfmParam * txfm_param)294 void av1_xform(MACROBLOCK *x, int plane, int block, int blk_row, int blk_col,
295                BLOCK_SIZE plane_bsize, TxfmParam *txfm_param) {
296   const struct macroblock_plane *const p = &x->plane[plane];
297   const int block_offset = BLOCK_OFFSET(block);
298   tran_low_t *const coeff = p->coeff + block_offset;
299   const int diff_stride = block_size_wide[plane_bsize];
300 
301   const int src_offset = (blk_row * diff_stride + blk_col);
302   const int16_t *src_diff = &p->src_diff[src_offset << MI_SIZE_LOG2];
303 
304   av1_fwd_txfm(src_diff, coeff, diff_stride, txfm_param);
305 }
306 
av1_quant(MACROBLOCK * x,int plane,int block,TxfmParam * txfm_param,QUANT_PARAM * qparam)307 void av1_quant(MACROBLOCK *x, int plane, int block, TxfmParam *txfm_param,
308                QUANT_PARAM *qparam) {
309   const struct macroblock_plane *const p = &x->plane[plane];
310   const SCAN_ORDER *const scan_order =
311       get_scan(txfm_param->tx_size, txfm_param->tx_type);
312   const int block_offset = BLOCK_OFFSET(block);
313   tran_low_t *const coeff = p->coeff + block_offset;
314   tran_low_t *const qcoeff = p->qcoeff + block_offset;
315   tran_low_t *const dqcoeff = p->dqcoeff + block_offset;
316   uint16_t *const eob = &p->eobs[block];
317 
318   if (qparam->xform_quant_idx != AV1_XFORM_QUANT_SKIP_QUANT) {
319     const int n_coeffs = av1_get_max_eob(txfm_param->tx_size);
320     if (LIKELY(!x->seg_skip_block)) {
321 #if CONFIG_AV1_HIGHBITDEPTH
322       quant_func_list[qparam->xform_quant_idx][txfm_param->is_hbd](
323           coeff, n_coeffs, p, qcoeff, dqcoeff, eob, scan_order, qparam);
324 #else
325       quant_func_list[qparam->xform_quant_idx](
326           coeff, n_coeffs, p, qcoeff, dqcoeff, eob, scan_order, qparam);
327 #endif
328     } else {
329       av1_quantize_skip(n_coeffs, qcoeff, dqcoeff, eob);
330     }
331   }
332   // use_optimize_b is true means av1_optimze_b will be called,
333   // thus cannot update entropy ctx now (performed in optimize_b)
334   if (qparam->use_optimize_b) {
335     p->txb_entropy_ctx[block] = 0;
336   } else {
337     p->txb_entropy_ctx[block] =
338         av1_get_txb_entropy_context(qcoeff, scan_order, *eob);
339   }
340 }
341 
av1_setup_xform(const AV1_COMMON * cm,MACROBLOCK * x,TX_SIZE tx_size,TX_TYPE tx_type,TxfmParam * txfm_param)342 void av1_setup_xform(const AV1_COMMON *cm, MACROBLOCK *x, TX_SIZE tx_size,
343                      TX_TYPE tx_type, TxfmParam *txfm_param) {
344   MACROBLOCKD *const xd = &x->e_mbd;
345   MB_MODE_INFO *const mbmi = xd->mi[0];
346 
347   txfm_param->tx_type = tx_type;
348   txfm_param->tx_size = tx_size;
349   txfm_param->lossless = xd->lossless[mbmi->segment_id];
350   txfm_param->tx_set_type = av1_get_ext_tx_set_type(
351       tx_size, is_inter_block(mbmi), cm->features.reduced_tx_set_used);
352 
353   txfm_param->bd = xd->bd;
354   txfm_param->is_hbd = is_cur_buf_hbd(xd);
355 }
av1_setup_quant(TX_SIZE tx_size,int use_optimize_b,int xform_quant_idx,int use_quant_b_adapt,QUANT_PARAM * qparam)356 void av1_setup_quant(TX_SIZE tx_size, int use_optimize_b, int xform_quant_idx,
357                      int use_quant_b_adapt, QUANT_PARAM *qparam) {
358   qparam->log_scale = av1_get_tx_scale(tx_size);
359   qparam->tx_size = tx_size;
360 
361   qparam->use_quant_b_adapt = use_quant_b_adapt;
362 
363   // TODO(bohanli): optimize_b and quantization idx has relationship,
364   // but is kind of buried and complicated in different encoding stages.
365   // Should have a unified function to derive quant_idx, rather than
366   // determine and pass in the quant_idx
367   qparam->use_optimize_b = use_optimize_b;
368   qparam->xform_quant_idx = xform_quant_idx;
369 
370   qparam->qmatrix = NULL;
371   qparam->iqmatrix = NULL;
372 }
av1_setup_qmatrix(const CommonQuantParams * quant_params,const MACROBLOCKD * xd,int plane,TX_SIZE tx_size,TX_TYPE tx_type,QUANT_PARAM * qparam)373 void av1_setup_qmatrix(const CommonQuantParams *quant_params,
374                        const MACROBLOCKD *xd, int plane, TX_SIZE tx_size,
375                        TX_TYPE tx_type, QUANT_PARAM *qparam) {
376   qparam->qmatrix = av1_get_qmatrix(quant_params, xd, plane, tx_size, tx_type);
377   qparam->iqmatrix =
378       av1_get_iqmatrix(quant_params, xd, plane, tx_size, tx_type);
379 }
380 
encode_block(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg,RUN_TYPE dry_run)381 static void encode_block(int plane, int block, int blk_row, int blk_col,
382                          BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg,
383                          RUN_TYPE dry_run) {
384   (void)dry_run;
385   struct encode_b_args *const args = arg;
386   const AV1_COMP *const cpi = args->cpi;
387   const AV1_COMMON *const cm = &cpi->common;
388   MACROBLOCK *const x = args->x;
389   MACROBLOCKD *const xd = &x->e_mbd;
390   MB_MODE_INFO *mbmi = xd->mi[0];
391   struct macroblock_plane *const p = &x->plane[plane];
392   struct macroblockd_plane *const pd = &xd->plane[plane];
393   tran_low_t *const dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
394   uint8_t *dst;
395   ENTROPY_CONTEXT *a, *l;
396   int dummy_rate_cost = 0;
397 
398   const int bw = mi_size_wide[plane_bsize];
399   dst = &pd->dst.buf[(blk_row * pd->dst.stride + blk_col) << MI_SIZE_LOG2];
400 
401   a = &args->ta[blk_col];
402   l = &args->tl[blk_row];
403 
404   TX_TYPE tx_type = DCT_DCT;
405   if (!is_blk_skip(x->txfm_search_info.blk_skip, plane,
406                    blk_row * bw + blk_col) &&
407       !mbmi->skip_mode) {
408     tx_type = av1_get_tx_type(xd, pd->plane_type, blk_row, blk_col, tx_size,
409                               cm->features.reduced_tx_set_used);
410     TxfmParam txfm_param;
411     QUANT_PARAM quant_param;
412     const int use_trellis = is_trellis_used(args->enable_optimize_b, dry_run);
413     int quant_idx;
414     if (use_trellis)
415       quant_idx = AV1_XFORM_QUANT_FP;
416     else
417       quant_idx =
418           USE_B_QUANT_NO_TRELLIS ? AV1_XFORM_QUANT_B : AV1_XFORM_QUANT_FP;
419     av1_setup_xform(cm, x, tx_size, tx_type, &txfm_param);
420     av1_setup_quant(tx_size, use_trellis, quant_idx,
421                     cpi->oxcf.q_cfg.quant_b_adapt, &quant_param);
422     av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
423                       &quant_param);
424     av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
425                     &quant_param);
426 
427     // Whether trellis or dropout optimization is required for inter frames.
428     const bool do_trellis = INTER_BLOCK_OPT_TYPE == TRELLIS_OPT ||
429                             INTER_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT;
430     const bool do_dropout = INTER_BLOCK_OPT_TYPE == DROPOUT_OPT ||
431                             INTER_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT;
432 
433     if (quant_param.use_optimize_b && do_trellis) {
434       TXB_CTX txb_ctx;
435       get_txb_ctx(plane_bsize, tx_size, plane, a, l, &txb_ctx);
436       av1_optimize_b(args->cpi, x, plane, block, tx_size, tx_type, &txb_ctx,
437                      &dummy_rate_cost);
438     }
439     if (!quant_param.use_optimize_b && do_dropout) {
440       av1_dropout_qcoeff(x, plane, block, tx_size, tx_type,
441                          cm->quant_params.base_qindex);
442     }
443   } else {
444     p->eobs[block] = 0;
445     p->txb_entropy_ctx[block] = 0;
446   }
447 
448   av1_set_txb_context(x, plane, block, tx_size, a, l);
449 
450   if (p->eobs[block]) {
451     *(args->skip) = 0;
452     av1_inverse_transform_block(xd, dqcoeff, plane, tx_type, tx_size, dst,
453                                 pd->dst.stride, p->eobs[block],
454                                 cm->features.reduced_tx_set_used);
455   }
456 
457   // TODO(debargha, jingning): Temporarily disable txk_type check for eob=0
458   // case. It is possible that certain collision in hash index would cause
459   // the assertion failure. To further optimize the rate-distortion
460   // performance, we need to re-visit this part and enable this assert
461   // again.
462   if (p->eobs[block] == 0 && plane == 0) {
463 #if 0
464     if (args->cpi->oxcf.q_cfg.aq_mode == NO_AQ &&
465         args->cpi->oxcf.q_cfg.deltaq_mode == NO_DELTA_Q) {
466       // TODO(jingning,angiebird,huisu@google.com): enable txk_check when
467       // enable_optimize_b is true to detect potential RD bug.
468       const uint8_t disable_txk_check = args->enable_optimize_b;
469       if (!disable_txk_check) {
470         assert(xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col)] ==
471             DCT_DCT);
472       }
473     }
474 #endif
475     update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
476   }
477 
478 #if CONFIG_MISMATCH_DEBUG
479   if (dry_run == OUTPUT_ENABLED) {
480     int pixel_c, pixel_r;
481     BLOCK_SIZE bsize = txsize_to_bsize[tx_size];
482     int blk_w = block_size_wide[bsize];
483     int blk_h = block_size_high[bsize];
484     mi_to_pixel_loc(&pixel_c, &pixel_r, xd->mi_col, xd->mi_row, blk_col,
485                     blk_row, pd->subsampling_x, pd->subsampling_y);
486     mismatch_record_block_tx(dst, pd->dst.stride, cm->current_frame.order_hint,
487                              plane, pixel_c, pixel_r, blk_w, blk_h,
488                              xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
489   }
490 #endif
491 }
492 
encode_block_inter(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg,RUN_TYPE dry_run)493 static void encode_block_inter(int plane, int block, int blk_row, int blk_col,
494                                BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
495                                void *arg, RUN_TYPE dry_run) {
496   struct encode_b_args *const args = arg;
497   MACROBLOCK *const x = args->x;
498   MACROBLOCKD *const xd = &x->e_mbd;
499   MB_MODE_INFO *const mbmi = xd->mi[0];
500   const struct macroblockd_plane *const pd = &xd->plane[plane];
501   const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
502   const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
503 
504   if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
505 
506   const TX_SIZE plane_tx_size =
507       plane ? av1_get_max_uv_txsize(mbmi->bsize, pd->subsampling_x,
508                                     pd->subsampling_y)
509             : mbmi->inter_tx_size[av1_get_txb_size_index(plane_bsize, blk_row,
510                                                          blk_col)];
511   if (!plane) {
512     assert(tx_size_wide[tx_size] >= tx_size_wide[plane_tx_size] &&
513            tx_size_high[tx_size] >= tx_size_high[plane_tx_size]);
514   }
515 
516   if (tx_size == plane_tx_size || plane) {
517     encode_block(plane, block, blk_row, blk_col, plane_bsize, tx_size, arg,
518                  dry_run);
519   } else {
520     assert(tx_size < TX_SIZES_ALL);
521     const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
522     assert(IMPLIES(tx_size <= TX_4X4, sub_txs == tx_size));
523     assert(IMPLIES(tx_size > TX_4X4, sub_txs < tx_size));
524     // This is the square transform block partition entry point.
525     const int bsw = tx_size_wide_unit[sub_txs];
526     const int bsh = tx_size_high_unit[sub_txs];
527     const int step = bsh * bsw;
528     const int row_end =
529         AOMMIN(tx_size_high_unit[tx_size], max_blocks_high - blk_row);
530     const int col_end =
531         AOMMIN(tx_size_wide_unit[tx_size], max_blocks_wide - blk_col);
532     assert(bsw > 0 && bsh > 0);
533 
534     for (int row = 0; row < row_end; row += bsh) {
535       const int offsetr = blk_row + row;
536       for (int col = 0; col < col_end; col += bsw) {
537         const int offsetc = blk_col + col;
538 
539         encode_block_inter(plane, block, offsetr, offsetc, plane_bsize, sub_txs,
540                            arg, dry_run);
541         block += step;
542       }
543     }
544   }
545 }
546 
av1_foreach_transformed_block_in_plane(const MACROBLOCKD * const xd,BLOCK_SIZE plane_bsize,int plane,foreach_transformed_block_visitor visit,void * arg)547 void av1_foreach_transformed_block_in_plane(
548     const MACROBLOCKD *const xd, BLOCK_SIZE plane_bsize, int plane,
549     foreach_transformed_block_visitor visit, void *arg) {
550   const struct macroblockd_plane *const pd = &xd->plane[plane];
551   // block and transform sizes, in number of 4x4 blocks log 2 ("*_b")
552   // 4x4=0, 8x8=2, 16x16=4, 32x32=6, 64x64=8
553   // transform size varies per plane, look it up in a common way.
554   const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
555   const uint8_t txw_unit = tx_size_wide_unit[tx_size];
556   const uint8_t txh_unit = tx_size_high_unit[tx_size];
557   const int step = txw_unit * txh_unit;
558 
559   // If mb_to_right_edge is < 0 we are in a situation in which
560   // the current block size extends into the UMV and we won't
561   // visit the sub blocks that are wholly within the UMV.
562   const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
563   const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
564   const BLOCK_SIZE max_unit_bsize =
565       get_plane_block_size(BLOCK_64X64, pd->subsampling_x, pd->subsampling_y);
566   const int mu_blocks_wide =
567       AOMMIN(mi_size_wide[max_unit_bsize], max_blocks_wide);
568   const int mu_blocks_high =
569       AOMMIN(mi_size_high[max_unit_bsize], max_blocks_high);
570 
571   // Keep track of the row and column of the blocks we use so that we know
572   // if we are in the unrestricted motion border.
573   int i = 0;
574   for (int r = 0; r < max_blocks_high; r += mu_blocks_high) {
575     const int unit_height = AOMMIN(mu_blocks_high + r, max_blocks_high);
576     // Skip visiting the sub blocks that are wholly within the UMV.
577     for (int c = 0; c < max_blocks_wide; c += mu_blocks_wide) {
578       const int unit_width = AOMMIN(mu_blocks_wide + c, max_blocks_wide);
579       for (int blk_row = r; blk_row < unit_height; blk_row += txh_unit) {
580         for (int blk_col = c; blk_col < unit_width; blk_col += txw_unit) {
581           visit(plane, i, blk_row, blk_col, plane_bsize, tx_size, arg);
582           i += step;
583         }
584       }
585     }
586   }
587 }
588 
589 typedef struct encode_block_pass1_args {
590   AV1_COMP *cpi;
591   MACROBLOCK *x;
592 } encode_block_pass1_args;
593 
encode_block_pass1(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)594 static void encode_block_pass1(int plane, int block, int blk_row, int blk_col,
595                                BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
596                                void *arg) {
597   encode_block_pass1_args *args = (encode_block_pass1_args *)arg;
598   AV1_COMP *cpi = args->cpi;
599   AV1_COMMON *cm = &cpi->common;
600   MACROBLOCK *const x = args->x;
601   MACROBLOCKD *const xd = &x->e_mbd;
602   struct macroblock_plane *const p = &x->plane[plane];
603   struct macroblockd_plane *const pd = &xd->plane[plane];
604   tran_low_t *const dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
605 
606   uint8_t *dst;
607   dst = &pd->dst.buf[(blk_row * pd->dst.stride + blk_col) << MI_SIZE_LOG2];
608 
609   TxfmParam txfm_param;
610   QUANT_PARAM quant_param;
611 
612   av1_setup_xform(cm, x, tx_size, DCT_DCT, &txfm_param);
613   av1_setup_quant(tx_size, 0, AV1_XFORM_QUANT_B, cpi->oxcf.q_cfg.quant_b_adapt,
614                   &quant_param);
615   av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, DCT_DCT,
616                     &quant_param);
617 
618   av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
619                   &quant_param);
620 
621   if (p->eobs[block] > 0) {
622     txfm_param.eob = p->eobs[block];
623     if (txfm_param.is_hbd) {
624       av1_highbd_inv_txfm_add(dqcoeff, dst, pd->dst.stride, &txfm_param);
625       return;
626     }
627     av1_inv_txfm_add(dqcoeff, dst, pd->dst.stride, &txfm_param);
628   }
629 }
630 
av1_encode_sby_pass1(AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize)631 void av1_encode_sby_pass1(AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize) {
632   encode_block_pass1_args args = { cpi, x };
633   av1_subtract_plane(x, bsize, 0);
634   av1_foreach_transformed_block_in_plane(&x->e_mbd, bsize, 0,
635                                          encode_block_pass1, &args);
636 }
637 
av1_encode_sb(const struct AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,RUN_TYPE dry_run)638 void av1_encode_sb(const struct AV1_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
639                    RUN_TYPE dry_run) {
640   assert(bsize < BLOCK_SIZES_ALL);
641   MACROBLOCKD *const xd = &x->e_mbd;
642   MB_MODE_INFO *mbmi = xd->mi[0];
643   mbmi->skip_txfm = 1;
644   if (x->txfm_search_info.skip_txfm) return;
645 
646   struct optimize_ctx ctx;
647   struct encode_b_args arg = {
648     cpi,  x,    &ctx,    &mbmi->skip_txfm,
649     NULL, NULL, dry_run, cpi->optimize_seg_arr[mbmi->segment_id]
650   };
651   const AV1_COMMON *const cm = &cpi->common;
652   const int num_planes = av1_num_planes(cm);
653   for (int plane = 0; plane < num_planes; ++plane) {
654     const struct macroblockd_plane *const pd = &xd->plane[plane];
655     const int subsampling_x = pd->subsampling_x;
656     const int subsampling_y = pd->subsampling_y;
657     if (plane && !xd->is_chroma_ref) break;
658     const BLOCK_SIZE plane_bsize =
659         get_plane_block_size(bsize, subsampling_x, subsampling_y);
660     assert(plane_bsize < BLOCK_SIZES_ALL);
661     const int mi_width = mi_size_wide[plane_bsize];
662     const int mi_height = mi_size_high[plane_bsize];
663     const TX_SIZE max_tx_size = get_vartx_max_txsize(xd, plane_bsize, plane);
664     const BLOCK_SIZE txb_size = txsize_to_bsize[max_tx_size];
665     const int bw = mi_size_wide[txb_size];
666     const int bh = mi_size_high[txb_size];
667     int block = 0;
668     const int step =
669         tx_size_wide_unit[max_tx_size] * tx_size_high_unit[max_tx_size];
670     av1_get_entropy_contexts(plane_bsize, pd, ctx.ta[plane], ctx.tl[plane]);
671     av1_subtract_plane(x, plane_bsize, plane);
672     arg.ta = ctx.ta[plane];
673     arg.tl = ctx.tl[plane];
674     const BLOCK_SIZE max_unit_bsize =
675         get_plane_block_size(BLOCK_64X64, subsampling_x, subsampling_y);
676     int mu_blocks_wide = mi_size_wide[max_unit_bsize];
677     int mu_blocks_high = mi_size_high[max_unit_bsize];
678     mu_blocks_wide = AOMMIN(mi_width, mu_blocks_wide);
679     mu_blocks_high = AOMMIN(mi_height, mu_blocks_high);
680 
681     for (int idy = 0; idy < mi_height; idy += mu_blocks_high) {
682       for (int idx = 0; idx < mi_width; idx += mu_blocks_wide) {
683         int blk_row, blk_col;
684         const int unit_height = AOMMIN(mu_blocks_high + idy, mi_height);
685         const int unit_width = AOMMIN(mu_blocks_wide + idx, mi_width);
686         for (blk_row = idy; blk_row < unit_height; blk_row += bh) {
687           for (blk_col = idx; blk_col < unit_width; blk_col += bw) {
688             encode_block_inter(plane, block, blk_row, blk_col, plane_bsize,
689                                max_tx_size, &arg, dry_run);
690             block += step;
691           }
692         }
693       }
694     }
695   }
696 }
697 
encode_block_intra_and_set_context(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)698 static void encode_block_intra_and_set_context(int plane, int block,
699                                                int blk_row, int blk_col,
700                                                BLOCK_SIZE plane_bsize,
701                                                TX_SIZE tx_size, void *arg) {
702   av1_encode_block_intra(plane, block, blk_row, blk_col, plane_bsize, tx_size,
703                          arg);
704 
705   struct encode_b_args *const args = arg;
706   MACROBLOCK *x = args->x;
707   ENTROPY_CONTEXT *a = &args->ta[blk_col];
708   ENTROPY_CONTEXT *l = &args->tl[blk_row];
709   av1_set_txb_context(x, plane, block, tx_size, a, l);
710 }
711 
av1_encode_block_intra(int plane,int block,int blk_row,int blk_col,BLOCK_SIZE plane_bsize,TX_SIZE tx_size,void * arg)712 void av1_encode_block_intra(int plane, int block, int blk_row, int blk_col,
713                             BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
714                             void *arg) {
715   struct encode_b_args *const args = arg;
716   const AV1_COMP *const cpi = args->cpi;
717   const AV1_COMMON *const cm = &cpi->common;
718   MACROBLOCK *const x = args->x;
719   MACROBLOCKD *const xd = &x->e_mbd;
720   struct macroblock_plane *const p = &x->plane[plane];
721   struct macroblockd_plane *const pd = &xd->plane[plane];
722   tran_low_t *dqcoeff = p->dqcoeff + BLOCK_OFFSET(block);
723   PLANE_TYPE plane_type = get_plane_type(plane);
724   uint16_t *eob = &p->eobs[block];
725   const int dst_stride = pd->dst.stride;
726   uint8_t *dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << MI_SIZE_LOG2];
727   int dummy_rate_cost = 0;
728 
729   av1_predict_intra_block_facade(cm, xd, plane, blk_col, blk_row, tx_size);
730 
731   TX_TYPE tx_type = DCT_DCT;
732   const int bw = mi_size_wide[plane_bsize];
733   if (plane == 0 && is_blk_skip(x->txfm_search_info.blk_skip, plane,
734                                 blk_row * bw + blk_col)) {
735     *eob = 0;
736     p->txb_entropy_ctx[block] = 0;
737   } else {
738     av1_subtract_txb(x, plane, plane_bsize, blk_col, blk_row, tx_size);
739 
740     const ENTROPY_CONTEXT *a = &args->ta[blk_col];
741     const ENTROPY_CONTEXT *l = &args->tl[blk_row];
742     tx_type = av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
743                               cm->features.reduced_tx_set_used);
744     TxfmParam txfm_param;
745     QUANT_PARAM quant_param;
746     const int use_trellis =
747         is_trellis_used(args->enable_optimize_b, args->dry_run);
748     int quant_idx;
749     if (use_trellis)
750       quant_idx = AV1_XFORM_QUANT_FP;
751     else
752       quant_idx =
753           USE_B_QUANT_NO_TRELLIS ? AV1_XFORM_QUANT_B : AV1_XFORM_QUANT_FP;
754 
755     av1_setup_xform(cm, x, tx_size, tx_type, &txfm_param);
756     av1_setup_quant(tx_size, use_trellis, quant_idx,
757                     cpi->oxcf.q_cfg.quant_b_adapt, &quant_param);
758     av1_setup_qmatrix(&cm->quant_params, xd, plane, tx_size, tx_type,
759                       &quant_param);
760 
761     av1_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, &txfm_param,
762                     &quant_param);
763 
764     // Whether trellis or dropout optimization is required for key frames and
765     // intra frames.
766     const bool do_trellis = (frame_is_intra_only(cm) &&
767                              (KEY_BLOCK_OPT_TYPE == TRELLIS_OPT ||
768                               KEY_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT)) ||
769                             (!frame_is_intra_only(cm) &&
770                              (INTRA_BLOCK_OPT_TYPE == TRELLIS_OPT ||
771                               INTRA_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT));
772     const bool do_dropout = (frame_is_intra_only(cm) &&
773                              (KEY_BLOCK_OPT_TYPE == DROPOUT_OPT ||
774                               KEY_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT)) ||
775                             (!frame_is_intra_only(cm) &&
776                              (INTRA_BLOCK_OPT_TYPE == DROPOUT_OPT ||
777                               INTRA_BLOCK_OPT_TYPE == TRELLIS_DROPOUT_OPT));
778 
779     if (quant_param.use_optimize_b && do_trellis) {
780       TXB_CTX txb_ctx;
781       get_txb_ctx(plane_bsize, tx_size, plane, a, l, &txb_ctx);
782       av1_optimize_b(args->cpi, x, plane, block, tx_size, tx_type, &txb_ctx,
783                      &dummy_rate_cost);
784     }
785     if (do_dropout) {
786       av1_dropout_qcoeff(x, plane, block, tx_size, tx_type,
787                          cm->quant_params.base_qindex);
788     }
789   }
790 
791   if (*eob) {
792     av1_inverse_transform_block(xd, dqcoeff, plane, tx_type, tx_size, dst,
793                                 dst_stride, *eob,
794                                 cm->features.reduced_tx_set_used);
795   }
796 
797   // TODO(jingning): Temporarily disable txk_type check for eob=0 case.
798   // It is possible that certain collision in hash index would cause
799   // the assertion failure. To further optimize the rate-distortion
800   // performance, we need to re-visit this part and enable this assert
801   // again.
802   if (*eob == 0 && plane == 0) {
803 #if 0
804     if (args->cpi->oxcf.q_cfg.aq_mode == NO_AQ
805         && args->cpi->oxcf.q_cfg.deltaq_mode == NO_DELTA_Q) {
806       assert(xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col)] ==
807           DCT_DCT);
808     }
809 #endif
810     update_txk_array(xd, blk_row, blk_col, tx_size, DCT_DCT);
811   }
812 
813   // For intra mode, skipped blocks are so rare that transmitting skip=1 is
814   // very expensive.
815   *(args->skip) = 0;
816 
817   if (plane == AOM_PLANE_Y && xd->cfl.store_y) {
818     cfl_store_tx(xd, blk_row, blk_col, tx_size, plane_bsize);
819   }
820 }
821 
av1_encode_intra_block_plane(const struct AV1_COMP * cpi,MACROBLOCK * x,BLOCK_SIZE bsize,int plane,RUN_TYPE dry_run,TRELLIS_OPT_TYPE enable_optimize_b)822 void av1_encode_intra_block_plane(const struct AV1_COMP *cpi, MACROBLOCK *x,
823                                   BLOCK_SIZE bsize, int plane, RUN_TYPE dry_run,
824                                   TRELLIS_OPT_TYPE enable_optimize_b) {
825   assert(bsize < BLOCK_SIZES_ALL);
826   const MACROBLOCKD *const xd = &x->e_mbd;
827   if (plane && !xd->is_chroma_ref) return;
828 
829   const struct macroblockd_plane *const pd = &xd->plane[plane];
830   const int ss_x = pd->subsampling_x;
831   const int ss_y = pd->subsampling_y;
832   ENTROPY_CONTEXT ta[MAX_MIB_SIZE] = { 0 };
833   ENTROPY_CONTEXT tl[MAX_MIB_SIZE] = { 0 };
834   struct encode_b_args arg = { cpi, x,  NULL,    &(xd->mi[0]->skip_txfm),
835                                ta,  tl, dry_run, enable_optimize_b };
836   const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, ss_x, ss_y);
837   if (enable_optimize_b) {
838     av1_get_entropy_contexts(plane_bsize, pd, ta, tl);
839   }
840   av1_foreach_transformed_block_in_plane(
841       xd, plane_bsize, plane, encode_block_intra_and_set_context, &arg);
842 }
843