encodetxb.c 88.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Copyright (c) 2017, Alliance for Open Media. All rights reserved
 *
 * 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.
 */

12
#include "aom_ports/mem.h"
13
#include "av1/common/scan.h"
Angie Chiang's avatar
Angie Chiang committed
14
#include "av1/common/blockd.h"
15
#include "av1/common/idct.h"
Angie Chiang's avatar
Angie Chiang committed
16
#include "av1/common/pred_common.h"
17 18
#include "av1/encoder/bitstream.h"
#include "av1/encoder/encodeframe.h"
19
#include "av1/encoder/cost.h"
20
#include "av1/encoder/encodetxb.h"
Angie Chiang's avatar
Angie Chiang committed
21
#include "av1/encoder/rdopt.h"
22
#include "av1/encoder/subexp.h"
Angie Chiang's avatar
Angie Chiang committed
23
#include "av1/encoder/tokenize.h"
24

Angie Chiang's avatar
Angie Chiang committed
25 26
#define TEST_OPTIMIZE_TXB 0

Dake He's avatar
Dake He committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
typedef struct LevelDownStats {
  int update;
  tran_low_t low_qc;
  tran_low_t low_dqc;
  int64_t dist0;
  int rate;
  int rate_low;
  int64_t dist;
  int64_t dist_low;
  int64_t rd;
  int64_t rd_low;
  int nz_rate;  // for eob
  int64_t rd_diff;
  int cost_diff;
  int64_t dist_diff;
  int new_eob;
} LevelDownStats;

45
void av1_alloc_txb_buf(AV1_COMP *cpi) {
46
#if 0
47 48 49 50 51 52 53 54 55 56 57 58
  AV1_COMMON *cm = &cpi->common;
  int mi_block_size = 1 << MI_SIZE_LOG2;
  // TODO(angiebird): Make sure cm->subsampling_x/y is set correctly, and then
  // use precise buffer size according to cm->subsampling_x/y
  int pixel_stride = mi_block_size * cm->mi_cols;
  int pixel_height = mi_block_size * cm->mi_rows;
  int i;
  for (i = 0; i < MAX_MB_PLANE; ++i) {
    CHECK_MEM_ERROR(
        cm, cpi->tcoeff_buf[i],
        aom_malloc(sizeof(*cpi->tcoeff_buf[i]) * pixel_stride * pixel_height));
  }
59
#else
60
  AV1_COMMON *cm = &cpi->common;
61 62
  int size = ((cm->mi_rows >> cm->mib_size_log2) + 1) *
             ((cm->mi_cols >> cm->mib_size_log2) + 1);
63

64
  av1_free_txb_buf(cpi);
65 66 67
  // TODO(jingning): This should be further reduced.
  CHECK_MEM_ERROR(cm, cpi->coeff_buffer_base,
                  aom_malloc(sizeof(*cpi->coeff_buffer_base) * size));
68
#endif
69 70 71
}

void av1_free_txb_buf(AV1_COMP *cpi) {
72
#if 0
73 74 75 76
  int i;
  for (i = 0; i < MAX_MB_PLANE; ++i) {
    aom_free(cpi->tcoeff_buf[i]);
  }
77
#else
78
  aom_free(cpi->coeff_buffer_base);
79
#endif
80 81
}

82 83
void av1_set_coeff_buffer(const AV1_COMP *const cpi, MACROBLOCK *const x,
                          int mi_row, int mi_col) {
84 85 86
  int mib_size_log2 = cpi->common.mib_size_log2;
  int stride = (cpi->common.mi_cols >> mib_size_log2) + 1;
  int offset = (mi_row >> mib_size_log2) * stride + (mi_col >> mib_size_log2);
87 88 89 90 91 92 93 94 95 96 97 98
  CB_COEFF_BUFFER *coeff_buf = &cpi->coeff_buffer_base[offset];
  const int txb_offset = x->cb_offset / (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
  for (int plane = 0; plane < MAX_MB_PLANE; ++plane) {
    x->mbmi_ext->tcoeff[plane] = coeff_buf->tcoeff[plane] + x->cb_offset;
    x->mbmi_ext->eobs[plane] = coeff_buf->eobs[plane] + txb_offset;
    x->mbmi_ext->txb_skip_ctx[plane] =
        coeff_buf->txb_skip_ctx[plane] + txb_offset;
    x->mbmi_ext->dc_sign_ctx[plane] =
        coeff_buf->dc_sign_ctx[plane] + txb_offset;
  }
}

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
static void write_golomb(aom_writer *w, int level) {
  int x = level + 1;
  int i = x;
  int length = 0;

  while (i) {
    i >>= 1;
    ++length;
  }
  assert(length > 0);

  for (i = 0; i < length - 1; ++i) aom_write_bit(w, 0);

  for (i = length - 1; i >= 0; --i) aom_write_bit(w, (x >> i) & 0x01);
}

Dake He's avatar
Dake He committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128
static INLINE tran_low_t get_lower_coeff(tran_low_t qc) {
  if (qc == 0) {
    return 0;
  }
  return qc > 0 ? qc - 1 : qc + 1;
}

static INLINE tran_low_t qcoeff_to_dqcoeff(tran_low_t qc, int dqv, int shift) {
  int sgn = qc < 0 ? -1 : 1;
  return sgn * ((abs(qc) * dqv) >> shift);
}

static INLINE int64_t get_coeff_dist(tran_low_t tcoeff, tran_low_t dqcoeff,
                                     int shift) {
129 130 131 132 133 134 135
#if CONFIG_DAALA_TX
  int depth_shift = (TX_COEFF_DEPTH - 11) * 2;
  int depth_round = depth_shift > 1 ? (1 << (depth_shift - 1)) : 0;
  const int64_t diff = tcoeff - dqcoeff;
  const int64_t error = diff * diff + depth_round >> depth_shift;
  (void)shift;
#else
Dake He's avatar
Dake He committed
136 137
  const int64_t diff = (tcoeff - dqcoeff) * (1 << shift);
  const int64_t error = diff * diff;
138
#endif
Dake He's avatar
Dake He committed
139 140 141
  return error;
}

Jingning Han's avatar
Jingning Han committed
142 143
void av1_update_eob_context(int eob, int seg_eob, TX_SIZE tx_size,
                            TX_TYPE tx_type, PLANE_TYPE plane,
144 145
                            FRAME_CONTEXT *ec_ctx, FRAME_COUNTS *counts,
                            uint8_t allow_update_cdf) {
Linfeng Zhang's avatar
Linfeng Zhang committed
146 147 148
  int eob_extra, dummy;
  const int eob_pt = get_eob_pos_token(eob, &eob_extra);
  const int max_eob_pt = get_eob_pos_token(seg_eob, &dummy);
149
  TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
Dake He's avatar
Dake He committed
150 151

  for (int i = 1; i < max_eob_pt; i++) {
Jingning Han's avatar
Jingning Han committed
152 153
    int eob_pos_ctx = av1_get_eob_pos_ctx(tx_type, i);
    counts->eob_flag[txs_ctx][plane][eob_pos_ctx][eob_pt == i]++;
154 155 156
    if (allow_update_cdf)
      update_cdf(ec_ctx->eob_flag_cdf[txs_ctx][plane][eob_pos_ctx], eob_pt == i,
                 2);
Dake He's avatar
Dake He committed
157 158 159 160
    if (eob_pt == i) {
      break;
    }
  }
Jingning Han's avatar
Jingning Han committed
161

Angie Chiang's avatar
Angie Chiang committed
162 163 164
  if (k_eob_offset_bits[eob_pt] > 0) {
    int eob_shift = k_eob_offset_bits[eob_pt] - 1;
    int bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
Jingning Han's avatar
Jingning Han committed
165
    counts->eob_extra[txs_ctx][plane][eob_pt][bit]++;
166 167
    if (allow_update_cdf)
      update_cdf(ec_ctx->eob_extra_cdf[txs_ctx][plane][eob_pt], bit, 2);
Angie Chiang's avatar
Angie Chiang committed
168
  }
Dake He's avatar
Dake He committed
169 170 171
}

static int get_eob_cost(int eob, int seg_eob,
Jingning Han's avatar
Jingning Han committed
172
                        const LV_MAP_COEFF_COST *txb_costs, TX_TYPE tx_type) {
Linfeng Zhang's avatar
Linfeng Zhang committed
173 174 175
  int eob_extra, dummy;
  const int eob_pt = get_eob_pos_token(eob, &eob_extra);
  const int max_eob_pt = get_eob_pos_token(seg_eob, &dummy);
Dake He's avatar
Dake He committed
176 177 178 179
  int eob_cost = 0;

  // printf("Enc: [%d, %d], (%d, %d) ", seg_eob, eob, eob_pt, eob_extra);
  for (int i = 1; i < max_eob_pt; i++) {
Jingning Han's avatar
Jingning Han committed
180
    int eob_pos_ctx = av1_get_eob_pos_ctx(tx_type, i);
Dake He's avatar
Dake He committed
181 182 183 184 185 186
    eob_cost += txb_costs->eob_cost[eob_pos_ctx][eob_pt == i];
    if (eob_pt == i) {
      break;
    }
  }
  if (k_eob_offset_bits[eob_pt] > 0) {
Angie Chiang's avatar
Angie Chiang committed
187 188 189 190 191 192
    int eob_shift = k_eob_offset_bits[eob_pt] - 1;
    int bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
    eob_cost += txb_costs->eob_extra_cost[eob_pt][bit];
    for (int i = 1; i < k_eob_offset_bits[eob_pt]; i++) {
      eob_shift = k_eob_offset_bits[eob_pt] - 1 - i;
      bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
Dake He's avatar
Dake He committed
193 194 195 196 197 198
      eob_cost += av1_cost_bit(128, bit);
    }
  }
  return eob_cost;
}

199
static int get_coeff_cost(const tran_low_t qc, const int scan_idx,
200 201 202
#if CONFIG_LV_MAP_MULTI
                          const int is_eob,
#endif
203 204
                          const TxbInfo *const txb_info,
                          const LV_MAP_COEFF_COST *const txb_costs);
Dake He's avatar
Dake He committed
205

Linfeng Zhang's avatar
Linfeng Zhang committed
206
static void get_dist_cost_stats(LevelDownStats *stats, int scan_idx,
207 208 209
#if CONFIG_LV_MAP_MULTI
                                const int is_eob,
#endif
Linfeng Zhang's avatar
Linfeng Zhang committed
210 211
                                const LV_MAP_COEFF_COST *txb_costs,
                                TxbInfo *txb_info) {
Dake He's avatar
Dake He committed
212 213 214
  const int16_t *scan = txb_info->scan_order->scan;
  const int coeff_idx = scan[scan_idx];
  const tran_low_t qc = txb_info->qcoeff[coeff_idx];
215
  const uint8_t *const levels = txb_info->levels;
Dake He's avatar
Dake He committed
216 217 218 219 220 221 222 223
  stats->new_eob = -1;
  stats->update = 0;

  const tran_low_t tqc = txb_info->tcoeff[coeff_idx];
  const int dqv = txb_info->dequant[coeff_idx != 0];

  const tran_low_t dqc = qcoeff_to_dqcoeff(qc, dqv, txb_info->shift);
  const int64_t dqc_dist = get_coeff_dist(tqc, dqc, txb_info->shift);
224 225 226
#if CONFIG_LV_MAP_MULTI
  const int qc_cost = get_coeff_cost(qc, scan_idx, is_eob, txb_info, txb_costs);
#else
Dake He's avatar
Dake He committed
227
  const int qc_cost = get_coeff_cost(qc, scan_idx, txb_info, txb_costs);
228
#endif
Dake He's avatar
Dake He committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

  // distortion difference when coefficient is quantized to 0
  const tran_low_t dqc0 = qcoeff_to_dqcoeff(0, dqv, txb_info->shift);
  stats->dist0 = get_coeff_dist(tqc, dqc0, txb_info->shift);
  stats->dist = dqc_dist - stats->dist0;
  stats->rate = qc_cost;

  if (qc == 0) {
    return;
  }
  stats->rd = RDCOST(txb_info->rdmult, stats->rate, stats->dist);

  stats->low_qc = get_lower_coeff(qc);
  stats->low_dqc = qcoeff_to_dqcoeff(stats->low_qc, dqv, txb_info->shift);
  const int64_t low_dqc_dist =
      get_coeff_dist(tqc, stats->low_dqc, txb_info->shift);
245 246 247 248
#if CONFIG_LV_MAP_MULTI
  const int low_qc_cost =
      get_coeff_cost(stats->low_qc, scan_idx, is_eob, txb_info, txb_costs);
#else
Dake He's avatar
Dake He committed
249 250
  const int low_qc_cost =
      get_coeff_cost(stats->low_qc, scan_idx, txb_info, txb_costs);
251
#endif
Dake He's avatar
Dake He committed
252 253 254 255
  stats->dist_low = low_dqc_dist - stats->dist0;
  stats->rate_low = low_qc_cost;
  stats->rd_low = RDCOST(txb_info->rdmult, stats->rate_low, stats->dist_low);

256
#if CONFIG_LV_MAP_MULTI
257
  (void)levels;
258
  if ((stats->rd_low < stats->rd) && (stats->low_qc == 0)) {
259
    stats->nz_rate = low_qc_cost;
260
  } else {
261 262 263 264 265 266 267 268 269
    if (stats->rd_low < stats->rd) {
      const int low_qc_eob_cost =
          get_coeff_cost(stats->low_qc, scan_idx, 1, txb_info, txb_costs);
      stats->nz_rate = low_qc_cost - low_qc_eob_cost;
    } else {
      const int qc_eob_cost =
          get_coeff_cost(qc, scan_idx, 1, txb_info, txb_costs);
      stats->nz_rate = qc_cost - qc_eob_cost;
    }
270 271
  }
#else
272
  int coeff_ctx = get_nz_map_ctx(levels, scan_idx, scan, txb_info->bwl,
273
                                 txb_info->height, txb_info->tx_type);
Dake He's avatar
Dake He committed
274 275 276 277 278
  if ((stats->rd_low < stats->rd) && (stats->low_qc == 0)) {
    stats->nz_rate = txb_costs->nz_map_cost[coeff_ctx][0];
  } else {
    stats->nz_rate = txb_costs->nz_map_cost[coeff_ctx][1];
  }
279
#endif
Dake He's avatar
Dake He committed
280 281
}

282 283
static INLINE void update_qcoeff(const int coeff_idx, const tran_low_t qc,
                                 const TxbInfo *const txb_info) {
Dake He's avatar
Dake He committed
284
  txb_info->qcoeff[coeff_idx] = qc;
285
  txb_info->levels[get_paded_idx(coeff_idx, txb_info->bwl)] =
286
      (uint8_t)clamp(abs(qc), 0, INT8_MAX);
287 288 289 290 291
}

static INLINE void update_coeff(const int coeff_idx, const tran_low_t qc,
                                const TxbInfo *const txb_info) {
  update_qcoeff(coeff_idx, qc, txb_info);
Dake He's avatar
Dake He committed
292 293 294 295
  const int dqv = txb_info->dequant[coeff_idx != 0];
  txb_info->dqcoeff[coeff_idx] = qcoeff_to_dqcoeff(qc, dqv, txb_info->shift);
}

296
static INLINE void av1_txb_init_levels(const tran_low_t *const coeff,
297
                                       const int width, const int height,
298 299
                                       uint8_t *const levels) {
  const int stride = width + TX_PAD_HOR;
300
  uint8_t *ls = levels;
301 302 303

  memset(levels - TX_PAD_TOP * stride, 0,
         sizeof(*levels) * TX_PAD_TOP * stride);
304 305
  memset(levels + stride * height, 0,
         sizeof(*levels) * (TX_PAD_BOTTOM * stride + TX_PAD_END));
306

307 308
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
309
      *ls++ = (uint8_t)clamp(abs(coeff[i * width + j]), 0, INT8_MAX);
310 311 312 313
    }
    for (int j = 0; j < TX_PAD_HOR; j++) {
      *ls++ = 0;
    }
314 315 316
  }
}

317
void av1_write_coeffs_txb(const AV1_COMMON *const cm, MACROBLOCKD *xd,
Jingning Han's avatar
Jingning Han committed
318 319 320
                          aom_writer *w, int blk_row, int blk_col, int block,
                          int plane, TX_SIZE tx_size, const tran_low_t *tcoeff,
                          uint16_t eob, TXB_CTX *txb_ctx) {
321
  MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
322
  const PLANE_TYPE plane_type = get_plane_type(plane);
323
  const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
324 325
  const TX_TYPE tx_type =
      av1_get_tx_type(plane_type, xd, blk_row, blk_col, block, tx_size);
Angie Chiang's avatar
Angie Chiang committed
326
  const SCAN_ORDER *const scan_order = get_scan(cm, tx_size, tx_type, mbmi);
327
  const int16_t *scan = scan_order->scan;
328
  const int seg_eob = av1_get_max_eob(tx_size);
329
  int c;
330 331 332
  const int bwl = get_txb_bwl(tx_size);
  const int width = get_txb_wide(tx_size);
  const int height = get_txb_high(tx_size);
333
  int update_eob = -1;
334
  FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
335 336
  uint8_t levels_buf[TX_PAD_2D];
  uint8_t *const levels = set_levels(levels_buf, width);
337
  DECLARE_ALIGNED(16, uint8_t, level_counts[MAX_TX_SQUARE]);
338

Jingning Han's avatar
Jingning Han committed
339 340
  (void)blk_row;
  (void)blk_col;
341 342
  aom_write_bin(w, eob == 0,
                ec_ctx->txb_skip_cdf[txs_ctx][txb_ctx->txb_skip_ctx], 2);
343
  if (eob == 0) return;
344

345
  av1_txb_init_levels(tcoeff, width, height, levels);
346

Angie Chiang's avatar
Angie Chiang committed
347
#if CONFIG_TXK_SEL
348 349
  av1_write_tx_type(cm, xd, blk_row, blk_col, block, plane,
                    get_min_tx_size(tx_size), w);
Angie Chiang's avatar
Angie Chiang committed
350
#endif
351

Linfeng Zhang's avatar
Linfeng Zhang committed
352 353 354
  int eob_extra, dummy;
  const int eob_pt = get_eob_pos_token(eob, &eob_extra);
  const int max_eob_pt = get_eob_pos_token(seg_eob, &dummy);
Dake He's avatar
Dake He committed
355 356 357

  // printf("Enc: [%d, %d], (%d, %d) ", seg_eob, eob, eob_pt, eob_extra);
  for (int i = 1; i < max_eob_pt; i++) {
Jingning Han's avatar
Jingning Han committed
358
    int eob_pos_ctx = av1_get_eob_pos_ctx(tx_type, i);
Dake He's avatar
Dake He committed
359 360 361 362 363 364 365 366 367 368 369

    aom_write_bin(w, eob_pt == i,
                  ec_ctx->eob_flag_cdf[txs_ctx][plane_type][eob_pos_ctx], 2);
    // aom_write_symbol(w, eob_pt == i,
    // ec_ctx->eob_flag_cdf[AOMMIN(txs_ctx,3)][plane_type][eob_pos_ctx], 2);
    if (eob_pt == i) {
      break;
    }
  }

  if (k_eob_offset_bits[eob_pt] > 0) {
Angie Chiang's avatar
Angie Chiang committed
370 371 372 373 374 375 376
    int eob_shift = k_eob_offset_bits[eob_pt] - 1;
    int bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
    aom_write_bin(w, bit, ec_ctx->eob_extra_cdf[txs_ctx][plane_type][eob_pt],
                  2);
    for (int i = 1; i < k_eob_offset_bits[eob_pt]; i++) {
      eob_shift = k_eob_offset_bits[eob_pt] - 1 - i;
      bit = (eob_extra & (1 << eob_shift)) ? 1 : 0;
Dake He's avatar
Dake He committed
377 378 379 380
      aom_write_bit(w, bit);
      // printf("%d ", bit);
    }
  }
381 382 383 384 385 386

#if USE_CAUSAL_BASE_CTX
  int coeff_ctx = 0;
  for (int i = 0; i < eob; ++i) {
    c = eob - 1 - i;

387 388
#if CONFIG_LV_MAP_MULTI
    coeff_ctx =
Linfeng Zhang's avatar
Linfeng Zhang committed
389
        get_nz_map_ctx(levels, c, scan, bwl, height, c == eob - 1, tx_type);
390
    tran_low_t v = tcoeff[scan[c]];
391 392 393 394 395 396 397 398 399 400 401 402 403 404
#if USE_BASE_EOB_ALPHABET
    if (c == eob - 1) {
      aom_write_symbol(
          w, AOMMIN(abs(v), 3) - 1,
          ec_ctx->coeff_base_eob_cdf[txs_ctx][plane_type]
                                    [coeff_ctx - SIG_COEF_CONTEXTS +
                                     SIG_COEF_CONTEXTS_EOB],
          3);
    } else {
      aom_write_symbol(w, AOMMIN(abs(v), 3),
                       ec_ctx->coeff_base_cdf[txs_ctx][plane_type][coeff_ctx],
                       4);
    }
#else
405 406
    aom_write_symbol(w, AOMMIN(abs(v), 3),
                     ec_ctx->coeff_base_cdf[txs_ctx][plane_type][coeff_ctx], 4);
407
#endif
408 409
#else
    coeff_ctx = get_nz_map_ctx(levels, c, scan, bwl, height, tx_type);
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    tran_low_t v = tcoeff[scan[c]];
    int is_nz = (v != 0);

    if (c < eob - 1) {
      aom_write_bin(w, is_nz,
                    ec_ctx->nz_map_cdf[txs_ctx][plane_type][coeff_ctx], 2);
    }
    if (is_nz) {
      const int level = abs(v);
      int k;
      for (k = 0; k < NUM_BASE_LEVELS; ++k) {
        int is_k = (level > (k + 1));
        int ctx = coeff_ctx;
        aom_write_bin(w, is_k,
                      ec_ctx->coeff_base_cdf[txs_ctx][plane_type][k][ctx], 2);
        if (is_k == 0) break;
      }
    }
428
#endif
429 430 431
  }
  update_eob = eob - 1;
#else
Dake He's avatar
Dake He committed
432 433
  for (int i = 1; i < eob; ++i) {
    c = eob - 1 - i;
434
    int coeff_ctx = get_nz_map_ctx(levels, c, scan, bwl, height, tx_type);
Dake He's avatar
Dake He committed
435 436 437 438 439 440 441 442 443

    tran_low_t v = tcoeff[scan[c]];
    int is_nz = (v != 0);

    aom_write_bin(w, is_nz, ec_ctx->nz_map_cdf[txs_ctx][plane_type][coeff_ctx],
                  2);
  }

  for (int i = 0; i < NUM_BASE_LEVELS; ++i) {
444
    av1_get_base_level_counts(levels, i, width, height, level_counts);
445
    for (c = eob - 1; c >= 0; --c) {
446
      const tran_low_t level = abs(tcoeff[scan[c]]);
447 448 449 450
      int ctx;

      if (level <= i) continue;

451
      ctx = get_base_ctx(levels, scan[c], bwl, i, level_counts[scan[c]]);
452 453

      if (level == i + 1) {
454 455
        aom_write_bin(w, 1, ec_ctx->coeff_base_cdf[txs_ctx][plane_type][i][ctx],
                      2);
456 457
        continue;
      }
458

459 460
      aom_write_bin(w, 0, ec_ctx->coeff_base_cdf[txs_ctx][plane_type][i][ctx],
                    2);
461 462 463
      update_eob = AOMMAX(update_eob, c);
    }
  }
464
#endif
465

466 467 468
  // Loop to code all signs in the transform block,
  // starting with the sign of DC (if applicable)
  for (c = 0; c < eob; ++c) {
469 470 471
    const tran_low_t v = tcoeff[scan[c]];
    const tran_low_t level = abs(v);
    const int sign = (v < 0) ? 1 : 0;
472
    if (level == 0) continue;
473 474

    if (c == 0) {
475
#if LV_MAP_PROB
476 477
      aom_write_bin(w, sign,
                    ec_ctx->dc_sign_cdf[plane_type][txb_ctx->dc_sign_ctx], 2);
478 479 480
#else
      aom_write(w, sign, ec_ctx->dc_sign[plane_type][txb_ctx->dc_sign_ctx]);
#endif
481 482 483
    } else {
      aom_write_bit(w, sign);
    }
484 485
  }

Linfeng Zhang's avatar
Linfeng Zhang committed
486
  if (update_eob >= 0) {
487
#if !CONFIG_LV_MAP_MULTI
Linfeng Zhang's avatar
Linfeng Zhang committed
488
    av1_get_br_level_counts(levels, width, height, level_counts);
489
#endif
Linfeng Zhang's avatar
Linfeng Zhang committed
490 491 492 493
    for (c = update_eob; c >= 0; --c) {
      const tran_low_t level = abs(tcoeff[scan[c]]);
      int idx;
      int ctx;
494

Linfeng Zhang's avatar
Linfeng Zhang committed
495 496
      if (level <= NUM_BASE_LEVELS) continue;

497 498
// level is above 1.
#if !CONFIG_LV_MAP_MULTI
Linfeng Zhang's avatar
Linfeng Zhang committed
499
      ctx = get_br_ctx(levels, scan[c], bwl, level_counts[scan[c]]);
500
#endif
Linfeng Zhang's avatar
Linfeng Zhang committed
501
      int base_range = level - 1 - NUM_BASE_LEVELS;
502
#if CONFIG_LV_MAP_MULTI
503 504 505 506 507 508
#if USE_CAUSAL_BR_CTX
      ctx = get_br_ctx(levels, scan[c], bwl, level_counts[scan[c]], tx_type);

#else
      ctx = get_br_ctx(levels, scan[c], bwl, level_counts[scan[c]]);
#endif
509 510
      for (idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
        int k = AOMMIN(base_range - idx, BR_CDF_SIZE - 1);
511 512 513 514
        aom_write_symbol(
            w, k,
            ec_ctx->coeff_br_cdf[AOMMIN(txs_ctx, TX_16X16)][plane_type][ctx],
            BR_CDF_SIZE);
515 516 517 518
        if (k < BR_CDF_SIZE - 1) break;
      }
      if (base_range < COEFF_BASE_RANGE) continue;
#else
Linfeng Zhang's avatar
Linfeng Zhang committed
519 520 521 522 523 524 525 526 527 528
      int br_set_idx = 0;
      int br_base = 0;
      int br_offset = 0;

      if (base_range >= COEFF_BASE_RANGE)
        br_set_idx = BASE_RANGE_SETS;
      else
        br_set_idx = coeff_to_br_index[base_range];

      for (idx = 0; idx < BASE_RANGE_SETS; ++idx) {
529
        // printf("br: %d %d %d %d\n", txs_ctx, plane_type, idx, ctx);
Linfeng Zhang's avatar
Linfeng Zhang committed
530 531 532 533 534 535 536 537 538 539 540 541 542
        aom_write_bin(w, idx == br_set_idx,
                      ec_ctx->coeff_br_cdf[txs_ctx][plane_type][idx][ctx], 2);
        if (idx == br_set_idx) {
          br_base = br_index_to_coeff[br_set_idx];
          br_offset = base_range - br_base;
          int extra_bits = (1 << br_extra_bits[idx]) - 1;
          for (int tok = 0; tok < extra_bits; ++tok) {
            if (tok == br_offset) {
              aom_write_bin(w, 1,
                            ec_ctx->coeff_lps_cdf[txs_ctx][plane_type][ctx], 2);
              break;
            }
            aom_write_bin(w, 0, ec_ctx->coeff_lps_cdf[txs_ctx][plane_type][ctx],
543
                          2);
544
          }
Linfeng Zhang's avatar
Linfeng Zhang committed
545 546
          //        aom_write_literal(w, br_offset, br_extra_bits[idx]);
          break;
547 548 549
        }
      }

Linfeng Zhang's avatar
Linfeng Zhang committed
550
      if (br_set_idx < BASE_RANGE_SETS) continue;
551
#endif
Linfeng Zhang's avatar
Linfeng Zhang committed
552 553 554 555
      // use 0-th order Golomb code to handle the residual level.
      write_golomb(
          w, abs(tcoeff[scan[c]]) - COEFF_BASE_RANGE - 1 - NUM_BASE_LEVELS);
    }
556
  }
557 558 559 560 561

#if CONFIG_ADAPT_SCAN
  const int mi_row = -xd->mb_to_top_edge >> (3 + MI_SIZE_LOG2);
  av1_update_scan_count_facade(cm, xd, mi_row, tx_size, tx_type, tcoeff, eob);
#endif
562
}
563

Angie Chiang's avatar
Angie Chiang committed
564 565 566 567 568 569
void av1_write_coeffs_mb(const AV1_COMMON *const cm, MACROBLOCK *x,
                         aom_writer *w, int plane) {
  MACROBLOCKD *xd = &x->e_mbd;
  MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
  BLOCK_SIZE bsize = mbmi->sb_type;
  struct macroblockd_plane *pd = &xd->plane[plane];
570 571
  const BLOCK_SIZE plane_bsize =
      AOMMAX(BLOCK_4X4, get_plane_block_size(bsize, pd));
572 573
  const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
  const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
574
  const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
Angie Chiang's avatar
Angie Chiang committed
575 576 577 578 579
  const int bkw = tx_size_wide_unit[tx_size];
  const int bkh = tx_size_high_unit[tx_size];
  const int step = tx_size_wide_unit[tx_size] * tx_size_high_unit[tx_size];
  int row, col;
  int block = 0;
580 581
  for (row = 0; row < max_blocks_high; row += bkh) {
    for (col = 0; col < max_blocks_wide; col += bkw) {
Angie Chiang's avatar
Angie Chiang committed
582 583 584 585
      tran_low_t *tcoeff = BLOCK_OFFSET(x->mbmi_ext->tcoeff[plane], block);
      uint16_t eob = x->mbmi_ext->eobs[plane][block];
      TXB_CTX txb_ctx = { x->mbmi_ext->txb_skip_ctx[plane][block],
                          x->mbmi_ext->dc_sign_ctx[plane][block] };
Jingning Han's avatar
Jingning Han committed
586 587
      av1_write_coeffs_txb(cm, xd, w, row, col, block, plane, tx_size, tcoeff,
                           eob, &txb_ctx);
Angie Chiang's avatar
Angie Chiang committed
588 589 590 591 592
      block += step;
    }
  }
}

593
#if !USE_CAUSAL_BASE_CTX
594 595
static INLINE void get_base_ctx_set(const uint8_t *const levels,
                                    const int c,  // raster order
596
                                    const int bwl,
597 598 599
                                    int ctx_set[NUM_BASE_LEVELS]) {
  const int row = c >> bwl;
  const int col = c - (row << bwl);
600 601
  const int width = 1 << bwl;
  const int stride = width + TX_PAD_HOR;
602 603
  int mag_count[NUM_BASE_LEVELS] = { 0 };
  int nb_mag[NUM_BASE_LEVELS][3] = { { 0 } };
604 605 606 607
  int idx;
  int i;

  for (idx = 0; idx < BASE_CONTEXT_POSITION_NUM; ++idx) {
608 609 610
    const int ref_row = row + base_ref_offset[idx][0];
    const int ref_col = col + base_ref_offset[idx][1];
    const int pos = ref_row * stride + ref_col;
611
    const uint8_t abs_coeff = levels[pos];
612 613 614

    for (i = 0; i < NUM_BASE_LEVELS; ++i) {
      ctx_set[i] += abs_coeff > i;
615 616 617 618 619 620
      if (base_ref_offset[idx][0] == 0 && base_ref_offset[idx][1] == 1)
        nb_mag[i][0] = abs_coeff;
      if (base_ref_offset[idx][0] == 1 && base_ref_offset[idx][1] == 0)
        nb_mag[i][1] = abs_coeff;
      if (base_ref_offset[idx][0] == 1 && base_ref_offset[idx][1] == 1)
        nb_mag[i][2] = abs_coeff;
621 622 623 624
    }
  }

  for (i = 0; i < NUM_BASE_LEVELS; ++i) {
625 626 627
    for (idx = 0; idx < 3; ++idx) mag_count[i] += nb_mag[i][idx] > i + 1;
    ctx_set[i] = get_base_ctx_from_count_mag(row, col, ctx_set[i],
                                             AOMMIN(2, mag_count[i]));
628 629 630
  }
  return;
}
631
#endif
632

633
static INLINE int get_br_cost(tran_low_t abs_qc, int ctx,
Angie Chiang's avatar
Angie Chiang committed
634
                              const int *coeff_lps) {
635 636
  const tran_low_t min_level = 1 + NUM_BASE_LEVELS;
  const tran_low_t max_level = 1 + NUM_BASE_LEVELS + COEFF_BASE_RANGE;
637
  (void)ctx;
638 639
  if (abs_qc >= min_level) {
    if (abs_qc >= max_level)
640
      return coeff_lps[COEFF_BASE_RANGE];  // COEFF_BASE_RANGE * cost0;
641
    else
642
      return coeff_lps[(abs_qc - min_level)];  //  * cost0 + cost1;
643 644 645 646 647 648
  } else {
    return 0;
  }
}

static INLINE int get_base_cost(tran_low_t abs_qc, int ctx,
649
                                const int coeff_base[2], int base_idx) {
650
  const int level = base_idx + 1;
651
  (void)ctx;
652 653 654
  if (abs_qc < level)
    return 0;
  else
655
    return coeff_base[abs_qc == level];
656 657
}

658
int av1_cost_coeffs_txb(const AV1_COMMON *const cm, MACROBLOCK *x, int plane,
Jingning Han's avatar
Jingning Han committed
659 660
                        int blk_row, int blk_col, int block, TX_SIZE tx_size,
                        TXB_CTX *txb_ctx) {
661
  MACROBLOCKD *const xd = &x->e_mbd;
662
  TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
663
  const PLANE_TYPE plane_type = get_plane_type(plane);
664 665
  const TX_TYPE tx_type =
      av1_get_tx_type(plane_type, xd, blk_row, blk_col, block, tx_size);
666 667 668 669 670 671 672
  MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi;
  const struct macroblock_plane *p = &x->plane[plane];
  const int eob = p->eobs[block];
  const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
  int c, cost;
  int txb_skip_ctx = txb_ctx->txb_skip_ctx;

673 674 675
  const int bwl = get_txb_bwl(tx_size);
  const int width = get_txb_wide(tx_size);
  const int height = get_txb_high(tx_size);
676

Angie Chiang's avatar
Angie Chiang committed
677
  const SCAN_ORDER *const scan_order = get_scan(cm, tx_size, tx_type, mbmi);
678
  const int16_t *scan = scan_order->scan;
679 680
  uint8_t levels_buf[TX_PAD_2D];
  uint8_t *const levels = set_levels(levels_buf, width);
681
  DECLARE_ALIGNED(16, uint8_t, level_counts[MAX_TX_SQUARE]);
682

683 684
  LV_MAP_COEFF_COST *coeff_costs = &x->coeff_costs[txs_ctx][plane_type];

685 686 687
  cost = 0;

  if (eob == 0) {
688
    cost = coeff_costs->txb_skip_cost[txb_skip_ctx][1];
689 690
    return cost;
  }
691
  cost = coeff_costs->txb_skip_cost[txb_skip_ctx][0];
692

693
  av1_txb_init_levels(qcoeff, width, height, levels);
694

Angie Chiang's avatar
Angie Chiang committed
695
#if CONFIG_TXK_SEL
696
  cost += av1_tx_type_cost(cm, x, xd, mbmi->sb_type, plane, tx_size, tx_type);
Angie Chiang's avatar
Angie Chiang committed
697
#endif
698

699
  const int seg_eob = av1_get_max_eob(tx_size);
Jingning Han's avatar
Jingning Han committed
700
  int eob_cost = get_eob_cost(eob, seg_eob, coeff_costs, tx_type);
701
#if !CONFIG_LV_MAP_MULTI
Linfeng Zhang's avatar
Linfeng Zhang committed
702
  av1_get_br_level_counts(levels, width, height, level_counts);
703
#endif
Dake He's avatar
Dake He committed
704
  cost += eob_cost;
705 706 707
#if USE_CAUSAL_BASE_CTX
  int coeff_ctx = 0;
#endif
Dake He's avatar
Dake He committed
708 709 710 711
  for (c = eob - 1; c >= 0; --c) {
    tran_low_t v = qcoeff[scan[c]];
    int is_nz = (v != 0);
    int level = abs(v);
712 713
#if CONFIG_LV_MAP_MULTI
    coeff_ctx =
Linfeng Zhang's avatar
Linfeng Zhang committed
714
        get_nz_map_ctx(levels, c, scan, bwl, height, c == eob - 1, tx_type);
715 716 717 718 719 720 721 722 723
#if USE_BASE_EOB_ALPHABET
    if (c == eob - 1) {
      cost += coeff_costs
                  ->base_eob_cost[coeff_ctx - SIG_COEF_CONTEXTS +
                                  SIG_COEF_CONTEXTS_EOB][AOMMIN(level, 3) - 1];
    } else {
      cost += coeff_costs->base_cost[coeff_ctx][AOMMIN(level, 3)];
    }
#else
724
    cost += coeff_costs->base_cost[coeff_ctx][AOMMIN(level, 3)];
725
#endif
726
#else  // CONFIG_LV_MAP_MULTI
727
#if USE_CAUSAL_BASE_CTX
728
    coeff_ctx = get_nz_map_ctx(levels, c, scan, bwl, height, tx_type);
729
#endif
Dake He's avatar
Dake He committed
730 731

    if (c < eob - 1) {
732
#if !USE_CAUSAL_BASE_CTX
733
      int coeff_ctx = get_nz_map_ctx(levels, c, scan, bwl, height, tx_type);
734
#endif
Dake He's avatar
Dake He committed
735 736
      cost += coeff_costs->nz_map_cost[coeff_ctx][is_nz];
    }
737
#endif  // CONFIG_LV_MAP_MULTI
Dake He's avatar
Dake He committed
738 739

    if (is_nz) {
740
#if !USE_CAUSAL_BASE_CTX
Dake He's avatar
Dake He committed
741
      int ctx_ls[NUM_BASE_LEVELS] = { 0 };
742
#endif
Dake He's avatar
Dake He committed
743 744 745 746 747 748 749 750 751
      int sign = (v < 0) ? 1 : 0;

      // sign bit cost
      if (c == 0) {
        int dc_sign_ctx = txb_ctx->dc_sign_ctx;
        cost += coeff_costs->dc_sign_cost[dc_sign_ctx][sign];
      } else {
        cost += av1_cost_bit(128, sign);
      }
752
#if !CONFIG_LV_MAP_MULTI
753 754 755 756 757 758 759 760 761 762
#if USE_CAUSAL_BASE_CTX
      int k;
      for (k = 0; k < NUM_BASE_LEVELS; ++k) {
        int is_k = (level > (k + 1));
        int ctx = coeff_ctx;
        // get_base_ctx_from_b(c, k, b0, b1, b2);
        cost += coeff_costs->base_cost[k][ctx][is_k];
        if (is_k == 0) break;
      }
#else
763
      get_base_ctx_set(levels, scan[c], bwl, ctx_ls);
Dake He's avatar
Dake He committed
764 765 766 767 768 769 770 771 772 773 774

      int i;
      for (i = 0; i < NUM_BASE_LEVELS; ++i) {
        if (level <= i) continue;

        if (level == i + 1) {
          cost += coeff_costs->base_cost[i][ctx_ls[i]][1];
          continue;
        }
        cost += coeff_costs->base_cost[i][ctx_ls[i]][0];
      }
775
#endif
776
#endif  // CONFIG_LV_MAP_MULTI
Dake He's avatar
Dake He committed
777 778
      if (level > NUM_BASE_LEVELS) {
        int ctx;
779 780 781
#if CONFIG_LV_MAP_MULTI && USE_CAUSAL_BR_CTX
        ctx = get_br_ctx(levels, scan[c], bwl, level_counts[scan[c]], tx_type);
#else
Linfeng Zhang's avatar
Linfeng Zhang committed
782
        ctx = get_br_ctx(levels, scan[c], bwl, level_counts[scan[c]]);
783
#endif
Dake He's avatar
Dake He committed
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        int base_range = level - 1 - NUM_BASE_LEVELS;
        if (base_range < COEFF_BASE_RANGE) {
          cost += coeff_costs->lps_cost[ctx][base_range];
        } else {
          cost += coeff_costs->lps_cost[ctx][COEFF_BASE_RANGE];
        }

        if (level >= 1 + NUM_BASE_LEVELS + COEFF_BASE_RANGE) {
          // residual cost
          int r = level - COEFF_BASE_RANGE - NUM_BASE_LEVELS;
          int ri = r;
          int length = 0;

          while (ri) {
            ri >>= 1;
            ++length;
          }

          for (ri = 0; ri < length - 1; ++ri) cost += av1_cost_bit(128, 0);

          for (ri = length - 1; ri >= 0; --ri)
            cost += av1_cost_bit(128, (r >> ri) & 0x01);
        }
      }
    }
  }
810 811
  return cost;
}
Angie Chiang's avatar
Angie Chiang committed
812

813 814 815 816 817 818 819 820 821
static INLINE int has_base(tran_low_t qc, int base_idx) {
  const int level = base_idx + 1;
  return abs(qc) >= level;
}

static INLINE int has_br(tran_low_t qc) {
  return abs(qc) >= 1 + NUM_BASE_LEVELS;
}

822
static INLINE int get_sign_bit_cost(tran_low_t qc, int coeff_idx,
823
                                    const int (*dc_sign_cost)[2],
824 825 826 827
                                    int dc_sign_ctx) {
  const int sign = (qc < 0) ? 1 : 0;
  // sign bit cost
  if (coeff_idx == 0) {
828
    return dc_sign_cost[dc_sign_ctx][sign];
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
  } else {
    return av1_cost_bit(128, sign);
  }
}
static INLINE int get_golomb_cost(int abs_qc) {
  if (abs_qc >= 1 + NUM_BASE_LEVELS + COEFF_BASE_RANGE) {
    // residual cost
    int r = abs_qc - COEFF_BASE_RANGE - NUM_BASE_LEVELS;
    int ri = r;
    int length = 0;

    while (ri) {
      ri >>= 1;
      ++length;
    }

    return av1_cost_literal(2 * length - 1);
  } else {
    return 0;
  }
}

851
void gen_txb_cache(TxbCache *txb_cache, TxbInfo *txb_info) {
Angie Chiang's avatar
Angie Chiang committed
852
  // gen_nz_count_arr
853
  const int16_t *scan = txb_info->scan_order->scan;
Angie Chiang's avatar
Angie Chiang committed
854 855
  const int bwl = txb_info->bwl;
  const int height = txb_info->height;
Linfeng Zhang's avatar
Linfeng Zhang committed
856
  const tran_low_t *const qcoeff = txb_info->qcoeff;
857
  const uint8_t *const levels = txb_info->levels;
858 859
  const BASE_CTX_TABLE *base_ctx_table =
      txb_info->coeff_ctx_table->base_ctx_table;
Angie Chiang's avatar
Angie Chiang committed
860 861 862 863
  for (int c = 0; c < txb_info->eob; ++c) {
    const int coeff_idx = scan[c];  // raster order
    const int row = coeff_idx >> bwl;
    const int col = coeff_idx - (row << bwl);
Jingning Han's avatar
Jingning Han committed
864

Linfeng Zhang's avatar
Linfeng Zhang committed
865 866
    txb_cache->nz_count_arr[coeff_idx] = get_nz_count(
        levels, bwl, row, col, tx_type_to_class[txb_info->tx_type]);
Dake He's avatar
Dake He committed
867

Linfeng Zhang's avatar
Linfeng Zhang committed
868
    txb_cache->nz_ctx_arr[coeff_idx] = get_nz_map_ctx_from_stats(
869
#if USE_CAUSAL_BASE_CTX
Linfeng Zhang's avatar
Linfeng Zhang committed
870 871 872
        0,
#else
        txb_cache->nz_count_arr[coeff_idx],
873
#endif
Linfeng Zhang's avatar
Linfeng Zhang committed
874
        coeff_idx, bwl, height, txb_info->tx_type);
Angie Chiang's avatar
Angie Chiang committed
875 876 877 878

    // gen_base_count_mag_arr
    if (!has_base(qcoeff[coeff_idx], 0)) continue;
    int *base_mag = txb_cache->base_mag_arr[coeff_idx];
Angie Chiang's avatar
Angie Chiang committed
879 880
    int count[NUM_BASE_LEVELS];
    get_base_count_mag(base_mag, count, qcoeff, bwl, height, row, col);
Angie Chiang's avatar
Angie Chiang committed
881 882

    for (int i = 0; i < NUM_BASE_LEVELS; ++i) {
Angie Chiang's avatar
Angie Chiang committed
883 884
      if (!has_base(qcoeff[coeff_idx], i)) break;
      txb_cache->base_count_arr[i][coeff_idx] = count[i];
Angie Chiang's avatar
Angie Chiang committed
885
      const int level = i + 1;
Angie Chiang's avatar
Angie Chiang committed
886
      txb_cache->base_ctx_arr[i][coeff_idx] =
887
          base_ctx_table[row != 0][col != 0][base_mag[0] > level][count[i]];
Angie Chiang's avatar
Angie Chiang committed
888 889 890 891 892 893
    }

    // gen_br_count_mag_arr
    if (!has_br(qcoeff[coeff_idx])) continue;
    int *br_count = txb_cache->br_count_arr + coeff_idx;
    int *br_mag = txb_cache->br_mag_arr[coeff_idx];
Angie Chiang's avatar
Angie Chiang committed
894 895
    *br_count = get_br_count_mag(br_mag, qcoeff, bwl, height, row, col,
                                 NUM_BASE_LEVELS);
Angie Chiang's avatar
Angie Chiang committed
896 897 898
    txb_cache->br_ctx_arr[coeff_idx] =
        get_br_ctx_from_count_mag(row, col, *br_count, br_mag[0]);
  }
899 900
}

901 902 903
static INLINE const int *get_level_prob(int level, int coeff_idx,
                                        const TxbCache *txb_cache,
                                        const LV_MAP_COEFF_COST *txb_costs) {
904 905 906 907 908
#if CONFIG_LV_MAP_MULTI
  if (level < 1 + NUM_BASE_LEVELS) {
    const int ctx = txb_cache->nz_ctx_arr[coeff_idx];
    return &txb_costs->base_cost[ctx][level];
#else
909
  if (level == 0) {