vp9_bitstream.c 49.5 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5 6
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
John Koleszar's avatar
John Koleszar committed
9 10
 */

11 12 13
#include <assert.h>
#include <stdio.h>
#include <limits.h>
John Koleszar's avatar
John Koleszar committed
14

15 16 17
#include "vpx/vpx_encoder.h"
#include "vpx_mem/vpx_mem.h"

18
#include "vp9/common/vp9_entropymode.h"
19
#include "vp9/common/vp9_entropymv.h"
20
#include "vp9/common/vp9_findnearmv.h"
21
#include "vp9/common/vp9_tile_common.h"
22 23 24 25 26
#include "vp9/common/vp9_seg_common.h"
#include "vp9/common/vp9_pred_common.h"
#include "vp9/common/vp9_entropy.h"
#include "vp9/common/vp9_entropymv.h"
#include "vp9/common/vp9_mvref_common.h"
27
#include "vp9/common/vp9_treecoder.h"
28 29 30 31 32 33 34
#include "vp9/common/vp9_systemdependent.h"
#include "vp9/common/vp9_pragmas.h"

#include "vp9/encoder/vp9_mcomp.h"
#include "vp9/encoder/vp9_encodemv.h"
#include "vp9/encoder/vp9_bitstream.h"
#include "vp9/encoder/vp9_segmentation.h"
35
#include "vp9/encoder/vp9_subexp.h"
36 37
#include "vp9/encoder/vp9_write_bit_buffer.h"

Paul Wilkins's avatar
Paul Wilkins committed
38

John Koleszar's avatar
John Koleszar committed
39 40 41 42 43
#if defined(SECTIONBITS_OUTPUT)
unsigned __int64 Sectionbits[500];
#endif

#ifdef ENTROPY_STATS
44 45 46
int intra_mode_stats[VP9_INTRA_MODES]
                    [VP9_INTRA_MODES]
                    [VP9_INTRA_MODES];
47
vp9_coeff_stats tree_update_hist[TX_SIZE_MAX_SB][BLOCK_TYPES];
48

John Koleszar's avatar
John Koleszar committed
49 50 51
extern unsigned int active_section;
#endif

52

53
#ifdef MODE_STATS
54 55 56
int64_t tx_count_32x32p_stats[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB];
int64_t tx_count_16x16p_stats[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB - 1];
int64_t tx_count_8x8p_stats[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB - 2];
57 58
int64_t switchable_interp_stats[VP9_SWITCHABLE_FILTERS+1]
                               [VP9_SWITCHABLE_FILTERS];
59 60 61 62 63 64 65

void init_tx_count_stats() {
  vp9_zero(tx_count_32x32p_stats);
  vp9_zero(tx_count_16x16p_stats);
  vp9_zero(tx_count_8x8p_stats);
}

66 67 68 69
void init_switchable_interp_stats() {
  vp9_zero(switchable_interp_stats);
}

70 71
static void update_tx_count_stats(VP9_COMMON *cm) {
  int i, j;
72
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
73 74 75 76
    for (j = 0; j < TX_SIZE_MAX_SB; j++) {
      tx_count_32x32p_stats[i][j] += cm->fc.tx_count_32x32p[i][j];
    }
  }
77
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
78 79 80 81
    for (j = 0; j < TX_SIZE_MAX_SB - 1; j++) {
      tx_count_16x16p_stats[i][j] += cm->fc.tx_count_16x16p[i][j];
    }
  }
82
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
83 84 85 86 87 88
    for (j = 0; j < TX_SIZE_MAX_SB - 2; j++) {
      tx_count_8x8p_stats[i][j] += cm->fc.tx_count_8x8p[i][j];
    }
  }
}

89 90 91 92 93 94 95 96
static void update_switchable_interp_stats(VP9_COMMON *cm) {
  int i, j;
  for (i = 0; i < VP9_SWITCHABLE_FILTERS+1; ++i)
    for (j = 0; j < VP9_SWITCHABLE_FILTERS; ++j) {
      switchable_interp_stats[i][j] += cm->fc.switchable_interp_count[i][j];
    }
}

97 98 99 100 101 102 103 104
void write_tx_count_stats() {
  int i, j;
  FILE *fp = fopen("tx_count.bin", "wb");
  fwrite(tx_count_32x32p_stats, sizeof(tx_count_32x32p_stats), 1, fp);
  fwrite(tx_count_16x16p_stats, sizeof(tx_count_16x16p_stats), 1, fp);
  fwrite(tx_count_8x8p_stats, sizeof(tx_count_8x8p_stats), 1, fp);
  fclose(fp);

105 106 107 108
  printf(
      "vp9_default_tx_count_32x32p[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB] = {\n");
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
    printf("  { ");
109 110 111 112 113 114
    for (j = 0; j < TX_SIZE_MAX_SB; j++) {
      printf("%"PRId64", ", tx_count_32x32p_stats[i][j]);
    }
    printf("},\n");
  }
  printf("};\n");
115 116 117 118
  printf(
      "vp9_default_tx_count_16x16p[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB-1] = {\n");
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
    printf("  { ");
119 120 121 122 123 124
    for (j = 0; j < TX_SIZE_MAX_SB - 1; j++) {
      printf("%"PRId64", ", tx_count_16x16p_stats[i][j]);
    }
    printf("},\n");
  }
  printf("};\n");
125 126 127 128
  printf(
      "vp9_default_tx_count_8x8p[TX_SIZE_CONTEXTS][TX_SIZE_MAX_SB-2] = {\n");
  for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
    printf("  { ");
129 130 131 132 133 134 135
    for (j = 0; j < TX_SIZE_MAX_SB - 2; j++) {
      printf("%"PRId64", ", tx_count_8x8p_stats[i][j]);
    }
    printf("},\n");
  }
  printf("};\n");
}
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

void write_switchable_interp_stats() {
  int i, j;
  FILE *fp = fopen("switchable_interp.bin", "wb");
  fwrite(switchable_interp_stats, sizeof(switchable_interp_stats), 1, fp);
  fclose(fp);

  printf(
      "vp9_default_switchable_filter_count[VP9_SWITCHABLE_FILTERS+1]"
      "[VP9_SWITCHABLE_FILTERS] = {\n");
  for (i = 0; i < VP9_SWITCHABLE_FILTERS+1; i++) {
    printf("  { ");
    for (j = 0; j < VP9_SWITCHABLE_FILTERS; j++) {
      printf("%"PRId64", ", switchable_interp_stats[i][j]);
    }
    printf("},\n");
  }
  printf("};\n");
}
155 156
#endif

157 158 159 160 161
static INLINE void write_be32(uint8_t *p, int value) {
  p[0] = value >> 24;
  p[1] = value >> 16;
  p[2] = value >> 8;
  p[3] = value;
162 163
}

164 165 166 167 168
void vp9_encode_unsigned_max(struct vp9_write_bit_buffer *wb,
                             int data, int max) {
  vp9_wb_write_literal(wb, data, get_unsigned_bits(max));
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
static void update_mode(
  vp9_writer *w,
  int n,
  const struct vp9_token tok[/* n */],
  vp9_tree tree,
  vp9_prob Pnew[/* n-1 */],
  vp9_prob Pcur[/* n-1 */],
  unsigned int bct[/* n-1 */] [2],
  const unsigned int num_events[/* n */]
) {
  int i = 0;

  vp9_tree_probs_from_distribution(tree, Pnew, bct, num_events, 0);
  n--;

  for (i = 0; i < n; ++i) {
185
    vp9_cond_prob_diff_update(w, &Pcur[i], VP9_MODE_UPDATE_PROB, bct[i]);
186 187 188 189 190 191
  }
}

static void update_mbintra_mode_probs(VP9_COMP* const cpi,
                                      vp9_writer* const bc) {
  VP9_COMMON *const cm = &cpi->common;
192
  int j;
193 194 195
  vp9_prob pnew[VP9_INTRA_MODES - 1];
  unsigned int bct[VP9_INTRA_MODES - 1][2];

196 197 198 199 200
  for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
    update_mode(bc, VP9_INTRA_MODES, vp9_intra_mode_encodings,
                vp9_intra_mode_tree, pnew,
                cm->fc.y_mode_prob[j], bct,
                (unsigned int *)cpi->y_mode_count[j]);
201 202
}

203 204
static void write_selected_txfm_size(const VP9_COMP *cpi, TX_SIZE tx_size,
                                     BLOCK_SIZE_TYPE bsize, vp9_writer *w) {
205
  const VP9_COMMON *const cm = &cpi->common;
206
  const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
207
  const vp9_prob *tx_probs = vp9_get_pred_probs_tx_size(xd, &cm->fc.tx_probs);
208 209 210 211 212 213 214 215
  vp9_write(w, tx_size != TX_4X4, tx_probs[0]);
  if (bsize >= BLOCK_SIZE_MB16X16 && tx_size != TX_4X4) {
    vp9_write(w, tx_size != TX_8X8, tx_probs[1]);
    if (bsize >= BLOCK_SIZE_SB32X32 && tx_size != TX_8X8)
      vp9_write(w, tx_size != TX_16X16, tx_probs[2]);
  }
}

216 217 218
static int write_skip_coeff(const VP9_COMP *cpi, int segment_id, MODE_INFO *m,
                            vp9_writer *w) {
  const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
219
  if (vp9_segfeature_active(&xd->seg, segment_id, SEG_LVL_SKIP)) {
220 221 222
    return 1;
  } else {
    const int skip_coeff = m->mbmi.mb_skip_coeff;
223
    vp9_write(w, skip_coeff, vp9_get_pred_prob_mbskip(&cpi->common, xd));
224 225 226 227
    return skip_coeff;
  }
}

228 229
void vp9_update_skip_probs(VP9_COMP *cpi, vp9_writer *w) {
  FRAME_CONTEXT *const fc = &cpi->common.fc;
230 231
  int k;

232 233 234
  for (k = 0; k < MBSKIP_CONTEXTS; ++k)
    vp9_cond_prob_diff_update(w, &fc->mbskip_probs[k],
                              VP9_MODE_UPDATE_PROB, fc->mbskip_count[k]);
235 236 237 238 239 240
}

static void write_intra_mode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_intra_mode_tree, p, vp9_intra_mode_encodings + m);
}

241
static void update_switchable_interp_probs(VP9_COMP *const cpi,
242
                                           vp9_writer* const bc) {
243
  VP9_COMMON *const pc = &cpi->common;
244 245 246 247 248 249 250 251 252 253 254 255 256
  unsigned int branch_ct[VP9_SWITCHABLE_FILTERS + 1]
                        [VP9_SWITCHABLE_FILTERS - 1][2];
  vp9_prob new_prob[VP9_SWITCHABLE_FILTERS + 1][VP9_SWITCHABLE_FILTERS - 1];
  int i, j;
  for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
    vp9_tree_probs_from_distribution(
        vp9_switchable_interp_tree,
        new_prob[j], branch_ct[j],
        pc->fc.switchable_interp_count[j], 0);
  }
  for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
    for (i = 0; i < VP9_SWITCHABLE_FILTERS - 1; ++i) {
      vp9_cond_prob_diff_update(bc, &pc->fc.switchable_interp_prob[j][i],
257
                                VP9_MODE_UPDATE_PROB, branch_ct[j][i]);
258 259
    }
  }
260 261 262 263
#ifdef MODE_STATS
  if (!cpi->dummy_packing)
    update_switchable_interp_stats(pc);
#endif
264 265 266 267 268 269
}

static void update_inter_mode_probs(VP9_COMMON *pc, vp9_writer* const bc) {
  int i, j;

  for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
270
    for (j = 0; j < VP9_INTER_MODES - 1; j++) {
271
      vp9_cond_prob_diff_update(bc, &pc->fc.inter_mode_probs[i][j],
272
                                VP9_MODE_UPDATE_PROB,
273 274 275 276 277
                                pc->fc.inter_mode_counts[i][j]);
    }
  }
}

278
static void pack_mb_tokens(vp9_writer* const bc,
279 280 281
                           TOKENEXTRA **tp,
                           const TOKENEXTRA *const stop) {
  TOKENEXTRA *p = *tp;
John Koleszar's avatar
John Koleszar committed
282

John Koleszar's avatar
John Koleszar committed
283
  while (p < stop) {
284
    const int t = p->token;
285
    const struct vp9_token *const a = vp9_coef_encodings + t;
286
    const vp9_extra_bit *const b = vp9_extra_bits + t;
John Koleszar's avatar
John Koleszar committed
287
    int i = 0;
288
    const vp9_prob *pp;
John Koleszar's avatar
John Koleszar committed
289
    int v = a->value;
290
    int n = a->len;
291
    vp9_prob probs[ENTROPY_NODES];
John Koleszar's avatar
John Koleszar committed
292

293
    if (t == EOSB_TOKEN) {
294 295 296
      ++p;
      break;
    }
297
    if (t >= TWO_TOKEN) {
298
      vp9_model_to_full_probs(p->context_tree, probs);
299 300 301 302
      pp = probs;
    } else {
      pp = p->context_tree;
    }
303
    assert(pp != 0);
304

John Koleszar's avatar
John Koleszar committed
305
    /* skip one or two nodes */
306
#if !CONFIG_BALANCED_COEFTREE
John Koleszar's avatar
John Koleszar committed
307 308 309 310
    if (p->skip_eob_node) {
      n -= p->skip_eob_node;
      i = 2 * p->skip_eob_node;
    }
311
#endif
John Koleszar's avatar
John Koleszar committed
312

John Koleszar's avatar
John Koleszar committed
313 314
    do {
      const int bb = (v >> --n) & 1;
315 316 317 318 319 320 321
#if CONFIG_BALANCED_COEFTREE
      if (i == 2 && p->skip_eob_node) {
        i += 2;
        assert(bb == 1);
        continue;
      }
#endif
322
      vp9_write(bc, bb, pp[i >> 1]);
323
      i = vp9_coef_tree[i + bb];
324
    } while (n);
John Koleszar's avatar
John Koleszar committed
325

John Koleszar's avatar
John Koleszar committed
326
    if (b->base_val) {
327
      const int e = p->extra, l = b->len;
John Koleszar's avatar
John Koleszar committed
328

329
      if (l) {
330
        const unsigned char *pb = b->prob;
John Koleszar's avatar
John Koleszar committed
331
        int v = e >> 1;
332
        int n = l;              /* number of bits in v, assumed nonzero */
John Koleszar's avatar
John Koleszar committed
333
        int i = 0;
John Koleszar's avatar
John Koleszar committed
334

John Koleszar's avatar
John Koleszar committed
335 336
        do {
          const int bb = (v >> --n) & 1;
337
          vp9_write(bc, bb, pb[i >> 1]);
John Koleszar's avatar
John Koleszar committed
338 339 340
          i = b->tree[i + bb];
        } while (n);
      }
John Koleszar's avatar
John Koleszar committed
341

342
      vp9_write_bit(bc, e & 1);
John Koleszar's avatar
John Koleszar committed
343
    }
John Koleszar's avatar
John Koleszar committed
344 345 346
    ++p;
  }

347
  *tp = p;
John Koleszar's avatar
John Koleszar committed
348 349
}

350
static void write_sb_mv_ref(vp9_writer *w, MB_PREDICTION_MODE mode,
351
                            const vp9_prob *p) {
352
  assert(is_inter_mode(mode));
353 354
  write_token(w, vp9_inter_mode_tree, p,
              &vp9_inter_mode_encodings[mode - NEARESTMV]);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
355 356
}

357

358
static void write_segment_id(vp9_writer *w, const struct segmentation *seg,
359
                             int segment_id) {
360 361
  if (seg->enabled && seg->update_map)
    treed_write(w, vp9_segment_tree, seg->tree_probs, segment_id, 3);
John Koleszar's avatar
John Koleszar committed
362 363
}

Paul Wilkins's avatar
Paul Wilkins committed
364
// This function encodes the reference frame
Ronald S. Bultje's avatar
Ronald S. Bultje committed
365 366 367 368 369 370
static void encode_ref_frame(VP9_COMP *cpi, vp9_writer *bc) {
  VP9_COMMON *const pc = &cpi->common;
  MACROBLOCK *const x = &cpi->mb;
  MACROBLOCKD *const xd = &x->e_mbd;
  MB_MODE_INFO *mi = &xd->mode_info_context->mbmi;
  const int segment_id = mi->segment_id;
371
  int seg_ref_active = vp9_segfeature_active(&xd->seg, segment_id,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
372
                                             SEG_LVL_REF_FRAME);
John Koleszar's avatar
John Koleszar committed
373 374
  // If segment level coding of this signal is disabled...
  // or the segment allows multiple reference frame options
375
  if (!seg_ref_active) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
376 377 378 379
    // does the feature use compound prediction or not
    // (if not specified at the frame/segment level)
    if (pc->comp_pred_mode == HYBRID_PREDICTION) {
      vp9_write(bc, mi->ref_frame[1] > INTRA_FRAME,
380
                vp9_get_pred_prob_comp_inter_inter(pc, xd));
Ronald S. Bultje's avatar
Ronald S. Bultje committed
381 382 383 384
    } else {
      assert((mi->ref_frame[1] <= INTRA_FRAME) ==
                 (pc->comp_pred_mode == SINGLE_PREDICTION_ONLY));
    }
385

Ronald S. Bultje's avatar
Ronald S. Bultje committed
386 387
    if (mi->ref_frame[1] > INTRA_FRAME) {
      vp9_write(bc, mi->ref_frame[0] == GOLDEN_FRAME,
388
                vp9_get_pred_prob_comp_ref_p(pc, xd));
Ronald S. Bultje's avatar
Ronald S. Bultje committed
389 390
    } else {
      vp9_write(bc, mi->ref_frame[0] != LAST_FRAME,
391
                vp9_get_pred_prob_single_ref_p1(pc, xd));
Ronald S. Bultje's avatar
Ronald S. Bultje committed
392 393
      if (mi->ref_frame[0] != LAST_FRAME)
        vp9_write(bc, mi->ref_frame[0] != GOLDEN_FRAME,
394
                  vp9_get_pred_prob_single_ref_p2(pc, xd));
Paul Wilkins's avatar
Paul Wilkins committed
395
    }
Ronald S. Bultje's avatar
Ronald S. Bultje committed
396 397
  } else {
    assert(mi->ref_frame[1] <= INTRA_FRAME);
398
    assert(vp9_get_segdata(&xd->seg, segment_id, SEG_LVL_REF_FRAME) ==
399
           mi->ref_frame[0]);
John Koleszar's avatar
John Koleszar committed
400
  }
Paul Wilkins's avatar
Paul Wilkins committed
401

John Koleszar's avatar
John Koleszar committed
402 403
  // if using the prediction mdoel we have nothing further to do because
  // the reference frame is fully coded by the segment
Paul Wilkins's avatar
Paul Wilkins committed
404
}
John Koleszar's avatar
John Koleszar committed
405

Ronald S. Bultje's avatar
Ronald S. Bultje committed
406
static void pack_inter_mode_mvs(VP9_COMP *cpi, MODE_INFO *m,
407
                                vp9_writer *bc, int mi_row, int mi_col) {
408
  VP9_COMMON *const pc = &cpi->common;
409
  const nmv_context *nmvc = &pc->fc.nmvc;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
410 411
  MACROBLOCK *const x = &cpi->mb;
  MACROBLOCKD *const xd = &x->e_mbd;
412
  struct segmentation *seg = &xd->seg;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
413
  MB_MODE_INFO *const mi = &m->mbmi;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
414
  const MV_REFERENCE_FRAME rf = mi->ref_frame[0];
Ronald S. Bultje's avatar
Ronald S. Bultje committed
415 416 417
  const MB_PREDICTION_MODE mode = mi->mode;
  const int segment_id = mi->segment_id;
  int skip_coeff;
Scott LaVarnway's avatar
Scott LaVarnway committed
418
  const BLOCK_SIZE_TYPE bsize = mi->sb_type;
Adrian Grange's avatar
Adrian Grange committed
419

Ronald S. Bultje's avatar
Ronald S. Bultje committed
420
  x->partition_info = x->pi + (m - pc->mi);
421

Ronald S. Bultje's avatar
Ronald S. Bultje committed
422 423
#ifdef ENTROPY_STATS
  active_section = 9;
424
#endif
425

426 427
  if (seg->update_map) {
    if (seg->temporal_update) {
Scott LaVarnway's avatar
Scott LaVarnway committed
428
      const int pred_flag = mi->seg_id_predicted;
429 430 431 432
      vp9_prob pred_prob = vp9_get_pred_prob_seg_id(xd);
      vp9_write(bc, pred_flag, pred_prob);
      if (!pred_flag)
        write_segment_id(bc, seg, segment_id);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
433
    } else {
434
      write_segment_id(bc, seg, segment_id);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
435 436
    }
  }
437

438
  skip_coeff = write_skip_coeff(cpi, segment_id, m, bc);
John Koleszar's avatar
John Koleszar committed
439

440
  if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
441
    vp9_write(bc, rf != INTRA_FRAME,
442
              vp9_get_pred_prob_intra_inter(pc, xd));
Paul Wilkins's avatar
Paul Wilkins committed
443

Scott LaVarnway's avatar
Scott LaVarnway committed
444
  if (bsize >= BLOCK_SIZE_SB8X8 && pc->tx_mode == TX_MODE_SELECT &&
445
      !(rf != INTRA_FRAME &&
446
        (skip_coeff || vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)))) {
Scott LaVarnway's avatar
Scott LaVarnway committed
447
    write_selected_txfm_size(cpi, mi->txfm_size, bsize, bc);
448 449
  }

Ronald S. Bultje's avatar
Ronald S. Bultje committed
450
  if (rf == INTRA_FRAME) {
451
#ifdef ENTROPY_STATS
Ronald S. Bultje's avatar
Ronald S. Bultje committed
452
    active_section = 6;
453
#endif
Paul Wilkins's avatar
Paul Wilkins committed
454

Scott LaVarnway's avatar
Scott LaVarnway committed
455
    if (bsize >= BLOCK_SIZE_SB8X8) {
456 457 458
      const int bwl = b_width_log2(bsize), bhl = b_height_log2(bsize);
      const int bsl = MIN(bwl, bhl);
      write_intra_mode(bc, mode, pc->fc.y_mode_prob[MIN(3, bsl)]);
459
    } else {
460
      int idx, idy;
Scott LaVarnway's avatar
Scott LaVarnway committed
461 462
      int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
      int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
Jim Bankoski's avatar
Jim Bankoski committed
463 464
      for (idy = 0; idy < 2; idy += num_4x4_blocks_high)
        for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
465
          const MB_PREDICTION_MODE bm = m->bmi[idy * 2 + idx].as_mode;
466 467
          write_intra_mode(bc, bm, pc->fc.y_mode_prob[0]);
        }
Ronald S. Bultje's avatar
Ronald S. Bultje committed
468
    }
469
    write_intra_mode(bc, mi->uv_mode, pc->fc.uv_mode_prob[mode]);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
470
  } else {
471
    vp9_prob *mv_ref_p;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
472
    encode_ref_frame(cpi, bc);
473
    mv_ref_p = cpi->common.fc.inter_mode_probs[mi->mb_mode_context[rf]];
Yaowu Xu's avatar
Yaowu Xu committed
474

John Koleszar's avatar
John Koleszar committed
475
#ifdef ENTROPY_STATS
Ronald S. Bultje's avatar
Ronald S. Bultje committed
476
    active_section = 3;
John Koleszar's avatar
John Koleszar committed
477 478
#endif

479
    // If segment skip is not enabled code the mode.
480
    if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)) {
Scott LaVarnway's avatar
Scott LaVarnway committed
481
      if (bsize >= BLOCK_SIZE_SB8X8) {
482
        write_sb_mv_ref(bc, mode, mv_ref_p);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
483 484
        vp9_accum_mv_refs(&cpi->common, mode, mi->mb_mode_context[rf]);
      }
Ronald S. Bultje's avatar
Ronald S. Bultje committed
485
    }
486

Ronald S. Bultje's avatar
Ronald S. Bultje committed
487 488
    if (cpi->common.mcomp_filter_type == SWITCHABLE) {
      write_token(bc, vp9_switchable_interp_tree,
489
                  vp9_get_pred_probs_switchable_interp(&cpi->common, xd),
Ronald S. Bultje's avatar
Ronald S. Bultje committed
490 491 492 493
                  vp9_switchable_interp_encodings +
                  vp9_switchable_interp_map[mi->interp_filter]);
    } else {
      assert(mi->interp_filter == cpi->common.mcomp_filter_type);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
494
    }
495

Scott LaVarnway's avatar
Scott LaVarnway committed
496
    if (bsize < BLOCK_SIZE_SB8X8) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
497 498 499
      int j;
      MB_PREDICTION_MODE blockmode;
      int_mv blockmv;
Scott LaVarnway's avatar
Scott LaVarnway committed
500 501
      int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
      int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
Ronald S. Bultje's avatar
Ronald S. Bultje committed
502
      int idx, idy;
Jim Bankoski's avatar
Jim Bankoski committed
503 504
      for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
        for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
505
          j = idy * 2 + idx;
Scott LaVarnway's avatar
Scott LaVarnway committed
506
          blockmode = x->partition_info->bmi[j].mode;
507
          blockmv = m->bmi[j].as_mv[0];
Ronald S. Bultje's avatar
Ronald S. Bultje committed
508 509 510
          write_sb_mv_ref(bc, blockmode, mv_ref_p);
          vp9_accum_mv_refs(&cpi->common, blockmode, mi->mb_mode_context[rf]);
          if (blockmode == NEWMV) {
511
#ifdef ENTROPY_STATS
Ronald S. Bultje's avatar
Ronald S. Bultje committed
512
            active_section = 11;
513
#endif
Paul Wilkins's avatar
Paul Wilkins committed
514
            vp9_encode_mv(cpi, bc, &blockmv.as_mv, &mi->best_mv.as_mv,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
515
                          nmvc, xd->allow_high_precision_mv);
516

Ronald S. Bultje's avatar
Ronald S. Bultje committed
517
            if (mi->ref_frame[1] > INTRA_FRAME)
Paul Wilkins's avatar
Paul Wilkins committed
518
              vp9_encode_mv(cpi, bc,
519
                            &m->bmi[j].as_mv[1].as_mv,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
520
                            &mi->best_second_mv.as_mv,
521
                            nmvc, xd->allow_high_precision_mv);
John Koleszar's avatar
John Koleszar committed
522
          }
523
        }
Ronald S. Bultje's avatar
Ronald S. Bultje committed
524 525 526 527 528
      }
    } else if (mode == NEWMV) {
#ifdef ENTROPY_STATS
      active_section = 5;
#endif
Paul Wilkins's avatar
Paul Wilkins committed
529
      vp9_encode_mv(cpi, bc,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
530 531 532
                    &mi->mv[0].as_mv, &mi->best_mv.as_mv,
                    nmvc, xd->allow_high_precision_mv);

Ronald S. Bultje's avatar
Ronald S. Bultje committed
533
      if (mi->ref_frame[1] > INTRA_FRAME)
Paul Wilkins's avatar
Paul Wilkins committed
534
        vp9_encode_mv(cpi, bc,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
535 536
                      &mi->mv[1].as_mv, &mi->best_second_mv.as_mv,
                      nmvc, xd->allow_high_precision_mv);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
537 538
    }
  }
John Koleszar's avatar
John Koleszar committed
539
}
540

Ronald S. Bultje's avatar
Ronald S. Bultje committed
541
static void write_mb_modes_kf(const VP9_COMP *cpi,
542
                              MODE_INFO *m,
543
                              vp9_writer *bc, int mi_row, int mi_col) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
544 545 546
  const VP9_COMMON *const c = &cpi->common;
  const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
  const int ym = m->mbmi.mode;
547
  const int mis = c->mode_info_stride;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
548
  const int segment_id = m->mbmi.segment_id;
549

550 551
  if (xd->seg.update_map)
    write_segment_id(bc, &xd->seg, m->mbmi.segment_id);
552

553
  write_skip_coeff(cpi, segment_id, m, bc);
554

555
  if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8 && c->tx_mode == TX_MODE_SELECT)
556
    write_selected_txfm_size(cpi, m->mbmi.txfm_size, m->mbmi.sb_type, bc);
557

558
  if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8) {
Yaowu Xu's avatar
Yaowu Xu committed
559 560
    const MB_PREDICTION_MODE A = above_block_mode(m, 0, mis);
    const MB_PREDICTION_MODE L = xd->left_available ?
561
                                 left_block_mode(m, 0) : DC_PRED;
562
    write_intra_mode(bc, ym, vp9_kf_y_mode_prob[A][L]);
563
  } else {
564
    int idx, idy;
Jim Bankoski's avatar
Jim Bankoski committed
565 566 567 568
    int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[m->mbmi.sb_type];
    int num_4x4_blocks_high = num_4x4_blocks_high_lookup[m->mbmi.sb_type];
    for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
      for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
569
        int i = idy * 2 + idx;
Yaowu Xu's avatar
Yaowu Xu committed
570 571
        const MB_PREDICTION_MODE A = above_block_mode(m, i, mis);
        const MB_PREDICTION_MODE L = (xd->left_available || idx) ?
572
                                     left_block_mode(m, i) : DC_PRED;
573
        const int bm = m->bmi[i].as_mode;
574 575 576
#ifdef ENTROPY_STATS
        ++intra_mode_stats[A][L][bm];
#endif
577
        write_intra_mode(bc, bm, vp9_kf_y_mode_prob[A][L]);
578 579
      }
    }
580 581
  }

582
  write_intra_mode(bc, m->mbmi.uv_mode, vp9_kf_uv_mode_prob[ym]);
583 584
}

Ronald S. Bultje's avatar
Ronald S. Bultje committed
585 586
static void write_modes_b(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
                          TOKENEXTRA **tok, TOKENEXTRA *tok_end,
587
                          int mi_row, int mi_col) {
588
  VP9_COMMON *const cm = &cpi->common;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
589 590
  MACROBLOCKD *const xd = &cpi->mb.e_mbd;

591 592 593
  if (m->mbmi.sb_type < BLOCK_SIZE_SB8X8)
    if (xd->ab_index > 0)
      return;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
594
  xd->mode_info_context = m;
595 596 597
  set_mi_row_col(&cpi->common, xd, mi_row,
                 1 << mi_height_log2(m->mbmi.sb_type),
                 mi_col, 1 << mi_width_log2(m->mbmi.sb_type));
Adrian Grange's avatar
Adrian Grange committed
598
  if ((cm->frame_type == KEY_FRAME) || cm->intra_only) {
599
    write_mb_modes_kf(cpi, m, bc, mi_row, mi_col);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
600 601 602 603
#ifdef ENTROPY_STATS
    active_section = 8;
#endif
  } else {
604
    pack_inter_mode_mvs(cpi, m, bc, mi_row, mi_col);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
605 606 607 608 609 610 611 612 613
#ifdef ENTROPY_STATS
    active_section = 1;
#endif
  }

  assert(*tok < tok_end);
  pack_mb_tokens(bc, tok, tok_end);
}

614 615
static void write_modes_sb(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
                           TOKENEXTRA **tok, TOKENEXTRA *tok_end,
616
                           int mi_row, int mi_col,
617 618
                           BLOCK_SIZE_TYPE bsize) {
  VP9_COMMON *const cm = &cpi->common;
619
  MACROBLOCKD *xd = &cpi->mb.e_mbd;
620
  const int mis = cm->mode_info_stride;
621 622
  int bsl = b_width_log2(bsize);
  int bs = (1 << bsl) / 4;  // mode_info step for subsize
623
  int n;
624
  PARTITION_TYPE partition = PARTITION_NONE;
625 626
  BLOCK_SIZE_TYPE subsize;

627
  if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
628 629
    return;

Jim Bankoski's avatar
Jim Bankoski committed
630
  partition = partition_lookup[bsl][m->mbmi.sb_type];
631

632
  if (bsize < BLOCK_SIZE_SB8X8)
633
    if (xd->ab_index > 0)
634 635 636
      return;

  if (bsize >= BLOCK_SIZE_SB8X8) {
637
    int pl;
638 639
    const int idx = check_bsize_coverage(cm, xd, mi_row, mi_col, bsize);
    set_partition_seg_context(cm, xd, mi_row, mi_col);
640
    pl = partition_plane_context(xd, bsize);
641
    // encode the partition information
642 643 644 645 646 647 648
    if (idx == 0)
      write_token(bc, vp9_partition_tree,
                  cm->fc.partition_prob[cm->frame_type][pl],
                  vp9_partition_encodings + partition);
    else if (idx > 0)
      vp9_write(bc, partition == PARTITION_SPLIT,
                cm->fc.partition_prob[cm->frame_type][pl][idx]);
649
  }
650

651
  subsize = get_subsize(bsize, partition);
652
  *(get_sb_index(xd, subsize)) = 0;
653

654 655
  switch (partition) {
    case PARTITION_NONE:
656
      write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
657 658
      break;
    case PARTITION_HORZ:
659
      write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
660
      *(get_sb_index(xd, subsize)) = 1;
661 662
      if ((mi_row + bs) < cm->mi_rows)
        write_modes_b(cpi, m + bs * mis, bc, tok, tok_end, mi_row + bs, mi_col);
663 664
      break;
    case PARTITION_VERT:
665
      write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
666
      *(get_sb_index(xd, subsize)) = 1;
667 668
      if ((mi_col + bs) < cm->mi_cols)
        write_modes_b(cpi, m + bs, bc, tok, tok_end, mi_row, mi_col + bs);
669 670 671 672
      break;
    case PARTITION_SPLIT:
      for (n = 0; n < 4; n++) {
        int j = n >> 1, i = n & 0x01;
673
        *(get_sb_index(xd, subsize)) = n;
674
        write_modes_sb(cpi, m + j * bs * mis + i * bs, bc, tok, tok_end,
675
                       mi_row + j * bs, mi_col + i * bs, subsize);
676 677 678 679 680
      }
      break;
    default:
      assert(0);
  }
681 682

  // update partition context
683 684
  if (bsize >= BLOCK_SIZE_SB8X8 &&
      (bsize == BLOCK_SIZE_SB8X8 || partition != PARTITION_SPLIT)) {
685 686 687
    set_partition_seg_context(cm, xd, mi_row, mi_col);
    update_partition_context(xd, subsize, bsize);
  }
688 689
}

690
static void write_modes(VP9_COMP *cpi, vp9_writer* const bc,
Ronald S. Bultje's avatar
Ronald S. Bultje committed
691
                        TOKENEXTRA **tok, TOKENEXTRA *tok_end) {
692
  VP9_COMMON *const c = &cpi->common;
John Koleszar's avatar
John Koleszar committed
693
  const int mis = c->mode_info_stride;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
694
  MODE_INFO *m, *m_ptr = c->mi;
695
  int mi_row, mi_col;
John Koleszar's avatar
John Koleszar committed
696

697
  m_ptr += c->cur_tile_mi_col_start + c->cur_tile_mi_row_start * mis;
698

699
  for (mi_row = c->cur_tile_mi_row_start; mi_row < c->cur_tile_mi_row_end;
Jingning Han's avatar
Jingning Han committed
700
       mi_row += 8, m_ptr += 8 * mis) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
701
    m = m_ptr;
702
    vp9_zero(c->left_seg_context);
703 704
    for (mi_col = c->cur_tile_mi_col_start; mi_col < c->cur_tile_mi_col_end;
         mi_col += MI_BLOCK_SIZE, m += MI_BLOCK_SIZE)
705
      write_modes_sb(cpi, m, bc, tok, tok_end, mi_row, mi_col,
706
                     BLOCK_SIZE_SB64X64);
John Koleszar's avatar
John Koleszar committed
707
  }
John Koleszar's avatar
John Koleszar committed
708
}
709

710
/* This function is used for debugging probability trees. */
711
static void print_prob_tree(vp9_coeff_probs *coef_probs, int block_types) {
John Koleszar's avatar
John Koleszar committed
712
  /* print coef probability tree */
713
  int i, j, k, l, m;
John Koleszar's avatar
John Koleszar committed
714 715
  FILE *f = fopen("enc_tree_probs.txt", "a");
  fprintf(f, "{\n");
716
  for (i = 0; i < block_types; i++) {
John Koleszar's avatar
John Koleszar committed
717
    fprintf(f, "  {\n");
718 719 720 721 722 723 724 725 726 727
    for (j = 0; j < REF_TYPES; ++j) {
      fprintf(f, "  {\n");
      for (k = 0; k < COEF_BANDS; k++) {
        fprintf(f, "    {\n");
        for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
          fprintf(f, "      {");
          for (m = 0; m < ENTROPY_NODES; m++) {
            fprintf(f, "%3u, ",
                    (unsigned int)(coef_probs[i][j][k][l][m]));
          }
728
        }
John Koleszar's avatar
John Koleszar committed
729 730 731
        fprintf(f, " }\n");
      }
      fprintf(f, "    }\n");
732
    }
John Koleszar's avatar
John Koleszar committed
733 734 735 736
    fprintf(f, "  }\n");
  }
  fprintf(f, "}\n");
  fclose(f);
737 738
}

739 740 741 742 743 744
static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE txfm_size) {
  vp9_coeff_probs_model *coef_probs = cpi->frame_coef_probs[txfm_size];
  vp9_coeff_count *coef_counts = cpi->coef_counts[txfm_size];
  unsigned int (*eob_branch_ct)[REF_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS] =
      cpi->common.fc.eob_branch_counts[txfm_size];
  vp9_coeff_stats *coef_branch_ct = cpi->frame_branch_ct[txfm_size];
745
  vp9_prob full_probs[ENTROPY_NODES];
746
  int i, j, k, l;
747

748
  for (i = 0; i < BLOCK_TYPES; ++i) {
749 750 751 752 753
    for (j = 0; j < REF_TYPES; ++j) {
      for (k = 0; k < COEF_BANDS; ++k) {
        for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
          if (l >= 3 && k == 0)
            continue;
754 755
          vp9_tree_probs_from_distribution(vp9_coef_tree,
                                           full_probs,
756
                                           coef_branch_ct[i][j][k][l],
757 758 759
                                           coef_counts[i][j][k][l], 0);
          vpx_memcpy(coef_probs[i][j][k][l], full_probs,
                     sizeof(vp9_prob) * UNCONSTRAINED_NODES);
760 761 762 763 764