vp9_bitstream.c 73.7 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
#include "vp9/common/vp9_header.h"
13
#include "vp9/encoder/vp9_encodemv.h"
14 15
#include "vp9/common/vp9_entropymode.h"
#include "vp9/common/vp9_findnearmv.h"
16
#include "vp9/encoder/vp9_mcomp.h"
17
#include "vp9/common/vp9_systemdependent.h"
John Koleszar's avatar
John Koleszar committed
18 19
#include <assert.h>
#include <stdio.h>
20
#include <limits.h>
21
#include "vp9/common/vp9_pragmas.h"
22
#include "vpx/vpx_encoder.h"
John Koleszar's avatar
John Koleszar committed
23
#include "vpx_mem/vpx_mem.h"
24 25
#include "vp9/encoder/vp9_bitstream.h"
#include "vp9/encoder/vp9_segmentation.h"
26

27 28 29 30 31 32
#include "vp9/common/vp9_seg_common.h"
#include "vp9/common/vp9_pred_common.h"
#include "vp9/common/vp9_entropy.h"
#include "vp9/encoder/vp9_encodemv.h"
#include "vp9/common/vp9_entropymv.h"
#include "vp9/common/vp9_mvref_common.h"
Paul Wilkins's avatar
Paul Wilkins committed
33

John Koleszar's avatar
John Koleszar committed
34 35 36 37 38
#if defined(SECTIONBITS_OUTPUT)
unsigned __int64 Sectionbits[500];
#endif

#ifdef ENTROPY_STATS
39 40 41
int intra_mode_stats[VP9_KF_BINTRAMODES]
                    [VP9_KF_BINTRAMODES]
                    [VP9_KF_BINTRAMODES];
42 43 44 45 46 47 48
vp9_coeff_stats tree_update_hist_4x4[BLOCK_TYPES_4X4];
vp9_coeff_stats hybrid_tree_update_hist_4x4[BLOCK_TYPES_4X4];
vp9_coeff_stats tree_update_hist_8x8[BLOCK_TYPES_8X8];
vp9_coeff_stats hybrid_tree_update_hist_8x8[BLOCK_TYPES_8X8];
vp9_coeff_stats tree_update_hist_16x16[BLOCK_TYPES_16X16];
vp9_coeff_stats hybrid_tree_update_hist_16x16[BLOCK_TYPES_16X16];
vp9_coeff_stats tree_update_hist_32x32[BLOCK_TYPES_32X32];
49

John Koleszar's avatar
John Koleszar committed
50 51 52 53 54 55 56
extern unsigned int active_section;
#endif

#ifdef MODE_STATS
int count_mb_seg[4] = { 0, 0, 0, 0 };
#endif

57 58
#define vp9_cost_upd  ((int)(vp9_cost_one(upd) - vp9_cost_zero(upd)) >> 8)
#define vp9_cost_upd256  ((int)(vp9_cost_one(upd) - vp9_cost_zero(upd)))
59 60 61 62

#define SEARCH_NEWP
static int update_bits[255];

John Koleszar's avatar
John Koleszar committed
63 64 65
static void compute_update_table() {
  int i;
  for (i = 0; i < 255; i++)
66
    update_bits[i] = vp9_count_term_subexp(i, SUBEXP_PARAM, 255);
67 68
}

John Koleszar's avatar
John Koleszar committed
69 70 71 72 73
static int split_index(int i, int n, int modulus) {
  int max1 = (n - 1 - modulus / 2) / modulus + 1;
  if (i % modulus == modulus / 2) i = i / modulus;
  else i = max1 + i - (i + modulus - modulus / 2) / modulus;
  return i;
74 75
}

John Koleszar's avatar
John Koleszar committed
76 77 78 79 80
static int remap_prob(int v, int m) {
  const int n = 256;
  const int modulus = MODULUS_PARAM;
  int i;
  if ((m << 1) <= n)
81
    i = vp9_recenter_nonneg(v, m) - 1;
John Koleszar's avatar
John Koleszar committed
82
  else
83
    i = vp9_recenter_nonneg(n - 1 - v, n - 1 - m) - 1;
John Koleszar's avatar
John Koleszar committed
84 85 86

  i = split_index(i, n - 1, modulus);
  return i;
87
}
88

89 90
static void write_prob_diff_update(vp9_writer *const bc,
                                   vp9_prob newp, vp9_prob oldp) {
John Koleszar's avatar
John Koleszar committed
91
  int delp = remap_prob(newp, oldp);
92
  vp9_encode_term_subexp(bc, delp, SUBEXP_PARAM, 255);
93 94
}

95
static int prob_diff_update_cost(vp9_prob newp, vp9_prob oldp) {
John Koleszar's avatar
John Koleszar committed
96 97
  int delp = remap_prob(newp, oldp);
  return update_bits[delp] * 256;
98
}
99

John Koleszar's avatar
John Koleszar committed
100
static void update_mode(
101
  vp9_writer *const bc,
John Koleszar's avatar
John Koleszar committed
102
  int n,
103 104 105 106
  vp9_token tok               [/* n */],
  vp9_tree tree,
  vp9_prob Pnew               [/* n-1 */],
  vp9_prob Pcur               [/* n-1 */],
John Koleszar's avatar
John Koleszar committed
107 108 109 110 111 112
  unsigned int bct            [/* n-1 */] [2],
  const unsigned int num_events[/* n */]
) {
  unsigned int new_b = 0, old_b = 0;
  int i = 0;

113
  vp9_tree_probs_from_distribution(
John Koleszar's avatar
John Koleszar committed
114 115 116 117 118 119
    n--, tok, tree,
    Pnew, bct, num_events,
    256, 1
  );

  do {
120 121
    new_b += cost_branch(bct[i], Pnew[i]);
    old_b += cost_branch(bct[i], Pcur[i]);
John Koleszar's avatar
John Koleszar committed
122 123 124
  } while (++i < n);

  if (new_b + (n << 8) < old_b) {
John Koleszar's avatar
John Koleszar committed
125 126
    int i = 0;

127
    vp9_write_bit(bc, 1);
John Koleszar's avatar
John Koleszar committed
128

John Koleszar's avatar
John Koleszar committed
129
    do {
130
      const vp9_prob p = Pnew[i];
John Koleszar's avatar
John Koleszar committed
131

132
      vp9_write_literal(bc, Pcur[i] = p ? p : 1, 8);
John Koleszar's avatar
John Koleszar committed
133 134
    } while (++i < n);
  } else
135
    vp9_write_bit(bc, 0);
John Koleszar's avatar
John Koleszar committed
136 137
}

138
static void update_mbintra_mode_probs(VP9_COMP* const cpi,
139
                                      vp9_writer* const bc) {
140
  VP9_COMMON *const cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
141

John Koleszar's avatar
John Koleszar committed
142
  {
143 144
    vp9_prob Pnew   [VP9_YMODES - 1];
    unsigned int bct [VP9_YMODES - 1] [2];
John Koleszar's avatar
John Koleszar committed
145

John Koleszar's avatar
John Koleszar committed
146
    update_mode(
147
      bc, VP9_YMODES, vp9_ymode_encodings, vp9_ymode_tree,
Paul Wilkins's avatar
Paul Wilkins committed
148
      Pnew, cm->fc.ymode_prob, bct, (unsigned int *)cpi->ymode_count
John Koleszar's avatar
John Koleszar committed
149
    );
150 151 152 153 154
#if CONFIG_SUPERBLOCKS
    update_mode(bc, VP9_I32X32_MODES, vp9_sb_ymode_encodings,
                vp9_sb_ymode_tree, Pnew, cm->fc.sb_ymode_prob, bct,
                (unsigned int *)cpi->sb_ymode_count);
#endif
John Koleszar's avatar
John Koleszar committed
155
  }
John Koleszar's avatar
John Koleszar committed
156 157
}

John Koleszar's avatar
John Koleszar committed
158
static int get_prob(int num, int den) {
159 160 161 162
  int p;
  if (den <= 0)
    return 128;
  p = (num * 255 + (den >> 1)) / den;
163
  return clip_prob(p);
164 165
}

John Koleszar's avatar
John Koleszar committed
166 167 168 169
static int get_binary_prob(int n0, int n1) {
  return get_prob(n0, n0 + n1);
}

170 171
void vp9_update_skip_probs(VP9_COMP *cpi) {
  VP9_COMMON *const pc = &cpi->common;
John Koleszar's avatar
John Koleszar committed
172
  int k;
Paul Wilkins's avatar
Paul Wilkins committed
173

John Koleszar's avatar
John Koleszar committed
174
  for (k = 0; k < MBSKIP_CONTEXTS; ++k) {
John Koleszar's avatar
John Koleszar committed
175 176
    pc->mbskip_pred_probs[k] = get_binary_prob(cpi->skip_false_count[k],
                                               cpi->skip_true_count[k]);
John Koleszar's avatar
John Koleszar committed
177
  }
Paul Wilkins's avatar
Paul Wilkins committed
178 179
}

180
static void update_switchable_interp_probs(VP9_COMP *cpi,
181
                                           vp9_writer* const bc) {
182
  VP9_COMMON *const pc = &cpi->common;
183 184
  unsigned int branch_ct[32][2];
  int i, j;
185
  for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
186
    vp9_tree_probs_from_distribution(
187
        VP9_SWITCHABLE_FILTERS,
188
        vp9_switchable_interp_encodings, vp9_switchable_interp_tree,
189 190
        pc->fc.switchable_interp_prob[j], branch_ct,
        cpi->switchable_interp_count[j], 256, 1);
191
    for (i = 0; i < VP9_SWITCHABLE_FILTERS - 1; ++i) {
192 193
      if (pc->fc.switchable_interp_prob[j][i] < 1)
        pc->fc.switchable_interp_prob[j][i] = 1;
194
      vp9_write_literal(bc, pc->fc.switchable_interp_prob[j][i], 8);
195 196 197 198
    }
  }
}

199
// This function updates the reference frame prediction stats
200 201
static void update_refpred_stats(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
John Koleszar's avatar
John Koleszar committed
202
  int i;
203
  vp9_prob new_pred_probs[PREDICTION_PROBS];
John Koleszar's avatar
John Koleszar committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217
  int old_cost, new_cost;

  // Set the prediction probability structures to defaults
  if (cm->frame_type == KEY_FRAME) {
    // Set the prediction probabilities to defaults
    cm->ref_pred_probs[0] = 120;
    cm->ref_pred_probs[1] = 80;
    cm->ref_pred_probs[2] = 40;

    vpx_memset(cpi->ref_pred_probs_update, 0,
               sizeof(cpi->ref_pred_probs_update));
  } else {
    // From the prediction counts set the probabilities for each context
    for (i = 0; i < PREDICTION_PROBS; i++) {
John Koleszar's avatar
John Koleszar committed
218 219
      new_pred_probs[i] = get_binary_prob(cpi->ref_pred_count[i][0],
                                          cpi->ref_pred_count[i][1]);
John Koleszar's avatar
John Koleszar committed
220 221 222 223

      // Decide whether or not to update the reference frame probs.
      // Returned costs are in 1/256 bit units.
      old_cost =
224 225
        (cpi->ref_pred_count[i][0] * vp9_cost_zero(cm->ref_pred_probs[i])) +
        (cpi->ref_pred_count[i][1] * vp9_cost_one(cm->ref_pred_probs[i]));
John Koleszar's avatar
John Koleszar committed
226 227

      new_cost =
228 229
        (cpi->ref_pred_count[i][0] * vp9_cost_zero(new_pred_probs[i])) +
        (cpi->ref_pred_count[i][1] * vp9_cost_one(new_pred_probs[i]));
John Koleszar's avatar
John Koleszar committed
230 231 232 233 234 235 236

      // Cost saving must be >= 8 bits (2048 in these units)
      if ((old_cost - new_cost) >= 2048) {
        cpi->ref_pred_probs_update[i] = 1;
        cm->ref_pred_probs[i] = new_pred_probs[i];
      } else
        cpi->ref_pred_probs_update[i] = 0;
237 238

    }
John Koleszar's avatar
John Koleszar committed
239
  }
240 241
}

242 243 244 245 246 247
// This function is called to update the mode probability context used to encode
// inter modes. It assumes the branch counts table has already been populated
// prior to the actual packing of the bitstream (in rd stage or dummy pack)
//
// The branch counts table is re-populated during the actual pack stage and in
// the decoder to facilitate backwards update of the context.
Jim Bankoski's avatar
Jim Bankoski committed
248 249
static void update_mode_probs(VP9_COMMON *cm,
                              int mode_context[INTER_MODE_CONTEXTS][4]) {
250
  int i, j;
Jim Bankoski's avatar
Jim Bankoski committed
251
  unsigned int (*mv_ref_ct)[4][2];
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

  vpx_memcpy(mode_context, cm->fc.vp9_mode_contexts,
             sizeof(cm->fc.vp9_mode_contexts));

  mv_ref_ct = cm->fc.mv_ref_ct;

  for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
    for (j = 0; j < 4; j++) {
      int new_prob, count, old_cost, new_cost;

      // Work out cost of coding branches with the old and optimal probability
      old_cost = cost_branch256(mv_ref_ct[i][j], mode_context[i][j]);
      count = mv_ref_ct[i][j][0] + mv_ref_ct[i][j][1];
      new_prob = count > 0 ? (255 * mv_ref_ct[i][j][0]) / count : 128;
      new_prob = (new_prob > 0) ? new_prob : 1;
      new_cost = cost_branch256(mv_ref_ct[i][j], new_prob);

      // If cost saving is >= 14 bits then update the mode probability.
      // This is the approximate net cost of updating one probability given
      // that the no update case ismuch more common than the update case.
      if (new_cost <= (old_cost - (14 << 8))) {
        mode_context[i][j] = new_prob;
      }
    }
  }
}
278 279
static void write_ymode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_ymode_tree, p, vp9_ymode_encodings + m);
John Koleszar's avatar
John Koleszar committed
280 281
}

282 283
static void kfwrite_ymode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_kf_ymode_tree, p, vp9_kf_ymode_encodings + m);
John Koleszar's avatar
John Koleszar committed
284 285
}

Ronald S. Bultje's avatar
Ronald S. Bultje committed
286
#if CONFIG_SUPERBLOCKS
287 288 289 290
static void write_sb_ymode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_sb_ymode_tree, p, vp9_sb_ymode_encodings + m);
}

291 292
static void sb_kfwrite_ymode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_uv_mode_tree, p, vp9_sb_kf_ymode_encodings + m);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
293 294 295
}
#endif

296 297
static void write_i8x8_mode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_i8x8_mode_tree, p, vp9_i8x8_mode_encodings + m);
Yaowu Xu's avatar
Yaowu Xu committed
298
}
Yaowu Xu's avatar
Yaowu Xu committed
299

300 301
static void write_uv_mode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_uv_mode_tree, p, vp9_uv_mode_encodings + m);
John Koleszar's avatar
John Koleszar committed
302 303 304
}


305
static void write_bmode(vp9_writer *bc, int m, const vp9_prob *p) {
306 307 308 309
#if CONFIG_NEWBINTRAMODES
  assert(m < B_CONTEXT_PRED - CONTEXT_PRED_REPLACEMENTS || m == B_CONTEXT_PRED);
  if (m == B_CONTEXT_PRED) m -= CONTEXT_PRED_REPLACEMENTS;
#endif
310
  write_token(bc, vp9_bmode_tree, p, vp9_bmode_encodings + m);
John Koleszar's avatar
John Koleszar committed
311 312
}

313 314 315 316
static void write_kf_bmode(vp9_writer *bc, int m, const vp9_prob *p) {
  write_token(bc, vp9_kf_bmode_tree, p, vp9_kf_bmode_encodings + m);
}

317
static void write_split(vp9_writer *bc, int x, const vp9_prob *p) {
318 319
  write_token(
    bc, vp9_mbsplit_tree, p, vp9_mbsplit_encodings + x);
John Koleszar's avatar
John Koleszar committed
320 321
}

322
static int prob_update_savings(const unsigned int *ct,
323 324 325 326 327
                               const vp9_prob oldp, const vp9_prob newp,
                               const vp9_prob upd) {
  const int old_b = cost_branch256(ct, oldp);
  const int new_b = cost_branch256(ct, newp);
  const int update_b = 2048 + vp9_cost_upd256;
John Koleszar's avatar
John Koleszar committed
328
  return (old_b - new_b - update_b);
329 330
}

331
static int prob_diff_update_savings(const unsigned int *ct,
332 333 334 335
                                    const vp9_prob oldp, const vp9_prob newp,
                                    const vp9_prob upd) {
  const int old_b = cost_branch256(ct, oldp);
  const int new_b = cost_branch256(ct, newp);
John Koleszar's avatar
John Koleszar committed
336
  const int update_b = (newp == oldp ? 0 :
337
                        prob_diff_update_cost(newp, oldp) + vp9_cost_upd256);
John Koleszar's avatar
John Koleszar committed
338
  return (old_b - new_b - update_b);
339 340 341
}

static int prob_diff_update_savings_search(const unsigned int *ct,
342 343 344
                                           const vp9_prob oldp, vp9_prob *bestp,
                                           const vp9_prob upd) {
  const int old_b = cost_branch256(ct, oldp);
John Koleszar's avatar
John Koleszar committed
345
  int new_b, update_b, savings, bestsavings, step;
346
  vp9_prob newp, bestnewp;
John Koleszar's avatar
John Koleszar committed
347 348 349 350 351 352

  bestsavings = 0;
  bestnewp = oldp;

  step = (*bestp > oldp ? -1 : 1);
  for (newp = *bestp; newp != oldp; newp += step) {
353 354
    new_b = cost_branch256(ct, newp);
    update_b = prob_diff_update_cost(newp, oldp) + vp9_cost_upd256;
John Koleszar's avatar
John Koleszar committed
355 356 357 358
    savings = old_b - new_b - update_b;
    if (savings > bestsavings) {
      bestsavings = savings;
      bestnewp = newp;
359
    }
John Koleszar's avatar
John Koleszar committed
360 361 362
  }
  *bestp = bestnewp;
  return bestsavings;
363 364
}

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
static void vp9_cond_prob_update(vp9_writer *bc, vp9_prob *oldp, vp9_prob upd,
                                 unsigned int *ct) {
  vp9_prob newp;
  int savings;
  newp = get_binary_prob(ct[0], ct[1]);
  savings = prob_update_savings(ct, *oldp, newp, upd);
  if (savings > 0) {
    vp9_write(bc, 1, upd);
    vp9_write_literal(bc, newp, 8);
    *oldp = newp;
  } else {
    vp9_write(bc, 0, upd);
  }
}

380
static void pack_mb_tokens(vp9_writer* const bc,
381 382
                           TOKENEXTRA **tp,
                           const TOKENEXTRA *const stop) {
John Koleszar's avatar
John Koleszar committed
383 384
  unsigned int split;
  unsigned int shift;
John Koleszar's avatar
John Koleszar committed
385 386 387
  int count = bc->count;
  unsigned int range = bc->range;
  unsigned int lowvalue = bc->lowvalue;
388
  TOKENEXTRA *p = *tp;
John Koleszar's avatar
John Koleszar committed
389

John Koleszar's avatar
John Koleszar committed
390 391
  while (p < stop) {
    const int t = p->Token;
392 393
    vp9_token *const a = vp9_coef_encodings + t;
    const vp9_extra_bit_struct *const b = vp9_extra_bits + t;
John Koleszar's avatar
John Koleszar committed
394 395 396 397 398
    int i = 0;
    const unsigned char *pp = p->context_tree;
    int v = a->value;
    int n = a->Len;

399 400 401 402 403 404
    if (t == EOSB_TOKEN)
    {
      ++p;
      break;
    }

John Koleszar's avatar
John Koleszar committed
405 406 407 408 409
    /* skip one or two nodes */
    if (p->skip_eob_node) {
      n -= p->skip_eob_node;
      i = 2 * p->skip_eob_node;
    }
John Koleszar's avatar
John Koleszar committed
410

John Koleszar's avatar
John Koleszar committed
411 412 413
    do {
      const int bb = (v >> --n) & 1;
      split = 1 + (((range - 1) * pp[i >> 1]) >> 8);
414
      i = vp9_coef_tree[i + bb];
John Koleszar's avatar
John Koleszar committed
415

John Koleszar's avatar
John Koleszar committed
416 417 418 419 420 421
      if (bb) {
        lowvalue += split;
        range = range - split;
      } else {
        range = split;
      }
John Koleszar's avatar
John Koleszar committed
422

423
      shift = vp9_norm[range];
John Koleszar's avatar
John Koleszar committed
424 425
      range <<= shift;
      count += shift;
John Koleszar's avatar
John Koleszar committed
426

John Koleszar's avatar
John Koleszar committed
427 428
      if (count >= 0) {
        int offset = shift - count;
John Koleszar's avatar
John Koleszar committed
429

John Koleszar's avatar
John Koleszar committed
430
        if ((lowvalue << (offset - 1)) & 0x80000000) {
John Koleszar's avatar
John Koleszar committed
431
          int x = bc->pos - 1;
John Koleszar's avatar
John Koleszar committed
432

John Koleszar's avatar
John Koleszar committed
433 434
          while (x >= 0 && bc->buffer[x] == 0xff) {
            bc->buffer[x] = (unsigned char)0;
John Koleszar's avatar
John Koleszar committed
435 436
            x--;
          }
John Koleszar's avatar
John Koleszar committed
437

John Koleszar's avatar
John Koleszar committed
438
          bc->buffer[x] += 1;
John Koleszar's avatar
John Koleszar committed
439
        }
John Koleszar's avatar
John Koleszar committed
440

John Koleszar's avatar
John Koleszar committed
441
        bc->buffer[bc->pos++] = (lowvalue >> (24 - offset));
John Koleszar's avatar
John Koleszar committed
442 443 444 445 446
        lowvalue <<= offset;
        shift = count;
        lowvalue &= 0xffffff;
        count -= 8;
      }
John Koleszar's avatar
John Koleszar committed
447

John Koleszar's avatar
John Koleszar committed
448 449
      lowvalue <<= shift;
    } while (n);
John Koleszar's avatar
John Koleszar committed
450 451


John Koleszar's avatar
John Koleszar committed
452 453
    if (b->base_val) {
      const int e = p->Extra, L = b->Len;
John Koleszar's avatar
John Koleszar committed
454

John Koleszar's avatar
John Koleszar committed
455 456 457 458 459
      if (L) {
        const unsigned char *pp = b->prob;
        int v = e >> 1;
        int n = L;              /* number of bits in v, assumed nonzero */
        int i = 0;
John Koleszar's avatar
John Koleszar committed
460

John Koleszar's avatar
John Koleszar committed
461 462 463 464
        do {
          const int bb = (v >> --n) & 1;
          split = 1 + (((range - 1) * pp[i >> 1]) >> 8);
          i = b->tree[i + bb];
John Koleszar's avatar
John Koleszar committed
465

John Koleszar's avatar
John Koleszar committed
466 467 468 469 470 471
          if (bb) {
            lowvalue += split;
            range = range - split;
          } else {
            range = split;
          }
John Koleszar's avatar
John Koleszar committed
472

473
          shift = vp9_norm[range];
John Koleszar's avatar
John Koleszar committed
474 475
          range <<= shift;
          count += shift;
John Koleszar's avatar
John Koleszar committed
476

John Koleszar's avatar
John Koleszar committed
477 478
          if (count >= 0) {
            int offset = shift - count;
John Koleszar's avatar
John Koleszar committed
479

John Koleszar's avatar
John Koleszar committed
480
            if ((lowvalue << (offset - 1)) & 0x80000000) {
John Koleszar's avatar
John Koleszar committed
481
              int x = bc->pos - 1;
John Koleszar's avatar
John Koleszar committed
482

John Koleszar's avatar
John Koleszar committed
483 484
              while (x >= 0 && bc->buffer[x] == 0xff) {
                bc->buffer[x] = (unsigned char)0;
John Koleszar's avatar
John Koleszar committed
485 486 487
                x--;
              }

John Koleszar's avatar
John Koleszar committed
488
              bc->buffer[x] += 1;
John Koleszar's avatar
John Koleszar committed
489 490
            }

John Koleszar's avatar
John Koleszar committed
491
            bc->buffer[bc->pos++] = (lowvalue >> (24 - offset));
John Koleszar's avatar
John Koleszar committed
492 493 494 495 496
            lowvalue <<= offset;
            shift = count;
            lowvalue &= 0xffffff;
            count -= 8;
          }
John Koleszar's avatar
John Koleszar committed
497

John Koleszar's avatar
John Koleszar committed
498 499 500
          lowvalue <<= shift;
        } while (n);
      }
John Koleszar's avatar
John Koleszar committed
501 502


John Koleszar's avatar
John Koleszar committed
503
      {
John Koleszar's avatar
John Koleszar committed
504

John Koleszar's avatar
John Koleszar committed
505
        split = (range + 1) >> 1;
John Koleszar's avatar
John Koleszar committed
506

John Koleszar's avatar
John Koleszar committed
507 508 509 510 511 512
        if (e & 1) {
          lowvalue += split;
          range = range - split;
        } else {
          range = split;
        }
John Koleszar's avatar
John Koleszar committed
513

John Koleszar's avatar
John Koleszar committed
514
        range <<= 1;
John Koleszar's avatar
John Koleszar committed
515

John Koleszar's avatar
John Koleszar committed
516
        if ((lowvalue & 0x80000000)) {
John Koleszar's avatar
John Koleszar committed
517
          int x = bc->pos - 1;
John Koleszar's avatar
John Koleszar committed
518

John Koleszar's avatar
John Koleszar committed
519 520
          while (x >= 0 && bc->buffer[x] == 0xff) {
            bc->buffer[x] = (unsigned char)0;
John Koleszar's avatar
John Koleszar committed
521 522
            x--;
          }
John Koleszar's avatar
John Koleszar committed
523

John Koleszar's avatar
John Koleszar committed
524
          bc->buffer[x] += 1;
John Koleszar's avatar
John Koleszar committed
525

John Koleszar's avatar
John Koleszar committed
526
        }
John Koleszar's avatar
John Koleszar committed
527

John Koleszar's avatar
John Koleszar committed
528 529 530 531
        lowvalue  <<= 1;

        if (!++count) {
          count = -8;
John Koleszar's avatar
John Koleszar committed
532
          bc->buffer[bc->pos++] = (lowvalue >> 24);
John Koleszar's avatar
John Koleszar committed
533
          lowvalue &= 0xffffff;
John Koleszar's avatar
John Koleszar committed
534
        }
John Koleszar's avatar
John Koleszar committed
535
      }
John Koleszar's avatar
John Koleszar committed
536 537

    }
John Koleszar's avatar
John Koleszar committed
538 539 540
    ++p;
  }

John Koleszar's avatar
John Koleszar committed
541 542 543
  bc->count = count;
  bc->lowvalue = lowvalue;
  bc->range = range;
544
  *tp = p;
John Koleszar's avatar
John Koleszar committed
545 546
}

John Koleszar's avatar
John Koleszar committed
547 548
static void write_partition_size(unsigned char *cx_data, int size) {
  signed char csize;
John Koleszar's avatar
John Koleszar committed
549

John Koleszar's avatar
John Koleszar committed
550 551 552 553 554 555
  csize = size & 0xff;
  *cx_data = csize;
  csize = (size >> 8) & 0xff;
  *(cx_data + 1) = csize;
  csize = (size >> 16) & 0xff;
  *(cx_data + 2) = csize;
John Koleszar's avatar
John Koleszar committed
556 557 558 559 560

}

static void write_mv_ref
(
561
  vp9_writer *bc, MB_PREDICTION_MODE m, const vp9_prob *p
John Koleszar's avatar
John Koleszar committed
562
) {
563
#if CONFIG_DEBUG
John Koleszar's avatar
John Koleszar committed
564
  assert(NEARESTMV <= m  &&  m <= SPLITMV);
565
#endif
566 567
  write_token(bc, vp9_mv_ref_tree, p,
              vp9_mv_ref_encoding_array - NEARESTMV + m);
John Koleszar's avatar
John Koleszar committed
568 569
}

Ronald S. Bultje's avatar
Ronald S. Bultje committed
570
#if CONFIG_SUPERBLOCKS
571 572
static void write_sb_mv_ref(vp9_writer *bc, MB_PREDICTION_MODE m,
                            const vp9_prob *p) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
573 574 575
#if CONFIG_DEBUG
  assert(NEARESTMV <= m  &&  m < SPLITMV);
#endif
576 577
  write_token(bc, vp9_sb_mv_ref_tree, p,
              vp9_sb_mv_ref_encoding_array - NEARESTMV + m);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
578 579 580
}
#endif

John Koleszar's avatar
John Koleszar committed
581 582
static void write_sub_mv_ref
(
583
  vp9_writer *bc, B_PREDICTION_MODE m, const vp9_prob *p
John Koleszar's avatar
John Koleszar committed
584
) {
585
#if CONFIG_DEBUG
John Koleszar's avatar
John Koleszar committed
586
  assert(LEFT4X4 <= m  &&  m <= NEW4X4);
587
#endif
588 589
  write_token(bc, vp9_sub_mv_ref_tree, p,
              vp9_sub_mv_ref_encoding_array - LEFT4X4 + m);
John Koleszar's avatar
John Koleszar committed
590 591
}

592
static void write_nmv(vp9_writer *bc, const MV *mv, const int_mv *ref,
John Koleszar's avatar
John Koleszar committed
593
                      const nmv_context *nmvc, int usehp) {
594 595 596 597
  MV e;
  e.row = mv->row - ref->as_mv.row;
  e.col = mv->col - ref->as_mv.col;

598 599
  vp9_encode_nmv(bc, &e, &ref->as_mv, nmvc);
  vp9_encode_nmv_fp(bc, &e, &ref->as_mv, nmvc, usehp);
600 601
}

602
#if CONFIG_NEW_MVREF
603 604
static void vp9_write_mv_ref_id(vp9_writer *w,
                                vp9_prob * ref_id_probs,
605 606 607 608
                                int mv_ref_id) {
  // Encode the index for the MV reference.
  switch (mv_ref_id) {
    case 0:
609
      vp9_write(w, 0, ref_id_probs[0]);
610 611
      break;
    case 1:
612 613
      vp9_write(w, 1, ref_id_probs[0]);
      vp9_write(w, 0, ref_id_probs[1]);
614 615
      break;
    case 2:
616 617 618
      vp9_write(w, 1, ref_id_probs[0]);
      vp9_write(w, 1, ref_id_probs[1]);
      vp9_write(w, 0, ref_id_probs[2]);
619 620
      break;
    case 3:
621 622 623
      vp9_write(w, 1, ref_id_probs[0]);
      vp9_write(w, 1, ref_id_probs[1]);
      vp9_write(w, 1, ref_id_probs[2]);
624 625 626 627 628 629 630 631 632 633
      break;

      // TRAP.. This should not happen
    default:
      assert(0);
      break;
  }
}
#endif

Paul Wilkins's avatar
Paul Wilkins committed
634 635
// This function writes the current macro block's segnment id to the bitstream
// It should only be called if a segment map update is indicated.
636
static void write_mb_segid(vp9_writer *bc,
Paul Wilkins's avatar
Paul Wilkins committed
637
                           const MB_MODE_INFO *mi, const MACROBLOCKD *xd) {
John Koleszar's avatar
John Koleszar committed
638
  // Encode the MB segment id.
Ronald S. Bultje's avatar
Ronald S. Bultje committed
639 640 641
  int seg_id = mi->segment_id;
#if CONFIG_SUPERBLOCKS
  if (mi->encoded_as_sb) {
642
    if (xd->mb_to_right_edge >= 0)
Ronald S. Bultje's avatar
Ronald S. Bultje committed
643
      seg_id = seg_id && xd->mode_info_context[1].mbmi.segment_id;
644
    if (xd->mb_to_bottom_edge >= 0) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
645 646
      seg_id = seg_id &&
               xd->mode_info_context[xd->mode_info_stride].mbmi.segment_id;
647
      if (xd->mb_to_right_edge >= 0)
Ronald S. Bultje's avatar
Ronald S. Bultje committed
648 649 650 651 652
        seg_id = seg_id &&
                xd->mode_info_context[xd->mode_info_stride + 1].mbmi.segment_id;
    }
  }
#endif
Paul Wilkins's avatar
Paul Wilkins committed
653
  if (xd->segmentation_enabled && xd->update_mb_segmentation_map) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
654
    switch (seg_id) {
John Koleszar's avatar
John Koleszar committed
655
      case 0:
656 657
        vp9_write(bc, 0, xd->mb_segment_tree_probs[0]);
        vp9_write(bc, 0, xd->mb_segment_tree_probs[1]);
John Koleszar's avatar
John Koleszar committed
658 659
        break;
      case 1:
660 661
        vp9_write(bc, 0, xd->mb_segment_tree_probs[0]);
        vp9_write(bc, 1, xd->mb_segment_tree_probs[1]);
John Koleszar's avatar
John Koleszar committed
662 663
        break;
      case 2:
664 665
        vp9_write(bc, 1, xd->mb_segment_tree_probs[0]);
        vp9_write(bc, 0, xd->mb_segment_tree_probs[2]);
John Koleszar's avatar
John Koleszar committed
666 667
        break;
      case 3:
668 669
        vp9_write(bc, 1, xd->mb_segment_tree_probs[0]);
        vp9_write(bc, 1, xd->mb_segment_tree_probs[2]);
John Koleszar's avatar
John Koleszar committed
670 671 672 673
        break;

        // TRAP.. This should not happen
      default:
674 675
        vp9_write(bc, 0, xd->mb_segment_tree_probs[0]);
        vp9_write(bc, 0, xd->mb_segment_tree_probs[1]);
John Koleszar's avatar
John Koleszar committed
676
        break;
John Koleszar's avatar
John Koleszar committed
677
    }
John Koleszar's avatar
John Koleszar committed
678
  }
John Koleszar's avatar
John Koleszar committed
679 680
}

Paul Wilkins's avatar
Paul Wilkins committed
681
// This function encodes the reference frame
682
static void encode_ref_frame(vp9_writer *const bc,
683
                             VP9_COMMON *const cm,
John Koleszar's avatar
John Koleszar committed
684 685 686 687 688
                             MACROBLOCKD *xd,
                             int segment_id,
                             MV_REFERENCE_FRAME rf) {
  int seg_ref_active;
  int seg_ref_count = 0;
689 690 691
  seg_ref_active = vp9_segfeature_active(xd,
                                         segment_id,
                                         SEG_LVL_REF_FRAME);
John Koleszar's avatar
John Koleszar committed
692 693

  if (seg_ref_active) {
694 695 696 697
    seg_ref_count = vp9_check_segref(xd, segment_id, INTRA_FRAME) +
                    vp9_check_segref(xd, segment_id, LAST_FRAME) +
                    vp9_check_segref(xd, segment_id, GOLDEN_FRAME) +
                    vp9_check_segref(xd, segment_id, ALTREF_FRAME);
John Koleszar's avatar
John Koleszar committed
698 699 700 701 702 703 704
  }

  // If segment level coding of this signal is disabled...
  // or the segment allows multiple reference frame options
  if (!seg_ref_active || (seg_ref_count > 1)) {
    // Values used in prediction model coding
    unsigned char prediction_flag;
705
    vp9_prob pred_prob;
John Koleszar's avatar
John Koleszar committed
706 707 708
    MV_REFERENCE_FRAME pred_rf;

    // Get the context probability the prediction flag
Paul Wilkins's avatar
Paul Wilkins committed
709
    pred_prob = vp9_get_pred_prob(cm, xd, PRED_REF);
John Koleszar's avatar
John Koleszar committed
710 711

    // Get the predicted value.
Paul Wilkins's avatar
Paul Wilkins committed
712
    pred_rf = vp9_get_pred_ref(cm, xd);
John Koleszar's avatar
John Koleszar committed
713 714 715 716 717

    // Did the chosen reference frame match its predicted value.
    prediction_flag =
      (xd->mode_info_context->mbmi.ref_frame == pred_rf);

Paul Wilkins's avatar
Paul Wilkins committed
718
    vp9_set_pred_flag(xd, PRED_REF, prediction_flag);
719
    vp9_write(bc, prediction_flag, pred_prob);
John Koleszar's avatar
John Koleszar committed
720 721 722

    // If not predicted correctly then code value explicitly
    if (!prediction_flag) {
723
      vp9_prob mod_refprobs[PREDICTION_PROBS];
John Koleszar's avatar
John Koleszar committed
724 725 726 727 728 729 730 731

      vpx_memcpy(mod_refprobs,
                 cm->mod_refprobs[pred_rf], sizeof(mod_refprobs));

      // If segment coding enabled blank out options that cant occur by
      // setting the branch probability to 0.
      if (seg_ref_active) {
        mod_refprobs[INTRA_FRAME] *=
732
          vp9_check_segref(xd, segment_id, INTRA_FRAME);
John Koleszar's avatar
John Koleszar committed
733
        mod_refprobs[LAST_FRAME] *=
734
          vp9_check_segref(xd, segment_id, LAST_FRAME);
John Koleszar's avatar
John Koleszar committed
735
        mod_refprobs[GOLDEN_FRAME] *=
736 737
          (vp9_check_segref(xd, segment_id, GOLDEN_FRAME) *
           vp9_check_segref(xd, segment_id, ALTREF_FRAME));
John Koleszar's avatar
John Koleszar committed
738 739 740
      }

      if (mod_refprobs[0]) {
741
        vp9_write(bc, (rf != INTRA_FRAME), mod_refprobs[0]);
John Koleszar's avatar
John Koleszar committed
742 743 744 745 746
      }

      // Inter coded
      if (rf != INTRA_FRAME) {
        if (mod_refprobs[1]) {
747
          vp9_write(bc, (rf != LAST_FRAME), mod_refprobs[1]);
John Koleszar's avatar
John Koleszar committed
748
        }
749

John Koleszar's avatar
John Koleszar committed
750 751
        if (rf != LAST_FRAME) {
          if (mod_refprobs[2]) {
752
            vp9_write(bc, (rf != GOLDEN_FRAME), mod_refprobs[2]);
John Koleszar's avatar
John Koleszar committed
753
          }
754
        }
John Koleszar's avatar
John Koleszar committed
755
      }
Paul Wilkins's avatar
Paul Wilkins committed
756
    }
John Koleszar's avatar
John Koleszar committed
757
  }
Paul Wilkins's avatar
Paul Wilkins committed
758

John Koleszar's avatar
John Koleszar committed
759 760
  // 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
761
}
John Koleszar's avatar
John Koleszar committed
762

763
// Update the probabilities used to encode reference frame data
764 765
static void update_ref_probs(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
766

John Koleszar's avatar
John Koleszar committed
767 768 769 770
  const int *const rfct = cpi->count_mb_ref_frame_usage;
  const int rf_intra = rfct[INTRA_FRAME];
  const int rf_inter = rfct[LAST_FRAME] +
                       rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
771

John Koleszar's avatar
John Koleszar committed
772 773 774
  cm->prob_intra_coded = get_binary_prob(rf_intra, rf_inter);
  cm->prob_last_coded = get_prob(rfct[LAST_FRAME], rf_inter);
  cm->prob_gf_coded = get_binary_prob(rfct[GOLDEN_FRAME], rfct[ALTREF_FRAME]);
775

John Koleszar's avatar
John Koleszar committed
776 777
  // Compute a modified set of probabilities to use when prediction of the
  // reference frame fails
Paul Wilkins's avatar
Paul Wilkins committed
778
  vp9_compute_mod_refprobs(cm);
779 780
}

781
static void pack_inter_mode_mvs(VP9_COMP *const cpi, vp9_writer *const bc) {
782
  VP9_COMMON *const pc = &cpi->common;
783
  const nmv_context *nmvc = &pc->fc.nmvc;
John Koleszar's avatar
John Koleszar committed
784 785 786
  MACROBLOCKD *xd = &cpi->mb.e_mbd;
  MODE_INFO *m;
  MODE_INFO *prev_m;
787 788
  TOKENEXTRA *tok = cpi->tok;
  TOKENEXTRA *tok_end = tok + cpi->tok_count;
789

John Koleszar's avatar
John Koleszar committed
790 791 792
  const int mis = pc->mode_info_stride;
  int mb_row, mb_col;
  int row, col;
John Koleszar's avatar
John Koleszar committed
793

John Koleszar's avatar
John Koleszar committed
794
  // Values used in prediction model coding
795
  vp9_prob pred_prob;
John Koleszar's avatar
John Koleszar committed
796
  unsigned char prediction_flag;
797

John Koleszar's avatar
John Koleszar committed
798 799
  int row_delta[4] = { 0, +1,  0, -1};
  int col_delta[4] = { +1, -1, +1, +1};
Adrian Grange's avatar
Adrian Grange committed
800

John Koleszar's avatar
John Koleszar committed
801
  cpi->mb.partition_info = cpi->mb.pi;
802

John Koleszar's avatar
John Koleszar committed
803 804 805 806 807 808 809 810 811 812 813
  mb_row = 0;
  for (row = 0; row < pc->mb_rows; row += 2) {
    m = pc->mi + row * mis;
    prev_m = pc->prev_mi + row * mis;

    mb_col = 0;
    for (col = 0; col < pc->mb_cols; col += 2) {
      int i;

      // Process the 4 MBs in the order:
      // top-left, top-right, bottom-left, bottom-right
Ronald S. Bultje's avatar
Ronald S. Bultje committed
814
#if CONFIG_SUPERBLOCKS
815
      vp9_write(bc, m->mbmi.encoded_as_sb, pc->sb_coded);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
816
#endif
John Koleszar's avatar
John Koleszar committed
817 818 819
      for (i = 0; i < 4; i++) {
        MB_MODE_INFO *mi;
        MV_REFERENCE_FRAME rf;
Deb Mukherjee's avatar
Deb Mukherjee committed
820
        MV_REFERENCE_FRAME sec_ref_frame;
John Koleszar's avatar
John Koleszar committed
821
        MB_PREDICTION_MODE mode;
822
        int segment_id, skip_coeff;
John Koleszar's avatar
John Koleszar committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836

        int dy = row_delta[i];
        int dx = col_delta[i];
        int offset_extended = dy * mis + dx;

        if ((mb_row >= pc->mb_rows) || (mb_col >= pc->mb_cols)) {
          // MB lies outside frame, move on
          mb_row += dy;
          mb_col += dx;
          m += offset_extended;
          prev_m += offset_extended;
          cpi->mb.partition_info += offset_extended;
          continue;
        }
Adrian Grange's avatar
Adrian Grange committed
837

John Koleszar's avatar
John Koleszar committed
838
        mi = &m->mbmi;
John Koleszar's avatar
John Koleszar committed
839
        rf = mi->ref_frame;
Deb Mukherjee's avatar
Deb Mukherjee committed
840
        sec_ref_frame = mi->second_ref_frame;
John Koleszar's avatar
John Koleszar committed
841 842
        mode = mi->mode;
        segment_id = mi->segment_id;
843

John Koleszar's avatar
John Koleszar committed
844 845 846 847 848
        // Distance of Mb to the various image edges.
        // These specified to 8th pel as they are always compared to MV
        // values that are in 1/8th pel units
        xd->mb_to_left_edge = -((mb_col * 16) << 3);
        xd->mb_to_top_edge = -((mb_row * 16)) << 3;
849 850 851 852 853 854 855