encodemb.c 47.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 28 29 30
#include "av1/encoder/encodemb.h"
#include "av1/encoder/hybrid_fwd_txfm.h"
#include "av1/encoder/rd.h"
#include "av1/encoder/tokenize.h"
Jingning Han's avatar
Jingning Han committed
31

32 33 34 35 36 37
#if CONFIG_PVQ
#include "av1/encoder/encint.h"
#include "av1/common/partition.h"
#include "av1/encoder/pvq_encoder.h"
#endif

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

Yaowu Xu's avatar
Yaowu Xu committed
41
void av1_subtract_plane(MACROBLOCK *x, BLOCK_SIZE bsize, int plane) {
Jingning Han's avatar
Jingning Han committed
42 43 44
  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);
45 46
  const int bw = block_size_wide[plane_bsize];
  const int bh = block_size_high[plane_bsize];
Jingning Han's avatar
Jingning Han committed
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
  if (check_subtract_block_size(bw, bh)) {
#if CONFIG_AOM_HIGHBITDEPTH
    if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
      aom_highbd_subtract_block_c(bh, bw, p->src_diff, bw, p->src.buf,
                                  p->src.stride, pd->dst.buf, pd->dst.stride,
                                  x->e_mbd.bd);
      return;
    }
#endif  // CONFIG_AOM_HIGHBITDEPTH
    aom_subtract_block_c(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
                         pd->dst.buf, pd->dst.stride);

    return;
  }

Yaowu Xu's avatar
Yaowu Xu committed
63
#if CONFIG_AOM_HIGHBITDEPTH
Jingning Han's avatar
Jingning Han committed
64
  if (x->e_mbd.cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
Yaowu Xu's avatar
Yaowu Xu committed
65
    aom_highbd_subtract_block(bh, bw, p->src_diff, bw, p->src.buf,
Jingning Han's avatar
Jingning Han committed
66 67 68 69
                              p->src.stride, pd->dst.buf, pd->dst.stride,
                              x->e_mbd.bd);
    return;
  }
Yaowu Xu's avatar
Yaowu Xu committed
70 71
#endif  // CONFIG_AOM_HIGHBITDEPTH
  aom_subtract_block(bh, bw, p->src_diff, bw, p->src.buf, p->src.stride,
Jingning Han's avatar
Jingning Han committed
72 73 74
                     pd->dst.buf, pd->dst.stride);
}

Yaowu Xu's avatar
Yaowu Xu committed
75
typedef struct av1_token_state {
76
  int64_t error;
77 78
  int rate;
  int16_t next;
79 80 81
  int16_t token;
  tran_low_t qc;
  tran_low_t dqc;
82
  uint8_t best_index;
Yaowu Xu's avatar
Yaowu Xu committed
83
} av1_token_state;
Jingning Han's avatar
Jingning Han committed
84

85 86
// These numbers are empirically obtained.
static const int plane_rd_mult[REF_TYPES][PLANE_TYPES] = {
Thomas Davies's avatar
Thomas Davies committed
87 88 89
#if CONFIG_EC_ADAPT
  { 10, 7 }, { 8, 5 },
#else
90
  { 10, 6 }, { 8, 5 },
Thomas Davies's avatar
Thomas Davies committed
91
#endif
92
};
Jingning Han's avatar
Jingning Han committed
93

94 95 96 97 98
#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
99

100 101 102 103 104 105 106 107 108 109 110
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
111 112
int av1_optimize_b(const AV1_COMMON *cm, MACROBLOCK *mb, int plane, int block,
                   TX_SIZE tx_size, int ctx) {
Jingning Han's avatar
Jingning Han committed
113 114 115 116
  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
117
  av1_token_state tokens[MAX_TX_SQUARE + 1][2];
118
  uint8_t token_cache[MAX_TX_SQUARE];
119
  const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
Jingning Han's avatar
Jingning Han committed
120 121 122
  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];
123
  const PLANE_TYPE plane_type = pd->plane_type;
124
  const int default_eob = tx_size_2d[tx_size];
125 126
  const int16_t *const dequant_ptr = pd->dequant;
  const uint8_t *const band_translate = get_band_translate(tx_size);
127 128
  const int block_raster_idx = av1_block_index_to_raster_order(tx_size, block);
  TX_TYPE tx_type = get_tx_type(plane_type, xd, block_raster_idx, tx_size);
129
  const SCAN_ORDER *const scan_order =
Angie Chiang's avatar
Angie Chiang committed
130
      get_scan(cm, tx_size, tx_type, is_inter_block(&xd->mi[0]->mbmi));
131 132
  const int16_t *const scan = scan_order->scan;
  const int16_t *const nb = scan_order->neighbors;
Thomas Davies's avatar
Thomas Davies committed
133
  int dqv;
134
  const int shift = get_tx_scale(tx_size);
135 136
#if CONFIG_AOM_QM
  int seg_id = xd->mi[0]->mbmi.segment_id;
137
  const qm_val_t *iqmatrix = pd->seg_iqmatrix[seg_id][!ref][tx_size];
138
#endif
139
#if CONFIG_NEW_QUANT
140
  int dq = get_dq_profile_from_ctx(mb->qindex, ctx, ref, plane_type);
141
  const dequant_val_type_nuq *dequant_val = pd->dequant_val_nuq[dq];
142
#elif !CONFIG_AOM_QM
143
  const int dq_step[2] = { dequant_ptr[0] >> shift, dequant_ptr[1] >> shift };
144
#endif  // CONFIG_NEW_QUANT
Jingning Han's avatar
Jingning Han committed
145
  int next = eob, sz = 0;
146
  const int64_t rdmult = (mb->rdmult * plane_rd_mult[ref][plane_type]) >> 1;
hui su's avatar
hui su committed
147
  const int64_t rddiv = mb->rddiv;
Jingning Han's avatar
Jingning Han committed
148
  int64_t rd_cost0, rd_cost1;
149 150
  int rate0, rate1;
  int64_t error0, error1;
Jingning Han's avatar
Jingning Han committed
151
  int16_t t0, t1;
152 153
  int best, band = (eob < default_eob) ? band_translate[eob]
                                       : band_translate[eob - 1];
154
  int pt, i, final_eob;
Yaowu Xu's avatar
Yaowu Xu committed
155
#if CONFIG_AOM_HIGHBITDEPTH
156
  const int cat6_bits = av1_get_cat6_extrabits_size(tx_size, xd->bd);
Jingning Han's avatar
Jingning Han committed
157
#else
158
  const int cat6_bits = av1_get_cat6_extrabits_size(tx_size, 8);
Jingning Han's avatar
Jingning Han committed
159
#endif
160
  unsigned int(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
161
      mb->token_costs[txsize_sqr_map[tx_size]][plane_type][ref];
162 163
  const uint16_t *band_counts = &band_count_table[tx_size][band];
  uint16_t band_left = eob - band_cum_count_table[tx_size][band] + 1;
164 165
  int shortcut = 0;
  int next_shortcut = 0;
166

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

169
  token_costs += band;
Jingning Han's avatar
Jingning Han committed
170

171
  assert((!plane_type && !plane) || (plane_type && plane));
Jingning Han's avatar
Jingning Han committed
172
  assert(eob <= default_eob);
173

Jingning Han's avatar
Jingning Han committed
174 175 176 177 178 179 180 181 182
  /* 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];

183 184
  for (i = 0; i < eob; i++) {
    const int rc = scan[i];
185
    tokens[i][0].rate = av1_get_token_cost(qcoeff[rc], &t0, cat6_bits);
186
    tokens[i][0].token = t0;
Yaowu Xu's avatar
Yaowu Xu committed
187
    token_cache[rc] = av1_pt_energy_class[t0];
188
  }
Jingning Han's avatar
Jingning Han committed
189 190

  for (i = eob; i-- > 0;) {
191 192
    int base_bits, dx;
    int64_t d2;
Jingning Han's avatar
Jingning Han committed
193
    const int rc = scan[i];
Thomas Davies's avatar
Thomas Davies committed
194
    int x = qcoeff[rc];
195 196
#if CONFIG_AOM_QM
    int iwt = iqmatrix[rc];
Thomas Davies's avatar
Thomas Davies committed
197 198 199 200
    dqv = dequant_ptr[rc != 0];
    dqv = ((iwt * (int)dqv) + (1 << (AOM_QM_BITS - 1))) >> AOM_QM_BITS;
#else
    dqv = dequant_ptr[rc != 0];
201
#endif
202
    next_shortcut = shortcut;
203

Jingning Han's avatar
Jingning Han committed
204
    /* Only add a trellis state for non-zero coefficients. */
205
    if (UNLIKELY(x)) {
Jingning Han's avatar
Jingning Han committed
206 207 208 209 210
      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;
211

212 213 214 215
      if (next_shortcut) {
        /* Consider both possible successor states. */
        if (next < default_eob) {
          pt = get_coef_context(nb, token_cache, i + 1);
216 217 218 219
          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);
220 221 222 223 224 225 226
        }
        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);
227 228
          rate0 +=
              get_token_bit_costs(*token_costs, 0, pt, tokens[next][0].token);
229 230
        }
        best = 0;
Jingning Han's avatar
Jingning Han committed
231
      }
232 233

      dx = (dqcoeff[rc] - coeff[rc]) * (1 << shift);
Yaowu Xu's avatar
Yaowu Xu committed
234
#if CONFIG_AOM_HIGHBITDEPTH
Jingning Han's avatar
Jingning Han committed
235 236 237
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
        dx >>= xd->bd - 8;
      }
Yaowu Xu's avatar
Yaowu Xu committed
238
#endif  // CONFIG_AOM_HIGHBITDEPTH
239
      d2 = (int64_t)dx * dx;
240
      tokens[i][0].rate += (best ? rate1 : rate0);
Jingning Han's avatar
Jingning Han committed
241 242 243
      tokens[i][0].error = d2 + (best ? error1 : error0);
      tokens[i][0].next = next;
      tokens[i][0].qc = x;
244
      tokens[i][0].dqc = dqcoeff[rc];
245
      tokens[i][0].best_index = best;
Jingning Han's avatar
Jingning Han committed
246 247 248 249 250

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

251
      // The threshold of 3 is empirically obtained.
252
      if (UNLIKELY(abs(x) > 3)) {
253 254
        shortcut = 0;
      } else {
255
#if CONFIG_NEW_QUANT
Thomas Davies's avatar
Thomas Davies committed
256
        shortcut = ((av1_dequant_abscoeff_nuq(abs(x), dqv,
Yaowu Xu's avatar
Yaowu Xu committed
257
                                              dequant_val[band_translate[i]]) >
258
                     (abs(coeff[rc]) << shift)) &&
Thomas Davies's avatar
Thomas Davies committed
259
                    (av1_dequant_abscoeff_nuq(abs(x) - 1, dqv,
Yaowu Xu's avatar
Yaowu Xu committed
260
                                              dequant_val[band_translate[i]]) <
261
                     (abs(coeff[rc]) << shift)));
262 263 264 265 266 267 268 269
#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
270
        if ((abs(x) * dequant_ptr[rc != 0] > (abs(coeff[rc]) << shift)) &&
271 272
            (abs(x) * dequant_ptr[rc != 0] <
             (abs(coeff[rc]) << shift) + dequant_ptr[rc != 0]))
273
#endif  // CONFIG_AOM_QM
274 275 276
          shortcut = 1;
        else
          shortcut = 0;
277
#endif  // CONFIG_NEW_QUANT
278
      }
Jingning Han's avatar
Jingning Han committed
279 280 281 282

      if (shortcut) {
        sz = -(x < 0);
        x -= 2 * sz + 1;
283 284 285
      } else {
        tokens[i][1] = tokens[i][0];
        next = i;
286

287
        if (UNLIKELY(!(--band_left))) {
288 289 290 291
          --band_counts;
          band_left = *band_counts;
          --token_costs;
        }
292
        continue;
Jingning Han's avatar
Jingning Han committed
293 294 295 296 297 298 299 300 301
      }

      /* 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;
302
        base_bits = 0;
Jingning Han's avatar
Jingning Han committed
303
      } else {
304
        base_bits = av1_get_token_cost(x, &t0, cat6_bits);
Jingning Han's avatar
Jingning Han committed
305 306
        t1 = t0;
      }
307 308

      if (next_shortcut) {
309
        if (LIKELY(next < default_eob)) {
310
          if (t0 != EOB_TOKEN) {
Yaowu Xu's avatar
Yaowu Xu committed
311
            token_cache[rc] = av1_pt_energy_class[t0];
312
            pt = get_coef_context(nb, token_cache, i + 1);
313 314
            rate0 += get_token_bit_costs(*token_costs, !x, pt,
                                         tokens[next][0].token);
315 316
          }
          if (t1 != EOB_TOKEN) {
Yaowu Xu's avatar
Yaowu Xu committed
317
            token_cache[rc] = av1_pt_energy_class[t1];
318
            pt = get_coef_context(nb, token_cache, i + 1);
319 320
            rate1 += get_token_bit_costs(*token_costs, !x, pt,
                                         tokens[next][1].token);
321 322 323 324 325 326 327 328 329
          }
        }

        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
330
          token_cache[rc] = av1_pt_energy_class[t0];
Jingning Han's avatar
Jingning Han committed
331
          pt = get_coef_context(nb, token_cache, i + 1);
332 333
          rate0 +=
              get_token_bit_costs(*token_costs, !x, pt, tokens[next][0].token);
Jingning Han's avatar
Jingning Han committed
334
        }
335
        best = 0;
Jingning Han's avatar
Jingning Han committed
336 337
      }

338
#if CONFIG_NEW_QUANT
Thomas Davies's avatar
Thomas Davies committed
339
      dx = av1_dequant_coeff_nuq(x, dqv, dequant_val[band_translate[i]]) -
340
           (coeff[rc] << shift);
Yaowu Xu's avatar
Yaowu Xu committed
341
#if CONFIG_AOM_HIGHBITDEPTH
hui su's avatar
hui su committed
342 343 344
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
        dx >>= xd->bd - 8;
      }
Yaowu Xu's avatar
Yaowu Xu committed
345
#endif  // CONFIG_AOM_HIGHBITDEPTH
346
#else   // CONFIG_NEW_QUANT
Yaowu Xu's avatar
Yaowu Xu committed
347
#if CONFIG_AOM_HIGHBITDEPTH
hui su's avatar
hui su committed
348
      if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
Thomas Davies's avatar
Thomas Davies committed
349
        dx -= ((dqv >> (xd->bd - 8)) + sz) ^ sz;
hui su's avatar
hui su committed
350
      } else {
Thomas Davies's avatar
Thomas Davies committed
351
        dx -= (dqv + sz) ^ sz;
hui su's avatar
hui su committed
352 353
      }
#else
Thomas Davies's avatar
Thomas Davies committed
354
      dx -= (dqv + sz) ^ sz;
Yaowu Xu's avatar
Yaowu Xu committed
355
#endif  // CONFIG_AOM_HIGHBITDEPTH
356
#endif  // CONFIG_NEW_QUANT
357
      d2 = (int64_t)dx * dx;
hui su's avatar
hui su committed
358

Jingning Han's avatar
Jingning Han committed
359 360 361 362 363
      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;
364 365

      if (x) {
366
#if CONFIG_NEW_QUANT
Yaowu Xu's avatar
Yaowu Xu committed
367
        tokens[i][1].dqc = av1_dequant_abscoeff_nuq(
Thomas Davies's avatar
Thomas Davies committed
368
            abs(x), dqv, dequant_val[band_translate[i]]);
369 370 371
        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;
372
#else
373 374 375 376
// 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
377 378 379 380 381 382 383

#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);
384 385 386 387 388

        if (sz == 0)
          tokens[i][1].dqc = dqcoeff[rc] - offset;
        else
          tokens[i][1].dqc = dqcoeff[rc] + offset;
389
#endif  // CONFIG_NEW_QUANT
390 391 392 393
      } else {
        tokens[i][1].dqc = 0;
      }

394
      tokens[i][1].best_index = best;
Jingning Han's avatar
Jingning Han committed
395 396 397 398 399 400 401 402
      /* 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;
403
      pt = get_coef_context(nb, token_cache, i + 1);
Jingning Han's avatar
Jingning Han committed
404 405
      /* Update the cost of each path if we're past the EOB token. */
      if (t0 != EOB_TOKEN) {
406
        tokens[next][0].rate += get_token_bit_costs(*token_costs, 1, pt, t0);
Jingning Han's avatar
Jingning Han committed
407 408 409
        tokens[next][0].token = ZERO_TOKEN;
      }
      if (t1 != EOB_TOKEN) {
410
        tokens[next][1].rate += get_token_bit_costs(*token_costs, 1, pt, t1);
Jingning Han's avatar
Jingning Han committed
411 412
        tokens[next][1].token = ZERO_TOKEN;
      }
413
      tokens[i][0].best_index = tokens[i][1].best_index = 0;
414
      shortcut = (tokens[next][0].rate != tokens[next][1].rate);
Jingning Han's avatar
Jingning Han committed
415 416
      /* Don't update next, because we didn't add a new node. */
    }
417

418
    if (UNLIKELY(!(--band_left))) {
419 420 421 422
      --band_counts;
      band_left = *band_counts;
      --token_costs;
    }
Jingning Han's avatar
Jingning Han committed
423 424 425 426 427 428 429 430 431
  }

  /* 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;
432 433
  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
434 435
  UPDATE_RD_COST();
  best = rd_cost1 < rd_cost0;
436

Jingning Han's avatar
Jingning Han committed
437
  final_eob = -1;
438

Jingning Han's avatar
Jingning Han committed
439 440 441
  for (i = next; i < eob; i = next) {
    const int x = tokens[i][best].qc;
    const int rc = scan[i];
442
    if (x) final_eob = i;
Jingning Han's avatar
Jingning Han committed
443
    qcoeff[rc] = x;
444 445
    dqcoeff[rc] = tokens[i][best].dqc;

Jingning Han's avatar
Jingning Han committed
446
    next = tokens[i][best].next;
447
    best = tokens[i][best].best_index;
Jingning Han's avatar
Jingning Han committed
448 449 450 451
  }
  final_eob++;

  mb->plane[plane].eobs[block] = final_eob;
452
  assert(final_eob <= default_eob);
Jingning Han's avatar
Jingning Han committed
453 454 455
  return final_eob;
}

Thomas Daede's avatar
Thomas Daede committed
456
#if !CONFIG_PVQ
Yaowu Xu's avatar
Yaowu Xu committed
457
#if CONFIG_AOM_HIGHBITDEPTH
Angie Chiang's avatar
Angie Chiang committed
458 459
typedef enum QUANT_FUNC {
  QUANT_FUNC_LOWBD = 0,
460
  QUANT_FUNC_HIGHBD = 1,
461
  QUANT_FUNC_TYPES = 2
Angie Chiang's avatar
Angie Chiang committed
462 463
} QUANT_FUNC;

464 465 466
static AV1_QUANT_FACADE
    quant_func_list[AV1_XFORM_QUANT_TYPES][QUANT_FUNC_TYPES] = {
      { av1_quantize_fp_facade, av1_highbd_quantize_fp_facade },
Yaowu Xu's avatar
Yaowu Xu committed
467 468
      { av1_quantize_b_facade, av1_highbd_quantize_b_facade },
      { av1_quantize_dc_facade, av1_highbd_quantize_dc_facade },
469 470 471 472 473 474 475
#if CONFIG_NEW_QUANT
      { 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 },
#endif  // CONFIG_NEW_QUANT
      { NULL, NULL }
    };
476

Thomas Daede's avatar
Thomas Daede committed
477
#else
478

Angie Chiang's avatar
Angie Chiang committed
479 480
typedef enum QUANT_FUNC {
  QUANT_FUNC_LOWBD = 0,
481
  QUANT_FUNC_TYPES = 1
Angie Chiang's avatar
Angie Chiang committed
482
} QUANT_FUNC;
Angie Chiang's avatar
Angie Chiang committed
483

484 485
static AV1_QUANT_FACADE quant_func_list[AV1_XFORM_QUANT_TYPES]
                                       [QUANT_FUNC_TYPES] = {
clang-format's avatar
clang-format committed
486 487 488
                                         { av1_quantize_fp_facade },
                                         { av1_quantize_b_facade },
                                         { av1_quantize_dc_facade },
489 490 491 492 493
#if CONFIG_NEW_QUANT
                                         { av1_quantize_fp_nuq_facade },
                                         { av1_quantize_b_nuq_facade },
                                         { av1_quantize_dc_nuq_facade },
#endif  // CONFIG_NEW_QUANT
clang-format's avatar
clang-format committed
494 495
                                         { NULL }
                                       };
Thomas Daede's avatar
Thomas Daede committed
496 497
#endif  // CONFIG_AOM_HIGHBITDEPTH
#endif  // CONFIG_PVQ
498

Angie Chiang's avatar
Angie Chiang committed
499 500
void av1_xform_quant(const AV1_COMMON *cm, MACROBLOCK *x, int plane, int block,
                     int blk_row, int blk_col, BLOCK_SIZE plane_bsize,
501 502
                     TX_SIZE tx_size, int ctx,
                     AV1_XFORM_QUANT xform_quant_idx) {
Jingning Han's avatar
Jingning Han committed
503
  MACROBLOCKD *const xd = &x->e_mbd;
504
  MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi;
Yushin Cho's avatar
Yushin Cho committed
505
#if !(CONFIG_PVQ || CONFIG_DAALA_DIST)
Jingning Han's avatar
Jingning Han committed
506 507
  const struct macroblock_plane *const p = &x->plane[plane];
  const struct macroblockd_plane *const pd = &xd->plane[plane];
508 509 510 511
#else
  struct macroblock_plane *const p = &x->plane[plane];
  struct macroblockd_plane *const pd = &xd->plane[plane];
#endif
512
  PLANE_TYPE plane_type = get_plane_type(plane);
513 514
  const int block_raster_idx = av1_block_index_to_raster_order(tx_size, block);
  TX_TYPE tx_type = get_tx_type(plane_type, xd, block_raster_idx, tx_size);
515
  const int is_inter = is_inter_block(mbmi);
Angie Chiang's avatar
Angie Chiang committed
516
  const SCAN_ORDER *const scan_order = get_scan(cm, tx_size, tx_type, is_inter);
Jingning Han's avatar
Jingning Han committed
517 518 519 520
  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];
521
  const int diff_stride = block_size_wide[plane_bsize];
522
#if CONFIG_AOM_QM
523
  int seg_id = mbmi->segment_id;
524 525
  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];
526
#endif
Angie Chiang's avatar
Angie Chiang committed
527 528

  FWD_TXFM_PARAM fwd_txfm_param;
529

Yushin Cho's avatar
Yushin Cho committed
530 531 532 533 534 535 536 537
#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

538 539
#if !CONFIG_PVQ
  const int tx2d_size = tx_size_2d[tx_size];
540
  QUANT_PARAM qparam;
541 542
  const int16_t *src_diff;

543 544
  src_diff =
      &p->src_diff[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
545
  qparam.log_scale = get_tx_scale(tx_size);
546 547 548 549 550 551 552 553
#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
554 555 556 557
#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
558 559 560
  uint8_t *src;
  int16_t *src_int16;
  const int src_stride = p->src.stride;
561

562
  (void)ctx;
563 564 565 566 567 568 569
  (void)scan_order;
  (void)qcoeff;

  if (x->pvq_coded) {
    assert(block < MAX_PVQ_BLOCKS_IN_SB);
    pvq_info = &x->pvq[block][plane];
  }
570 571 572
  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
573 574 575

  // transform block size in pixels
  tx_blk_size = tx_size_wide[tx_size];
Thomas Daede's avatar
Thomas Daede committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589
#if CONFIG_AOM_HIGHBITDEPTH
  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 {
#endif  // CONFIG_AOM_HIGHBITDEPTH
    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];
#if CONFIG_AOM_HIGHBITDEPTH
  }
#endif  // CONFIG_AOM_HIGHBITDEPTH
Yushin Cho's avatar
Yushin Cho committed
590 591 592 593
#endif

#if CONFIG_PVQ || CONFIG_DAALA_DIST
  dst = &pd->dst.buf[(blk_row * dst_stride + blk_col) << tx_size_wide_log2[0]];
594
  pred = &pd->pred[(blk_row * diff_stride + blk_col) << tx_size_wide_log2[0]];
595 596 597 598

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

Thomas Daede's avatar
Thomas Daede committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
// copy uint8 orig and predicted block to int16 buffer
// in order to use existing VP10 transform functions
#if CONFIG_AOM_HIGHBITDEPTH
  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 {
#endif  // CONFIG_AOM_HIGHBITDEPTH
    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];
#if CONFIG_AOM_HIGHBITDEPTH
  }
#endif  // CONFIG_AOM_HIGHBITDEPTH
615
#endif
Yushin Cho's avatar
Yushin Cho committed
616

617
  (void)ctx;
618 619

  fwd_txfm_param.tx_type = tx_type;
Angie Chiang's avatar
Angie Chiang committed
620
  fwd_txfm_param.tx_size = tx_size;
621
  fwd_txfm_param.lossless = xd->lossless[mbmi->segment_id];
Angie Chiang's avatar
Angie Chiang committed
622

Thomas Daede's avatar
Thomas Daede committed
623
#if !CONFIG_PVQ
Yaowu Xu's avatar
Yaowu Xu committed
624
#if CONFIG_AOM_HIGHBITDEPTH
625
  fwd_txfm_param.bd = xd->bd;
Jingning Han's avatar
Jingning Han committed
626
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
Angie Chiang's avatar
Angie Chiang committed
627
    highbd_fwd_txfm(src_diff, coeff, diff_stride, &fwd_txfm_param);
Yaowu Xu's avatar
Yaowu Xu committed
628
    if (xform_quant_idx != AV1_XFORM_QUANT_SKIP_QUANT) {
629
      if (LIKELY(!x->skip_block)) {
630
        quant_func_list[xform_quant_idx][QUANT_FUNC_HIGHBD](
631
            coeff, tx2d_size, p, qcoeff, pd, dqcoeff, eob, scan_order, &qparam);
632
      } else {
Yaowu Xu's avatar
Yaowu Xu committed
633
        av1_quantize_skip(tx2d_size, qcoeff, dqcoeff, eob);
634 635 636 637
      }
    }
    return;
  }
Yaowu Xu's avatar
Yaowu Xu committed
638
#endif  // CONFIG_AOM_HIGHBITDEPTH
639
  fwd_txfm(src_diff, coeff, diff_stride, &fwd_txfm_param);
Yaowu Xu's avatar
Yaowu Xu committed
640
  if (xform_quant_idx != AV1_XFORM_QUANT_SKIP_QUANT) {
641
    if (LIKELY(!x->skip_block)) {
642
      quant_func_list[xform_quant_idx][QUANT_FUNC_LOWBD](
643
          coeff, tx2d_size, p, qcoeff, pd, dqcoeff, eob, scan_order, &qparam);
644
    } else {
Yaowu Xu's avatar
Yaowu Xu committed
645
      av1_quantize_skip(tx2d_size, qcoeff, dqcoeff, eob);
Jingning Han's avatar
Jingning Han committed
646 647
    }
  }
Thomas Daede's avatar
Thomas Daede committed
648
#else  // #if !CONFIG_PVQ
Angie Chiang's avatar
Angie Chiang committed
649
  (void)xform_quant_idx;
Thomas Daede's avatar
Thomas Daede committed
650 651 652 653 654 655 656 657 658 659 660 661
#if CONFIG_AOM_HIGHBITDEPTH
  fwd_txfm_param.bd = xd->bd;
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
    highbd_fwd_txfm(src_int16, coeff, diff_stride, &fwd_txfm_param);
    highbd_fwd_txfm(pred, ref_coeff, diff_stride, &fwd_txfm_param);
  } else {
#endif
    fwd_txfm(src_int16, coeff, diff_stride, &fwd_txfm_param);
    fwd_txfm(pred, ref_coeff, diff_stride, &fwd_txfm_param);
#if CONFIG_AOM_HIGHBITDEPTH
  }
#endif
662 663

  // PVQ for inter mode block
664
  if (!x->skip_block) {
ltrudeau's avatar
ltrudeau committed
665
    PVQ_SKIP_TYPE ac_dc_coded =
Thomas Daede's avatar
Thomas Daede committed
666
        av1_pvq_encode_helper(x,
ltrudeau's avatar
ltrudeau committed
667 668 669 670 671 672 673 674 675 676 677 678
                              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;
679
  }
680 681 682 683
  x->pvq_skip[plane] = skip;

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

686
static void encode_block(int plane, int block, int blk_row, int blk_col,
687
                         BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
Jingning Han's avatar
Jingning Han committed
688
  struct encode_b_args *const args = arg;
Angie Chiang's avatar
Angie Chiang committed
689
  AV1_COMMON *cm = args->cm;
Jingning Han's avatar
Jingning Han committed
690 691
  MACROBLOCK *const x = args->x;
  MACROBLOCKD *const xd = &x->e_mbd;
692
  int ctx;
Jingning Han's avatar
Jingning Han committed
693 694 695 696
  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;
697
#if !CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
698
  ENTROPY_CONTEXT *a, *l;
699
#endif
Angie Chiang's avatar
Angie Chiang committed
700
  INV_TXFM_PARAM inv_txfm_param;
701
  const int block_raster_idx = av1_block_index_to_raster_order(tx_size, block);
702
#if CONFIG_PVQ
703
  int tx_width_pixels, tx_height_pixels;
704
  int j;
705
#endif
706
#if CONFIG_VAR_TX
707
  int bw = block_size_wide[plane_bsize] >> tx_size_wide_log2[0];
708
#endif
709 710
  dst = &pd->dst
             .buf[(blk_row * pd->dst.stride + blk_col) << tx_size_wide_log2[0]];
711 712

#if !CONFIG_PVQ
713 714
  a = &args->ta[blk_col];
  l = &args->tl[blk_row];
715 716 717 718 719
#if CONFIG_VAR_TX
  ctx = get_entropy_context(tx_size, a, l);
#else
  ctx = combine_entropy_contexts(*a, *l);
#endif
720 721 722
#else
  ctx = 0;
#endif  // CONFIG_PVQ
Jingning Han's avatar
Jingning Han committed
723

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

728
  if (x->blk_skip[plane][blk_row * bw + blk_col] == 0) {
729
#else
730
  {
731
#endif
732
#if CONFIG_NEW_QUANT
733 734
    av1_xform_quant(cm, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
                    ctx, AV1_XFORM_QUANT_FP_NUQ);
735
#else
Angie Chiang's avatar
Angie Chiang committed
736
    av1_xform_quant(cm, x, plane, block, blk_row, blk_col, plane_bsize, tx_size,
737
                    ctx, AV1_XFORM_QUANT_FP);
738
#endif  // CONFIG_NEW_QUANT
Jingning Han's avatar
Jingning Han committed
739
  }
740 741
#if CONFIG_VAR_TX
  else {
742
    p->eobs[block] = 0;
743 744
  }
#endif
745

746
#if !CONFIG_PVQ
747 748
  if (p->eobs[block] && !xd->lossless[xd->mi[0]->mbmi.segment_id])
    av1_optimize_b(cm, x, plane, block, tx_size, ctx);
749

750 751
  av1_set_txb_context(x, plane, block, tx_size, a, l);

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

754
  if (p->eobs[block] == 0) return;
755 756 757 758 759 760 761
#else
  (void)ctx;
  if (!x->pvq_skip[plane]) *(args->skip) = 0;

  if (x->pvq_skip[plane]) return;

  // transform block size in pixels
762 763
  tx_width_pixels = tx_size_wide[tx_size];
  tx_height_pixels = tx_size_high[tx_size];
764 765 766 767 768

  // Since av1 does not have separate function which does inverse transform
  // but av1_inv_txfm_add_*x*() also does addition of predicted image to
  // inverse transformed image,
  // pass blank dummy image to av1_inv_txfm_add_*x*(), i.e. set dst as zeros
769 770
  for (j = 0; j < tx_height_pixels; j++) {
    int i;
771
    for (i = 0; i < tx_width_pixels; i++) dst[j * pd->dst.stride + i] = 0;
772
  }
773
#endif
Angie Chiang's avatar
Angie Chiang committed
774 775

  // inverse transform parameters
776 777
  inv_txfm_param.tx_type =
      get_tx_type(pd->plane_type, xd, block_raster_idx, tx_size);
Angie Chiang's avatar
Angie Chiang committed
778 779 780 781
  inv_txfm_param.tx_size = tx_size;
  inv_txfm_param.eob = p->eobs[block];
  inv_txfm_param.lossless = xd->lossless[xd->mi[0]->mbmi.segment_id];

Yaowu Xu's avatar
Yaowu Xu committed
782
#if CONFIG_AOM_HIGHBITDEPTH
Jingning Han's avatar
Jingning Han committed
783
  if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {