encodemb.c 43.8 KB
Newer Older
Jingning Han's avatar
Jingning Han committed
1
/*
Yaowu Xu's avatar
Yaowu Xu committed
2
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
Jingning Han's avatar
Jingning Han committed
3
 *
Yaowu Xu's avatar
Yaowu Xu committed
4
5
6
7
8
9
 * This source code is subject to the terms of the BSD 2 Clause License and
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
 * was not distributed with this source code in the LICENSE file, you can
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
 * Media Patent License 1.0 was not distributed with this source code in the
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
Jingning Han's avatar
Jingning Han committed
10
11
 */

Yaowu Xu's avatar
Yaowu Xu committed
12
13
14
#include "./av1_rtcd.h"
#include "./aom_config.h"
#include "./aom_dsp_rtcd.h"
Jingning Han's avatar
Jingning Han committed
15

16
#include "aom_dsp/bitwriter.h"
17
#include "aom_dsp/quantize.h"
Yaowu Xu's avatar
Yaowu Xu committed
18
#include "aom_mem/aom_mem.h"
19
#include "aom_ports/mem.h"
Jingning Han's avatar
Jingning Han committed
20

21
22
23
24
#include "av1/common/idct.h"
#include "av1/common/reconinter.h"
#include "av1/common/reconintra.h"
#include "av1/common/scan.h"
Jingning Han's avatar
Jingning Han committed
25

26
#include "av1/encoder/av1_quantize.h"
27
#include "av1/encoder/encodemb.h"
28
29
30
#if CONFIG_LV_MAP
#include "av1/encoder/encodetxb.h"
#endif
31
32
33
#include "av1/encoder/hybrid_fwd_txfm.h"
#include "av1/encoder/rd.h"
#include "av1/encoder/tokenize.h"
Jingning Han's avatar
Jingning Han committed
34

35
36
37
38
39
40
#if CONFIG_PVQ
#include "av1/encoder/encint.h"
#include "av1/common/partition.h"
#include "av1/encoder/pvq_encoder.h"
#endif

41
42
43
// Check if one needs to use c version subtraction.
static int check_subtract_block_size(int w, int h) { return w < 4 || h < 4; }

Angie Chiang's avatar
Angie Chiang committed
44
45
46
47
static void subtract_block(const MACROBLOCKD *xd, 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) {
48
#if !CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
49
50
  (void)xd;
#endif
Jingning Han's avatar
Jingning Han committed
51

Angie Chiang's avatar
Angie Chiang committed
52
  if (check_subtract_block_size(rows, cols)) {
53
#if CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
54
55
56
    if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
      aom_highbd_subtract_block_c(rows, cols, diff, diff_stride, src8,
                                  src_stride, pred8, pred_stride, xd->bd);
57
58
      return;
    }
59
#endif  // CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
60
61
    aom_subtract_block_c(rows, cols, diff, diff_stride, src8, src_stride, pred8,
                         pred_stride);
62
63
64
65

    return;
  }

66
#if CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
67
68
69
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
    aom_highbd_subtract_block(rows, cols, diff, diff_stride, src8, src_stride,
                              pred8, pred_stride, xd->bd);
Jingning Han's avatar
Jingning Han committed
70
71
    return;
  }
72
#endif  // CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
73
74
75
76
  aom_subtract_block(rows, cols, diff, diff_stride, src8, src_stride, pred8,
                     pred_stride);
}

Angie Chiang's avatar
Angie Chiang committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
void av1_subtract_txb(MACROBLOCK *x, int plane, BLOCK_SIZE plane_bsize,
                      int blk_col, int blk_row, TX_SIZE tx_size) {
  MACROBLOCKD *const xd = &x->e_mbd;
  struct macroblock_plane *const p = &x->plane[plane];
  const struct macroblockd_plane *const pd = &x->e_mbd.plane[plane];
  const int diff_stride = block_size_wide[plane_bsize];
  const int src_stride = p->src.stride;
  const int dst_stride = pd->dst.stride;
  const int tx1d_width = tx_size_wide[tx_size];
  const int tx1d_height = tx_size_high[tx_size];
  uint8_t *dst =
      &pd->dst.buf[(blk_row * dst_stride + blk_col) << tx_size_wide_log2[0]];
  uint8_t *src =
      &p->src.buf[(blk_row * src_stride + blk_col) << tx_size_wide_log2[0]];
  int16_t *src_diff =
      &p->src_diff[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
  subtract_block(xd, tx1d_height, tx1d_width, src_diff, diff_stride, src,
                 src_stride, dst, dst_stride);
}

Angie Chiang's avatar
Angie Chiang committed
97
98
99
100
101
102
103
104
105
106
void av1_subtract_plane(MACROBLOCK *x, BLOCK_SIZE bsize, int plane) {
  struct macroblock_plane *const p = &x->plane[plane];
  const struct macroblockd_plane *const pd = &x->e_mbd.plane[plane];
  const BLOCK_SIZE plane_bsize = get_plane_block_size(bsize, pd);
  const int bw = block_size_wide[plane_bsize];
  const int bh = block_size_high[plane_bsize];
  const MACROBLOCKD *xd = &x->e_mbd;

  subtract_block(xd, bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
                 pd->dst.buf, pd->dst.stride);
Jingning Han's avatar
Jingning Han committed
107
108
}

Yaowu Xu's avatar
Yaowu Xu committed
109
typedef struct av1_token_state {
110
  int64_t error;
111
112
  int rate;
  int16_t next;
113
114
115
  int16_t token;
  tran_low_t qc;
  tran_low_t dqc;
116
  uint8_t best_index;
Yaowu Xu's avatar
Yaowu Xu committed
117
} av1_token_state;
Jingning Han's avatar
Jingning Han committed
118

119
120
// These numbers are empirically obtained.
static const int plane_rd_mult[REF_TYPES][PLANE_TYPES] = {
Thomas Davies's avatar
Thomas Davies committed
121
122
123
#if CONFIG_EC_ADAPT
  { 10, 7 }, { 8, 5 },
#else
124
  { 10, 6 }, { 8, 5 },
Thomas Davies's avatar
Thomas Davies committed
125
#endif
126
};
Jingning Han's avatar
Jingning Han committed
127

128
129
130
131
132
#define UPDATE_RD_COST()                             \
  {                                                  \
    rd_cost0 = RDCOST(rdmult, rddiv, rate0, error0); \
    rd_cost1 = RDCOST(rdmult, rddiv, rate1, error1); \
  }
Jingning Han's avatar
Jingning Han committed
133

134
135
136
137
138
139
140
141
142
143
144
static inline int64_t get_token_bit_costs(
    unsigned int token_costs[2][COEFF_CONTEXTS][ENTROPY_TOKENS], int skip_eob,
    int ctx, int token) {
#if CONFIG_NEW_TOKENSET
  (void)skip_eob;
  return token_costs[token == ZERO_TOKEN || token == EOB_TOKEN][ctx][token];
#else
  return token_costs[skip_eob][ctx][token];
#endif
}

Angie Chiang's avatar
Angie Chiang committed
145
146
int av1_optimize_b(const AV1_COMMON *cm, MACROBLOCK *mb, int plane, int block,
                   TX_SIZE tx_size, int ctx) {
147
#if !CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
148
149
150
151
  MACROBLOCKD *const xd = &mb->e_mbd;
  struct macroblock_plane *const p = &mb->plane[plane];
  struct macroblockd_plane *const pd = &xd->plane[plane];
  const int ref = is_inter_block(&xd->mi[0]->mbmi);
Yaowu Xu's avatar
Yaowu Xu committed
152
  av1_token_state tokens[MAX_TX_SQUARE + 1][2];
153
  uint8_t token_cache[MAX_TX_SQUARE];
154
  const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
Jingning Han's avatar
Jingning Han committed
155
156
157
  tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
  tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
  const int eob = p->eobs[block];
158
  const PLANE_TYPE plane_type = pd->plane_type;
159
  const int default_eob = tx_size_2d[tx_size];
160
161
  const int16_t *const dequant_ptr = pd->dequant;
  const uint8_t *const band_translate = get_band_translate(tx_size);
162
  TX_TYPE tx_type = get_tx_type(plane_type, xd, block, tx_size);
163
  const SCAN_ORDER *const scan_order =
Angie Chiang's avatar
Angie Chiang committed
164
      get_scan(cm, tx_size, tx_type, is_inter_block(&xd->mi[0]->mbmi));
165
166
  const int16_t *const scan = scan_order->scan;
  const int16_t *const nb = scan_order->neighbors;
Thomas Davies's avatar
Thomas Davies committed
167
  int dqv;
168
  const int shift = get_tx_scale(tx_size);
169
170
#if CONFIG_AOM_QM
  int seg_id = xd->mi[0]->mbmi.segment_id;
171
  const qm_val_t *iqmatrix = pd->seg_iqmatrix[seg_id][!ref][tx_size];
172
#endif
173
#if CONFIG_NEW_QUANT
174
  int dq = get_dq_profile_from_ctx(mb->qindex, ctx, ref, plane_type);
175
  const dequant_val_type_nuq *dequant_val = pd->dequant_val_nuq[dq];
176
#elif !CONFIG_AOM_QM
177
  const int dq_step[2] = { dequant_ptr[0] >> shift, dequant_ptr[1] >> shift };
178
#endif  // CONFIG_NEW_QUANT
Jingning Han's avatar
Jingning Han committed
179
  int next = eob, sz = 0;
180
  const int64_t rdmult = (mb->rdmult * plane_rd_mult[ref][plane_type]) >> 1;
hui su's avatar
hui su committed
181
  const int64_t rddiv = mb->rddiv;
Jingning Han's avatar
Jingning Han committed
182
  int64_t rd_cost0, rd_cost1;
183
184
  int rate0, rate1;
  int64_t error0, error1;
Jingning Han's avatar
Jingning Han committed
185
  int16_t t0, t1;
186
187
  int best, band = (eob < default_eob) ? band_translate[eob]
                                       : band_translate[eob - 1];
188
  int pt, i, final_eob;
189
#if CONFIG_HIGHBITDEPTH
190
  const int cat6_bits = av1_get_cat6_extrabits_size(tx_size, xd->bd);
Jingning Han's avatar
Jingning Han committed
191
#else
192
  const int cat6_bits = av1_get_cat6_extrabits_size(tx_size, 8);
Jingning Han's avatar
Jingning Han committed
193
#endif
194
  unsigned int(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
195
      mb->token_costs[txsize_sqr_map[tx_size]][plane_type][ref];
196
197
  const uint16_t *band_counts = &band_count_table[tx_size][band];
  uint16_t band_left = eob - band_cum_count_table[tx_size][band] + 1;
198
199
  int shortcut = 0;
  int next_shortcut = 0;
200

201
  assert((mb->qindex == 0) ^ (xd->lossless[xd->mi[0]->mbmi.segment_id] == 0));
202

203
  token_costs += band;
Jingning Han's avatar
Jingning Han committed
204

205
  assert((!plane_type && !plane) || (plane_type && plane));
Jingning Han's avatar
Jingning Han committed
206
  assert(eob <= default_eob);
207

Jingning Han's avatar
Jingning Han committed
208
209
210
211
212
213
214
215
216
  /* Now set up a Viterbi trellis to evaluate alternative roundings. */
  /* Initialize the sentinel node of the trellis. */
  tokens[eob][0].rate = 0;
  tokens[eob][0].error = 0;
  tokens[eob][0].next = default_eob;
  tokens[eob][0].token = EOB_TOKEN;
  tokens[eob][0].qc = 0;
  tokens[eob][1] = tokens[eob][0];

217
218
  for (i = 0; i < eob; i++) {
    const int rc = scan[i];
219
    tokens[i][0].rate = av1_get_token_cost(qcoeff[rc], &t0, cat6_bits);
220
    tokens[i][0].token = t0;
Yaowu Xu's avatar
Yaowu Xu committed
221
    token_cache[rc] = av1_pt_energy_class[t0];
222
  }
Jingning Han's avatar
Jingning Han committed
223
224

  for (i = eob; i-- > 0;) {
225
226
    int base_bits, dx;
    int64_t d2;
Jingning Han's avatar
Jingning Han committed
227
    const int rc = scan[i];
Thomas Davies's avatar
Thomas Davies committed
228
    int x = qcoeff[rc];
229
230
#if CONFIG_AOM_QM
    int iwt = iqmatrix[rc];
Thomas Davies's avatar
Thomas Davies committed
231
232
233
234
    dqv = dequant_ptr[rc != 0];
    dqv = ((iwt * (int)dqv) + (1 << (AOM_QM_BITS - 1))) >> AOM_QM_BITS;
#else
    dqv = dequant_ptr[rc != 0];
235
#endif
236
    next_shortcut = shortcut;
237

Jingning Han's avatar
Jingning Han committed
238
    /* Only add a trellis state for non-zero coefficients. */
239
    if (UNLIKELY(x)) {
Jingning Han's avatar
Jingning Han committed
240
241
242
243
244
      error0 = tokens[next][0].error;
      error1 = tokens[next][1].error;
      /* Evaluate the first possibility for this state. */
      rate0 = tokens[next][0].rate;
      rate1 = tokens[next][1].rate;
245

246
247
248
249
      if (next_shortcut) {
        /* Consider both possible successor states. */
        if (next < default_eob) {
          pt = get_coef_context(nb, token_cache, i + 1);
250
251
252
253
          rate0 +=
              get_token_bit_costs(*token_costs, 0, pt, tokens[next][0].token);
          rate1 +=
              get_token_bit_costs(*token_costs, 0, pt, tokens[next][1].token);
254
255
256
257
258
259
260
        }
        UPDATE_RD_COST();
        /* And pick the best. */
        best = rd_cost1 < rd_cost0;
      } else {
        if (next < default_eob) {
          pt = get_coef_context(nb, token_cache, i + 1);
261
262
          rate0 +=
              get_token_bit_costs(*token_costs, 0, pt, tokens[next][0].token);
263
264
        }
        best = 0;
Jingning Han's avatar
Jingning Han committed
265
      }
266
267

      dx = (dqcoeff[rc] - coeff[rc]) * (1 << shift);
268
#if CONFIG_HIGHBITDEPTH
Jingning Han's avatar
Jingning Han committed
269
270
271
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
        dx >>= xd->bd - 8;
      }
272
#endif  // CONFIG_HIGHBITDEPTH
273
      d2 = (int64_t)dx * dx;
274
      tokens[i][0].rate += (best ? rate1 : rate0);
Jingning Han's avatar
Jingning Han committed
275
276
277
      tokens[i][0].error = d2 + (best ? error1 : error0);
      tokens[i][0].next = next;
      tokens[i][0].qc = x;
278
      tokens[i][0].dqc = dqcoeff[rc];
279
      tokens[i][0].best_index = best;
Jingning Han's avatar
Jingning Han committed
280
281
282
283
284

      /* Evaluate the second possibility for this state. */
      rate0 = tokens[next][0].rate;
      rate1 = tokens[next][1].rate;

285
      // The threshold of 3 is empirically obtained.
286
      if (UNLIKELY(abs(x) > 3)) {
287
288
        shortcut = 0;
      } else {
289
#if CONFIG_NEW_QUANT
Thomas Davies's avatar
Thomas Davies committed
290
        shortcut = ((av1_dequant_abscoeff_nuq(abs(x), dqv,
Yaowu Xu's avatar
Yaowu Xu committed
291
                                              dequant_val[band_translate[i]]) >
292
                     (abs(coeff[rc]) << shift)) &&
Thomas Davies's avatar
Thomas Davies committed
293
                    (av1_dequant_abscoeff_nuq(abs(x) - 1, dqv,
Yaowu Xu's avatar
Yaowu Xu committed
294
                                              dequant_val[band_translate[i]]) <
295
                     (abs(coeff[rc]) << shift)));
296
297
298
299
300
301
302
303
#else  // CONFIG_NEW_QUANT
#if CONFIG_AOM_QM
        if ((abs(x) * dequant_ptr[rc != 0] * iwt >
             ((abs(coeff[rc]) << shift) << AOM_QM_BITS)) &&
            (abs(x) * dequant_ptr[rc != 0] * iwt <
             (((abs(coeff[rc]) << shift) + dequant_ptr[rc != 0])
              << AOM_QM_BITS)))
#else
304
        if ((abs(x) * dequant_ptr[rc != 0] > (abs(coeff[rc]) << shift)) &&
305
306
            (abs(x) * dequant_ptr[rc != 0] <
             (abs(coeff[rc]) << shift) + dequant_ptr[rc != 0]))
307
#endif  // CONFIG_AOM_QM
308
309
310
          shortcut = 1;
        else
          shortcut = 0;
311
#endif  // CONFIG_NEW_QUANT
312
      }
Jingning Han's avatar
Jingning Han committed
313
314
315
316

      if (shortcut) {
        sz = -(x < 0);
        x -= 2 * sz + 1;
317
318
319
      } else {
        tokens[i][1] = tokens[i][0];
        next = i;
320

321
        if (UNLIKELY(!(--band_left))) {
322
323
324
325
          --band_counts;
          band_left = *band_counts;
          --token_costs;
        }
326
        continue;
Jingning Han's avatar
Jingning Han committed
327
328
329
330
331
332
333
334
335
      }

      /* Consider both possible successor states. */
      if (!x) {
        /* If we reduced this coefficient to zero, check to see if
         *  we need to move the EOB back here.
         */
        t0 = tokens[next][0].token == EOB_TOKEN ? EOB_TOKEN : ZERO_TOKEN;
        t1 = tokens[next][1].token == EOB_TOKEN ? EOB_TOKEN : ZERO_TOKEN;
336
        base_bits = 0;
Jingning Han's avatar
Jingning Han committed
337
      } else {
338
        base_bits = av1_get_token_cost(x, &t0, cat6_bits);
Jingning Han's avatar
Jingning Han committed
339
340
        t1 = t0;
      }
341
342

      if (next_shortcut) {
343
        if (LIKELY(next < default_eob)) {
344
          if (t0 != EOB_TOKEN) {
Yaowu Xu's avatar
Yaowu Xu committed
345
            token_cache[rc] = av1_pt_energy_class[t0];
346
            pt = get_coef_context(nb, token_cache, i + 1);
347
348
            rate0 += get_token_bit_costs(*token_costs, !x, pt,
                                         tokens[next][0].token);
349
350
          }
          if (t1 != EOB_TOKEN) {
Yaowu Xu's avatar
Yaowu Xu committed
351
            token_cache[rc] = av1_pt_energy_class[t1];
352
            pt = get_coef_context(nb, token_cache, i + 1);
353
354
            rate1 += get_token_bit_costs(*token_costs, !x, pt,
                                         tokens[next][1].token);
355
356
357
358
359
360
361
362
363
          }
        }

        UPDATE_RD_COST();
        /* And pick the best. */
        best = rd_cost1 < rd_cost0;
      } else {
        // The two states in next stage are identical.
        if (next < default_eob && t0 != EOB_TOKEN) {
Yaowu Xu's avatar
Yaowu Xu committed
364
          token_cache[rc] = av1_pt_energy_class[t0];
Jingning Han's avatar
Jingning Han committed
365
          pt = get_coef_context(nb, token_cache, i + 1);
366
367
          rate0 +=
              get_token_bit_costs(*token_costs, !x, pt, tokens[next][0].token);
Jingning Han's avatar
Jingning Han committed
368
        }
369
        best = 0;
Jingning Han's avatar
Jingning Han committed
370
371
      }

372
#if CONFIG_NEW_QUANT
Thomas Davies's avatar
Thomas Davies committed
373
      dx = av1_dequant_coeff_nuq(x, dqv, dequant_val[band_translate[i]]) -
374
           (coeff[rc] << shift);
375
#if CONFIG_HIGHBITDEPTH
hui su's avatar
hui su committed
376
377
378
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
        dx >>= xd->bd - 8;
      }
379
#endif  // CONFIG_HIGHBITDEPTH
380
#else   // CONFIG_NEW_QUANT
381
#if CONFIG_HIGHBITDEPTH
hui su's avatar
hui su committed
382
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
Thomas Davies's avatar
Thomas Davies committed
383
        dx -= ((dqv >> (xd->bd - 8)) + sz) ^ sz;
hui su's avatar
hui su committed
384
      } else {
Thomas Davies's avatar
Thomas Davies committed
385
        dx -= (dqv + sz) ^ sz;
hui su's avatar
hui su committed
386
387
      }
#else
Thomas Davies's avatar
Thomas Davies committed
388
      dx -= (dqv + sz) ^ sz;
389
#endif  // CONFIG_HIGHBITDEPTH
390
#endif  // CONFIG_NEW_QUANT
391
      d2 = (int64_t)dx * dx;
hui su's avatar
hui su committed
392

Jingning Han's avatar
Jingning Han committed
393
394
395
396
397
      tokens[i][1].rate = base_bits + (best ? rate1 : rate0);
      tokens[i][1].error = d2 + (best ? error1 : error0);
      tokens[i][1].next = next;
      tokens[i][1].token = best ? t1 : t0;
      tokens[i][1].qc = x;
398
399

      if (x) {
400
#if CONFIG_NEW_QUANT
Yaowu Xu's avatar
Yaowu Xu committed
401
        tokens[i][1].dqc = av1_dequant_abscoeff_nuq(
Thomas Davies's avatar
Thomas Davies committed
402
            abs(x), dqv, dequant_val[band_translate[i]]);
403
404
405
        tokens[i][1].dqc = shift ? ROUND_POWER_OF_TWO(tokens[i][1].dqc, shift)
                                 : tokens[i][1].dqc;
        if (sz) tokens[i][1].dqc = -tokens[i][1].dqc;
406
#else
407
408
409
410
// The 32x32 transform coefficient uses half quantization step size.
// Account for the rounding difference in the dequantized coefficeint
// value when the quantization index is dropped from an even number
// to an odd number.
Thomas Davies's avatar
Thomas Davies committed
411
412
413
414
415
416
417

#if CONFIG_AOM_QM
        tran_low_t offset = dqv >> shift;
#else
        tran_low_t offset = dq_step[rc != 0];
#endif
        if (shift & x) offset += (dqv & 0x01);
418
419
420
421
422

        if (sz == 0)
          tokens[i][1].dqc = dqcoeff[rc] - offset;
        else
          tokens[i][1].dqc = dqcoeff[rc] + offset;
423
#endif  // CONFIG_NEW_QUANT
424
425
426
427
      } else {
        tokens[i][1].dqc = 0;
      }

428
      tokens[i][1].best_index = best;
Jingning Han's avatar
Jingning Han committed
429
430
431
432
433
434
435
436
      /* Finally, make this the new head of the trellis. */
      next = i;
    } else {
      /* There's no choice to make for a zero coefficient, so we don't
       *  add a new trellis node, but we do need to update the costs.
       */
      t0 = tokens[next][0].token;
      t1 = tokens[next][1].token;
437
      pt = get_coef_context(nb, token_cache, i + 1);
Jingning Han's avatar
Jingning Han committed
438
439
      /* Update the cost of each path if we're past the EOB token. */
      if (t0 != EOB_TOKEN) {
440
        tokens[next][0].rate += get_token_bit_costs(*token_costs, 1, pt, t0);
Jingning Han's avatar
Jingning Han committed
441
442
443
        tokens[next][0].token = ZERO_TOKEN;
      }
      if (t1 != EOB_TOKEN) {
444
        tokens[next][1].rate += get_token_bit_costs(*token_costs, 1, pt, t1);
Jingning Han's avatar
Jingning Han committed
445
446
        tokens[next][1].token = ZERO_TOKEN;
      }
447
      tokens[i][0].best_index = tokens[i][1].best_index = 0;
448
      shortcut = (tokens[next][0].rate != tokens[next][1].rate);
Jingning Han's avatar
Jingning Han committed
449
450
      /* Don't update next, because we didn't add a new node. */
    }
451

452
    if (UNLIKELY(!(--band_left))) {
453
454
455
456
      --band_counts;
      band_left = *band_counts;
      --token_costs;
    }
Jingning Han's avatar
Jingning Han committed
457
458
459
460
461
462
463
464
465
  }

  /* Now pick the best path through the whole trellis. */
  rate0 = tokens[next][0].rate;
  rate1 = tokens[next][1].rate;
  error0 = tokens[next][0].error;
  error1 = tokens[next][1].error;
  t0 = tokens[next][0].token;
  t1 = tokens[next][1].token;
466
467
  rate0 += get_token_bit_costs(*token_costs, 0, ctx, t0);
  rate1 += get_token_bit_costs(*token_costs, 0, ctx, t1);
Jingning Han's avatar
Jingning Han committed
468
469
  UPDATE_RD_COST();
  best = rd_cost1 < rd_cost0;
470

Jingning Han's avatar
Jingning Han committed
471
  final_eob = -1;
472

Jingning Han's avatar
Jingning Han committed
473
474
475
  for (i = next; i < eob; i = next) {
    const int x = tokens[i][best].qc;
    const int rc = scan[i];
476
    if (x) final_eob = i;
Jingning Han's avatar
Jingning Han committed
477
    qcoeff[rc] = x;
478
479
    dqcoeff[rc] = tokens[i][best].dqc;

Jingning Han's avatar
Jingning Han committed
480
    next = tokens[i][best].next;
481
    best = tokens[i][best].best_index;
Jingning Han's avatar
Jingning Han committed
482
483
484
485
  }
  final_eob++;

  mb->plane[plane].eobs[block] = final_eob;
486
  assert(final_eob <= default_eob);
Jingning Han's avatar
Jingning Han committed
487
  return final_eob;
488
489
490
491
492
493
494
#else   // !CONFIG_PVQ
  (void)cm;
  (void)tx_size;
  (void)ctx;
  struct macroblock_plane *const p = &mb->plane[plane];
  return p->eobs[block];
#endif  // !CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
495
496
}

Thomas Daede's avatar
Thomas Daede committed
497
#if !CONFIG_PVQ
498
#if CONFIG_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
499
500
typedef enum QUANT_FUNC {
  QUANT_FUNC_LOWBD = 0,
501
  QUANT_FUNC_HIGHBD = 1,
502
  QUANT_FUNC_TYPES = 2
Angie Chiang's avatar
Angie Chiang committed
503
504
} QUANT_FUNC;

505
506
static AV1_QUANT_FACADE
    quant_func_list[AV1_XFORM_QUANT_TYPES][QUANT_FUNC_TYPES] = {
507
#if !CONFIG_NEW_QUANT
508
      { av1_quantize_fp_facade, av1_highbd_quantize_fp_facade },
Yaowu Xu's avatar
Yaowu Xu committed
509
510
      { av1_quantize_b_facade, av1_highbd_quantize_b_facade },
      { av1_quantize_dc_facade, av1_highbd_quantize_dc_facade },
511
#else   // !CONFIG_NEW_QUANT
512
513
514
      { av1_quantize_fp_nuq_facade, av1_highbd_quantize_fp_nuq_facade },
      { av1_quantize_b_nuq_facade, av1_highbd_quantize_b_nuq_facade },
      { av1_quantize_dc_nuq_facade, av1_highbd_quantize_dc_nuq_facade },
515
#endif  // !CONFIG_NEW_QUANT
516
517
      { NULL, NULL }
    };
518

Thomas Daede's avatar
Thomas Daede committed
519
#else
520

Angie Chiang's avatar
Angie Chiang committed
521
522
typedef enum QUANT_FUNC {
  QUANT_FUNC_LOWBD = 0,
523
  QUANT_FUNC_TYPES = 1
Angie Chiang's avatar
Angie Chiang committed
524
} QUANT_FUNC;
Angie Chiang's avatar
Angie Chiang committed
525

526
527
static AV1_QUANT_FACADE quant_func_list[AV1_XFORM_QUANT_TYPES]
                                       [QUANT_FUNC_TYPES] = {
528
#if !CONFIG_NEW_QUANT
clang-format's avatar
clang-format committed
529
530
531
                                         { av1_quantize_fp_facade },
                                         { av1_quantize_b_facade },
                                         { av1_quantize_dc_facade },
532
#else   // !CONFIG_NEW_QUANT
533
534
535
                                         { av1_quantize_fp_nuq_facade },
                                         { av1_quantize_b_nuq_facade },
                                         { av1_quantize_dc_nuq_facade },
536
#endif  // !CONFIG_NEW_QUANT
clang-format's avatar
clang-format committed
537
538
                                         { NULL }
                                       };
539
#endif  // CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
540
#endif  // CONFIG_PVQ
541

Angie Chiang's avatar
Angie Chiang committed
542
543
void av1_xform_quant(const AV1_COMMON *cm, MACROBLOCK *x, int plane, int block,
                     int blk_row, int blk_col, BLOCK_SIZE plane_bsize,
544
545
                     TX_SIZE tx_size, int ctx,
                     AV1_XFORM_QUANT xform_quant_idx) {
Jingning Han's avatar
Jingning Han committed
546
  MACROBLOCKD *const xd = &x->e_mbd;
547
  MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
Yushin Cho's avatar
Yushin Cho committed
548
#if !(CONFIG_PVQ || CONFIG_DAALA_DIST)
Jingning Han's avatar
Jingning Han committed
549
550
  const struct macroblock_plane *const p = &x->plane[plane];
  const struct macroblockd_plane *const pd = &xd->plane[plane];
551
552
553
554
#else
  struct macroblock_plane *const p = &x->plane[plane];
  struct macroblockd_plane *const pd = &xd->plane[plane];
#endif
555
  PLANE_TYPE plane_type = get_plane_type(plane);
556
  TX_TYPE tx_type = get_tx_type(plane_type, xd, block, tx_size);
557
  const int is_inter = is_inter_block(mbmi);
Angie Chiang's avatar
Angie Chiang committed
558
  const SCAN_ORDER *const scan_order = get_scan(cm, tx_size, tx_type, is_inter);
Jingning Han's avatar
Jingning Han committed
559
560
561
562
  tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
  tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
  tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
  uint16_t *const eob = &p->eobs[block];
563
  const int diff_stride = block_size_wide[plane_bsize];
564
#if CONFIG_AOM_QM
565
  int seg_id = mbmi->segment_id;
566
567
  const qm_val_t *qmatrix = pd->seg_qmatrix[seg_id][!is_inter][tx_size];
  const qm_val_t *iqmatrix = pd->seg_iqmatrix[seg_id][!is_inter][tx_size];
568
#endif
Angie Chiang's avatar
Angie Chiang committed
569
570

  FWD_TXFM_PARAM fwd_txfm_param;
571

Yushin Cho's avatar
Yushin Cho committed
572
573
574
575
576
577
578
579
#if CONFIG_PVQ || CONFIG_DAALA_DIST
  uint8_t *dst;
  int16_t *pred;
  const int dst_stride = pd->dst.stride;
  int tx_blk_size;
  int i, j;
#endif

580
581
#if !CONFIG_PVQ
  const int tx2d_size = tx_size_2d[tx_size];
582
  QUANT_PARAM qparam;
583
584
  const int16_t *src_diff;

585
586
  src_diff =
      &p->src_diff[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
587
  qparam.log_scale = get_tx_scale(tx_size);
588
589
590
591
592
593
594
595
#if CONFIG_NEW_QUANT
  qparam.tx_size = tx_size;
  qparam.dq = get_dq_profile_from_ctx(x->qindex, ctx, is_inter, plane_type);
#endif  // CONFIG_NEW_QUANT
#if CONFIG_AOM_QM
  qparam.qmatrix = qmatrix;
  qparam.iqmatrix = iqmatrix;
#endif  // CONFIG_AOM_QM
596
597
598
599
#else
  tran_low_t *ref_coeff = BLOCK_OFFSET(pd->pvq_ref_coeff, block);
  int skip = 1;
  PVQ_INFO *pvq_info = NULL;
Yushin Cho's avatar
Yushin Cho committed
600
601
602
  uint8_t *src;
  int16_t *src_int16;
  const int src_stride = p->src.stride;
603

604
  (void)ctx;
605
606
607
608
609
610
611
  (void)scan_order;
  (void)qcoeff;

  if (x->pvq_coded) {
    assert(block < MAX_PVQ_BLOCKS_IN_SB);
    pvq_info = &x->pvq[block][plane];
  }
612
613
614
  src = &p->src.buf[(blk_row * src_stride + blk_col) << tx_size_wide_log2[0]];
  src_int16 =
      &p->src_int16[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
Yushin Cho's avatar
Yushin Cho committed
615
616
617

  // transform block size in pixels
  tx_blk_size = tx_size_wide[tx_size];
618
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
619
620
621
622
623
624
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
    for (j = 0; j < tx_blk_size; j++)
      for (i = 0; i < tx_blk_size; i++)
        src_int16[diff_stride * j + i] =
            CONVERT_TO_SHORTPTR(src)[src_stride * j + i];
  } else {
625
#endif  // CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
626
627
628
    for (j = 0; j < tx_blk_size; j++)
      for (i = 0; i < tx_blk_size; i++)
        src_int16[diff_stride * j + i] = src[src_stride * j + i];
629
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
630
  }
631
#endif  // CONFIG_HIGHBITDEPTH
Yushin Cho's avatar
Yushin Cho committed
632
633
634
635
#endif

#if CONFIG_PVQ || CONFIG_DAALA_DIST
  dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << tx_size_wide_log2[0]];
636
  pred = &pd->pred[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
637
638
639
640

  // transform block size in pixels
  tx_blk_size = tx_size_wide[tx_size];

Thomas Daede's avatar
Thomas Daede committed
641
642
// copy uint8 orig and predicted block to int16 buffer
// in order to use existing VP10 transform functions
643
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
644
645
646
647
648
649
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
    for (j = 0; j < tx_blk_size; j++)
      for (i = 0; i < tx_blk_size; i++)
        pred[diff_stride * j + i] =
            CONVERT_TO_SHORTPTR(dst)[dst_stride * j + i];
  } else {
650
#endif  // CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
651
652
653
    for (j = 0; j < tx_blk_size; j++)
      for (i = 0; i < tx_blk_size; i++)
        pred[diff_stride * j + i] = dst[dst_stride * j + i];
654
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
655
  }
656
#endif  // CONFIG_HIGHBITDEPTH
657
#endif
Yushin Cho's avatar
Yushin Cho committed
658

659
  (void)ctx;
660
661

  fwd_txfm_param.tx_type = tx_type;
Angie Chiang's avatar
Angie Chiang committed
662
  fwd_txfm_param.tx_size = tx_size;
663
  fwd_txfm_param.lossless = xd->lossless[mbmi->segment_id];
Angie Chiang's avatar
Angie Chiang committed
664

Thomas Daede's avatar
Thomas Daede committed
665
#if !CONFIG_PVQ
666
#if CONFIG_HIGHBITDEPTH
667
  fwd_txfm_param.bd = xd->bd;
Jingning Han's avatar
Jingning Han committed
668
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
hui su's avatar
hui su committed
669
    av1_highbd_fwd_txfm(src_diff, coeff, diff_stride, &fwd_txfm_param);
Yaowu Xu's avatar
Yaowu Xu committed
670
    if (xform_quant_idx != AV1_XFORM_QUANT_SKIP_QUANT) {
671
      if (LIKELY(!x->skip_block)) {
672
        quant_func_list[xform_quant_idx][QUANT_FUNC_HIGHBD](
673
            coeff, tx2d_size, p, qcoeff, pd, dqcoeff, eob, scan_order, &qparam);
674
      } else {
Yaowu Xu's avatar
Yaowu Xu committed
675
        av1_quantize_skip(tx2d_size, qcoeff, dqcoeff, eob);
676
677
      }
    }
678
679
680
681
#if CONFIG_LV_MAP
    p->txb_entropy_ctx[block] =
        (uint8_t)av1_get_txb_entropy_context(qcoeff, scan_order, *eob);
#endif  // CONFIG_LV_MAP
682
683
    return;
  }
684
#endif  // CONFIG_HIGHBITDEPTH
hui su's avatar
hui su committed
685
  av1_fwd_txfm(src_diff, coeff, diff_stride, &fwd_txfm_param);
Yaowu Xu's avatar
Yaowu Xu committed
686
  if (xform_quant_idx != AV1_XFORM_QUANT_SKIP_QUANT) {
687
    if (LIKELY(!x->skip_block)) {
688
      quant_func_list[xform_quant_idx][QUANT_FUNC_LOWBD](
689
          coeff, tx2d_size, p, qcoeff, pd, dqcoeff, eob, scan_order, &qparam);
690
    } else {
Yaowu Xu's avatar
Yaowu Xu committed
691
      av1_quantize_skip(tx2d_size, qcoeff, dqcoeff, eob);
Jingning Han's avatar
Jingning Han committed
692
693
    }
  }
694
695
696
697
698
#if CONFIG_LV_MAP
  p->txb_entropy_ctx[block] =
      (uint8_t)av1_get_txb_entropy_context(qcoeff, scan_order, *eob);
#endif  // CONFIG_LV_MAP
#else   // #if !CONFIG_PVQ
Angie Chiang's avatar
Angie Chiang committed
699
  (void)xform_quant_idx;
700
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
701
702
  fwd_txfm_param.bd = xd->bd;
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
hui su's avatar
hui su committed
703
704
    av1_highbd_fwd_txfm(src_int16, coeff, diff_stride, &fwd_txfm_param);
    av1_highbd_fwd_txfm(pred, ref_coeff, diff_stride, &fwd_txfm_param);
Thomas Daede's avatar
Thomas Daede committed
705
706
  } else {
#endif
hui su's avatar
hui su committed
707
708
    av1_fwd_txfm(src_int16, coeff, diff_stride, &fwd_txfm_param);
    av1_fwd_txfm(pred, ref_coeff, diff_stride, &fwd_txfm_param);
709
#if CONFIG_HIGHBITDEPTH
Thomas Daede's avatar
Thomas Daede committed
710
711
  }
#endif
712
713

  // PVQ for inter mode block
714
  if (!x->skip_block) {
ltrudeau's avatar
ltrudeau committed
715
    PVQ_SKIP_TYPE ac_dc_coded =
Thomas Daede's avatar
Thomas Daede committed
716
        av1_pvq_encode_helper(x,
ltrudeau's avatar
ltrudeau committed
717
718
719
720
721
722
723
724
725
726
727
728
                              coeff,        // target original vector
                              ref_coeff,    // reference vector
                              dqcoeff,      // de-quantized vector
                              eob,          // End of Block marker
                              pd->dequant,  // aom's quantizers
                              plane,        // image plane
                              tx_size,      // block size in log_2 - 2
                              tx_type,
                              &x->rate,  // rate measured
                              x->pvq_speed,
                              pvq_info);  // PVQ info for a block
    skip = ac_dc_coded == PVQ_SKIP;
729
  }
730
731
732
733
  x->pvq_skip[plane] = skip;

  if (!skip) mbmi->skip = 0;
#endif  // #if !CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
734
735
}

736
static void encode_block(int plane, int block, int blk_row, int blk_col,
737
                         BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
Jingning Han's avatar
Jingning Han committed
738
  struct encode_b_args *const args = arg;
Angie Chiang's avatar
Angie Chiang committed
739
  AV1_COMMON *cm = args->cm;
Jingning Han's avatar
Jingning Han committed
740
741
  MACROBLOCK *const x = args->x;
  MACROBLOCKD *const xd = &x->e_mbd;
742
  int ctx;
Jingning Han's avatar
Jingning Han committed
743
744
745
746
  struct macroblock_plane *const p = &x->plane[plane];
  struct macroblockd_plane *const pd = &xd->plane[plane];
  tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
  uint8_t *dst;
747
#if !CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
748
  ENTROPY_CONTEXT *a, *l;
749
#endif
750
#if CONFIG_VAR_TX
751
  int bw = block_size_wide[plane_bsize] >> tx_size_wide_log2[0];
752
#endif
753
754
  dst = &pd->dst
             .buf[(blk_row * pd->dst.stride + blk_col) << tx_size_wide_log2[0]];
755
756

#if !CONFIG_PVQ
757
758
  a = &args->ta[blk_col];
  l = &args->tl[blk_row];
759
760
761
762
763
#if CONFIG_VAR_TX
  ctx = get_entropy_context(tx_size, a, l);
#else
  ctx = combine_entropy_contexts(*a, *l);
#endif
764
765
766
#else
  ctx = 0;
#endif  // CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
767

Alex Converse's avatar
Alex Converse committed
768
#if CONFIG_VAR_TX
769
  // Assert not magic number (uninitialized).
770
  assert(x->blk_skip[plane][blk_row * bw + blk_col] != 234);
771

772
  if (x->blk_skip[plane][blk_row * bw + blk_col] == 0) {
773
#else
774
  {
775
#endif
Angie Chiang's avatar
Angie Chiang committed
776
    av1_xform_quant(cm, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
777
                    ctx, AV1_XFORM_QUANT_FP);
Jingning Han's avatar
Jingning Han committed
778
  }
779
780
#if CONFIG_VAR_TX
  else {
781
    p->eobs[block] = 0;
782
783
  }
#endif
784

785
#if !CONFIG_PVQ
786
787
  if (p->eobs[block] && !xd->lossless[xd->mi[0]->mbmi.segment_id])
    av1_optimize_b(cm, x, plane, block, tx_size, ctx);
788

789
790
  av1_set_txb_context(x, plane, block, tx_size, a, l);

791
  if (p->eobs[block]) *(args->skip) = 0;
Jingning Han's avatar
Jingning Han committed
792

793
  if (p->eobs[block] == 0) return;
794
795
796
797
798
799
#else
  (void)ctx;
  if (!x->pvq_skip[plane]) *(args->skip) = 0;

  if (x->pvq_skip[plane]) return;
#endif
800
  TX_TYPE tx_type = get_tx_type(pd->plane_type, xd, block, tx_size);
801
802
  av1_inverse_transform_block(xd, dqcoeff, tx_type, tx_size, dst,
                              pd->dst.stride, p->eobs[block]);
Jingning Han's avatar
Jingning Han committed
803
804
}

805
806
807
808
809
810
811
812
#if CONFIG_VAR_TX
static void encode_block_inter(int plane, int block, int blk_row, int blk_col,
                               BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
                               void *arg) {
  struct encode_b_args *const args = arg;
  MACROBLOCK *const x = args->x;
  MACROBLOCKD *const xd = &x->e_mbd;
  MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
813
  const BLOCK_SIZE bsize = txsize_to_bsize[tx_size];
814
  const struct macroblockd_plane *const pd = &xd->plane[plane];
815
816
  const int tx_row = blk_row >> (1 - pd->subsampling_y);
  const int tx_col = blk_col >> (1 - pd->subsampling_x);
Debargha Mukherjee's avatar
Debargha Mukherjee committed
817
  TX_SIZE plane_tx_size;
818
819
  const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
  const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
820

821
  if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
822

823
824
825
  plane_tx_size =
      plane ? uv_txsize_lookup[bsize][mbmi->inter_tx_size[tx_row][tx_col]][0][0]
            : mbmi->inter_tx_size[tx_row][tx_col];
Debargha Mukherjee's avatar
Debargha Mukherjee committed
826

827
  if (tx_size == plane_tx_size) {
828
    encode_block(plane, block, blk_row, blk_col, plane_bsize, tx_size, arg);
829
  } else {
830
831
832
    const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
    // This is the square transform block partition entry point.
    int bsl = tx_size_wide_unit[sub_txs];
833
834
    int i;
    assert(bsl > 0);
835
    assert(tx_size < TX_SIZES_ALL);
836

837
    for (i = 0; i < 4; ++i) {
838
839
840
      const int offsetr = blk_row + ((i >> 1) * bsl);
      const int offsetc = blk_col + ((i & 0x01) * bsl);
      int step = tx_size_wide_unit[sub_txs] * tx_size_high_unit[sub_txs];
841

842
      if (offsetr >= max_blocks_high || offsetc >= max_blocks_wide) continue;
843

844
845
846
      encode_block_inter(plane, block, offsetr, offsetc, plane_bsize, sub_txs,
                         arg);
      block += step;
847
848
849
850
851
    }
  }
}
#endif

Angie Chiang's avatar
Angie Chiang committed
852
853
854
855
856
typedef struct encode_block_pass1_args {
  AV1_COMMON *cm;
  MACROBLOCK *x;
} encode_block_pass1_args;

857
static void encode_block_pass1(int plane, int block, int blk_row, int blk_col,
858
859
                               BLOCK_SIZE plane_bsize, TX_SIZE tx_size,
                               void *arg) {
Angie Chiang's avatar
Angie Chiang committed
860
861
862
  encode_block_pass1_args *args = (encode_block_pass1_args *)arg;
  AV1_COMMON *cm = args->cm;
  MACROBLOCK *const x = args->x;
Jingning Han's avatar
Jingning Han committed
863
864
865
866
867
  MACROBLOCKD *const xd = &x->e_mbd;
  struct macroblock_plane *const p = &x