Coverage Report

Created: 2026-04-01 07:49

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