2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * 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.
15 #include "vpx/vpx_encoder.h"
16 #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 #include "vp9/common/vp9_seg_common.h"
23 #include "vp9/common/vp9_pred_common.h"
24 #include "vp9/common/vp9_entropy.h"
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_mvref_common.h"
27 #include "vp9/common/vp9_treecoder.h"
28 #include "vp9/common/vp9_systemdependent.h"
29 #include "vp9/common/vp9_pragmas.h"
31 #include "vp9/encoder/vp9_mcomp.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_bitstream.h"
34 #include "vp9/encoder/vp9_segmentation.h"
35 #include "vp9/encoder/vp9_write_bit_buffer.h"
38 #if defined(SECTIONBITS_OUTPUT)
39 unsigned __int64 Sectionbits[500];
43 int intra_mode_stats[VP9_INTRA_MODES]
46 vp9_coeff_stats tree_update_hist_4x4[BLOCK_TYPES];
47 vp9_coeff_stats tree_update_hist_8x8[BLOCK_TYPES];
48 vp9_coeff_stats tree_update_hist_16x16[BLOCK_TYPES];
49 vp9_coeff_stats tree_update_hist_32x32[BLOCK_TYPES];
51 extern unsigned int active_section;
54 #define vp9_cost_upd ((int)(vp9_cost_one(upd) - vp9_cost_zero(upd)) >> 8)
55 #define vp9_cost_upd256 ((int)(vp9_cost_one(upd) - vp9_cost_zero(upd)))
57 static int update_bits[255];
59 static INLINE void write_le16(uint8_t *p, int value) {
64 static INLINE void write_le32(uint8_t *p, int value) {
71 void vp9_encode_unsigned_max(vp9_writer *br, int data, int max) {
74 vp9_write_bit(br, data & 1);
80 int recenter_nonneg(int v, int m) {
84 return ((v - m) << 1);
86 return ((m - v) << 1) - 1;
89 static int get_unsigned_bits(unsigned num_values) {
91 if ((num_values--) <= 1) return 0;
92 while (num_values > 0) {
99 void encode_uniform(vp9_writer *w, int v, int n) {
100 int l = get_unsigned_bits(n);
106 vp9_write_literal(w, v, l - 1);
108 vp9_write_literal(w, m + ((v - m) >> 1), l - 1);
109 vp9_write_literal(w, (v - m) & 1, 1);
113 int count_uniform(int v, int n) {
114 int l = get_unsigned_bits(n);
116 if (l == 0) return 0;
124 void encode_term_subexp(vp9_writer *w, int word, int k, int num_syms) {
128 int b = (i ? k + i - 1 : k);
130 if (num_syms <= mk + 3 * a) {
131 encode_uniform(w, word - mk, num_syms - mk);
134 int t = (word >= mk + a);
135 vp9_write_literal(w, t, 1);
140 vp9_write_literal(w, word - mk, b);
147 int count_term_subexp(int word, int k, int num_syms) {
152 int b = (i ? k + i - 1 : k);
154 if (num_syms <= mk + 3 * a) {
155 count += count_uniform(word - mk, num_syms - mk);
158 int t = (word >= mk + a);
172 static void compute_update_table() {
174 for (i = 0; i < 255; i++)
175 update_bits[i] = count_term_subexp(i, SUBEXP_PARAM, 255);
178 static int split_index(int i, int n, int modulus) {
179 int max1 = (n - 1 - modulus / 2) / modulus + 1;
180 if (i % modulus == modulus / 2) i = i / modulus;
181 else i = max1 + i - (i + modulus - modulus / 2) / modulus;
185 static int remap_prob(int v, int m) {
187 const int modulus = MODULUS_PARAM;
190 i = recenter_nonneg(v, m) - 1;
192 i = recenter_nonneg(n - 1 - v, n - 1 - m) - 1;
194 i = split_index(i, n - 1, modulus);
198 static void write_prob_diff_update(vp9_writer *w,
199 vp9_prob newp, vp9_prob oldp) {
200 int delp = remap_prob(newp, oldp);
201 encode_term_subexp(w, delp, SUBEXP_PARAM, 255);
204 static int prob_diff_update_cost(vp9_prob newp, vp9_prob oldp) {
205 int delp = remap_prob(newp, oldp);
206 return update_bits[delp] * 256;
209 static void update_mode(
212 const struct vp9_token tok[/* n */],
214 vp9_prob Pnew [/* n-1 */],
215 vp9_prob Pcur [/* n-1 */],
216 unsigned int bct [/* n-1 */] [2],
217 const unsigned int num_events[/* n */]
219 unsigned int new_b = 0, old_b = 0;
222 vp9_tree_probs_from_distribution(tree, Pnew, bct, num_events, 0);
226 new_b += cost_branch(bct[i], Pnew[i]);
227 old_b += cost_branch(bct[i], Pcur[i]);
230 if (new_b + (n << 8) < old_b) {
236 const vp9_prob p = Pnew[i];
238 vp9_write_literal(w, Pcur[i] = p ? p : 1, 8);
244 static void update_mbintra_mode_probs(VP9_COMP* const cpi,
245 vp9_writer* const bc) {
246 VP9_COMMON *const cm = &cpi->common;
248 vp9_prob pnew[VP9_INTRA_MODES - 1];
249 unsigned int bct[VP9_INTRA_MODES - 1][2];
251 update_mode(bc, VP9_INTRA_MODES, vp9_intra_mode_encodings,
252 vp9_intra_mode_tree, pnew,
253 cm->fc.y_mode_prob, bct, (unsigned int *)cpi->y_mode_count);
256 void vp9_update_skip_probs(VP9_COMP *cpi) {
257 VP9_COMMON *const pc = &cpi->common;
260 for (k = 0; k < MBSKIP_CONTEXTS; ++k)
261 pc->mbskip_pred_probs[k] = get_binary_prob(cpi->skip_false_count[k],
262 cpi->skip_true_count[k]);
265 static void update_switchable_interp_probs(VP9_COMP *cpi,
266 vp9_writer* const bc) {
267 VP9_COMMON *const pc = &cpi->common;
268 unsigned int branch_ct[32][2];
270 for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
271 vp9_tree_probs_from_distribution(
272 vp9_switchable_interp_tree,
273 pc->fc.switchable_interp_prob[j], branch_ct,
274 cpi->switchable_interp_count[j], 0);
275 for (i = 0; i < VP9_SWITCHABLE_FILTERS - 1; ++i) {
276 if (pc->fc.switchable_interp_prob[j][i] < 1)
277 pc->fc.switchable_interp_prob[j][i] = 1;
278 vp9_write_prob(bc, pc->fc.switchable_interp_prob[j][i]);
283 // This function updates the reference frame prediction stats
284 static void update_refpred_stats(VP9_COMP *cpi) {
285 VP9_COMMON *const cm = &cpi->common;
287 vp9_prob new_pred_probs[PREDICTION_PROBS];
288 int old_cost, new_cost;
290 // Set the prediction probability structures to defaults
291 if (cm->frame_type != KEY_FRAME) {
292 // From the prediction counts set the probabilities for each context
293 for (i = 0; i < PREDICTION_PROBS; i++) {
294 const int c0 = cpi->ref_pred_count[i][0];
295 const int c1 = cpi->ref_pred_count[i][1];
297 new_pred_probs[i] = get_binary_prob(c0, c1);
299 // Decide whether or not to update the reference frame probs.
300 // Returned costs are in 1/256 bit units.
301 old_cost = c0 * vp9_cost_zero(cm->ref_pred_probs[i]) +
302 c1 * vp9_cost_one(cm->ref_pred_probs[i]);
304 new_cost = c0 * vp9_cost_zero(new_pred_probs[i]) +
305 c1 * vp9_cost_one(new_pred_probs[i]);
307 // Cost saving must be >= 8 bits (2048 in these units)
308 if ((old_cost - new_cost) >= 2048) {
309 cpi->ref_pred_probs_update[i] = 1;
310 cm->ref_pred_probs[i] = new_pred_probs[i];
312 cpi->ref_pred_probs_update[i] = 0;
317 // This function is called to update the mode probability context used to encode
318 // inter modes. It assumes the branch counts table has already been populated
319 // prior to the actual packing of the bitstream (in rd stage or dummy pack)
321 // The branch counts table is re-populated during the actual pack stage and in
322 // the decoder to facilitate backwards update of the context.
323 static void update_inter_mode_probs(VP9_COMMON *cm,
324 int mode_context[INTER_MODE_CONTEXTS][VP9_MVREFS - 1]) {
326 unsigned int (*mv_ref_ct)[VP9_MVREFS - 1][2] = cm->fc.mv_ref_ct;
328 vpx_memcpy(mode_context, cm->fc.vp9_mode_contexts,
329 sizeof(cm->fc.vp9_mode_contexts));
331 for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
332 for (j = 0; j < VP9_MVREFS - 1; j++) {
333 int new_prob, old_cost, new_cost;
335 // Work out cost of coding branches with the old and optimal probability
336 old_cost = cost_branch256(mv_ref_ct[i][j], mode_context[i][j]);
337 new_prob = get_binary_prob(mv_ref_ct[i][j][0], mv_ref_ct[i][j][1]);
338 new_cost = cost_branch256(mv_ref_ct[i][j], new_prob);
340 // If cost saving is >= 14 bits then update the mode probability.
341 // This is the approximate net cost of updating one probability given
342 // that the no update case ismuch more common than the update case.
343 if (new_cost <= (old_cost - (14 << 8))) {
344 mode_context[i][j] = new_prob;
350 static void write_intra_mode(vp9_writer *bc, int m, const vp9_prob *p) {
351 write_token(bc, vp9_intra_mode_tree, p, vp9_intra_mode_encodings + m);
354 static int prob_update_savings(const unsigned int *ct,
355 const vp9_prob oldp, const vp9_prob newp,
356 const vp9_prob upd) {
357 const int old_b = cost_branch256(ct, oldp);
358 const int new_b = cost_branch256(ct, newp);
359 const int update_b = 2048 + vp9_cost_upd256;
360 return old_b - new_b - update_b;
363 static int prob_diff_update_savings_search(const unsigned int *ct,
364 const vp9_prob oldp, vp9_prob *bestp,
365 const vp9_prob upd) {
366 const int old_b = cost_branch256(ct, oldp);
367 int new_b, update_b, savings, bestsavings, step;
368 vp9_prob newp, bestnewp;
373 step = (*bestp > oldp ? -1 : 1);
374 for (newp = *bestp; newp != oldp; newp += step) {
375 new_b = cost_branch256(ct, newp);
376 update_b = prob_diff_update_cost(newp, oldp) + vp9_cost_upd256;
377 savings = old_b - new_b - update_b;
378 if (savings > bestsavings) {
379 bestsavings = savings;
387 static int prob_diff_update_savings_search_model(const unsigned int *ct,
388 const vp9_prob *oldp,
392 int i, old_b, new_b, update_b, savings, bestsavings, step;
394 vp9_prob bestnewp, newplist[ENTROPY_NODES], oldplist[ENTROPY_NODES];
395 vp9_model_to_full_probs(oldp, oldplist);
396 vpx_memcpy(newplist, oldp, sizeof(vp9_prob) * UNCONSTRAINED_NODES);
397 for (i = UNCONSTRAINED_NODES, old_b = 0; i < ENTROPY_NODES; ++i)
398 old_b += cost_branch256(ct + 2 * i, oldplist[i]);
399 old_b += cost_branch256(ct + 2 * PIVOT_NODE, oldplist[PIVOT_NODE]);
402 bestnewp = oldp[PIVOT_NODE];
404 step = (*bestp > oldp[PIVOT_NODE] ? -1 : 1);
406 for (; newp != oldp[PIVOT_NODE]; newp += step) {
407 if (newp < 1 || newp > 255) continue;
408 newplist[PIVOT_NODE] = newp;
409 vp9_model_to_full_probs(newplist, newplist);
410 for (i = UNCONSTRAINED_NODES, new_b = 0; i < ENTROPY_NODES; ++i)
411 new_b += cost_branch256(ct + 2 * i, newplist[i]);
412 new_b += cost_branch256(ct + 2 * PIVOT_NODE, newplist[PIVOT_NODE]);
413 update_b = prob_diff_update_cost(newp, oldp[PIVOT_NODE]) +
415 savings = old_b - new_b - update_b;
416 if (savings > bestsavings) {
417 bestsavings = savings;
425 static void vp9_cond_prob_update(vp9_writer *bc, vp9_prob *oldp, vp9_prob upd,
429 newp = get_binary_prob(ct[0], ct[1]);
430 savings = prob_update_savings(ct, *oldp, newp, upd);
432 vp9_write(bc, 1, upd);
433 vp9_write_prob(bc, newp);
436 vp9_write(bc, 0, upd);
440 static void pack_mb_tokens(vp9_writer* const bc,
442 const TOKENEXTRA *const stop) {
446 const int t = p->token;
447 const struct vp9_token *const a = vp9_coef_encodings + t;
448 const vp9_extra_bit *const b = vp9_extra_bits + t;
453 vp9_prob probs[ENTROPY_NODES];
455 if (t == EOSB_TOKEN) {
459 if (t >= TWO_TOKEN) {
460 vp9_model_to_full_probs(p->context_tree, probs);
463 pp = p->context_tree;
467 /* skip one or two nodes */
468 #if !CONFIG_BALANCED_COEFTREE
469 if (p->skip_eob_node) {
470 n -= p->skip_eob_node;
471 i = 2 * p->skip_eob_node;
476 const int bb = (v >> --n) & 1;
477 #if CONFIG_BALANCED_COEFTREE
478 if (i == 2 && p->skip_eob_node) {
484 vp9_write(bc, bb, pp[i >> 1]);
485 i = vp9_coef_tree[i + bb];
489 const int e = p->extra, l = b->len;
492 const unsigned char *pb = b->prob;
494 int n = l; /* number of bits in v, assumed nonzero */
498 const int bb = (v >> --n) & 1;
499 vp9_write(bc, bb, pb[i >> 1]);
504 vp9_write_bit(bc, e & 1);
512 static void write_sb_mv_ref(vp9_writer *bc, MB_PREDICTION_MODE m,
515 assert(NEARESTMV <= m && m <= NEWMV);
517 write_token(bc, vp9_sb_mv_ref_tree, p,
518 vp9_sb_mv_ref_encoding_array - NEARESTMV + m);
521 // This function writes the current macro block's segnment id to the bitstream
522 // It should only be called if a segment map update is indicated.
523 static void write_mb_segid(vp9_writer *bc,
524 const MB_MODE_INFO *mi, const MACROBLOCKD *xd) {
525 if (xd->segmentation_enabled && xd->update_mb_segmentation_map)
526 treed_write(bc, vp9_segment_tree, xd->mb_segment_tree_probs,
530 // This function encodes the reference frame
531 static void encode_ref_frame(vp9_writer *const bc,
532 VP9_COMMON *const cm,
535 MV_REFERENCE_FRAME rf) {
537 int seg_ref_count = 0;
538 seg_ref_active = vp9_segfeature_active(xd,
542 if (seg_ref_active) {
543 seg_ref_count = vp9_check_segref(xd, segment_id, INTRA_FRAME) +
544 vp9_check_segref(xd, segment_id, LAST_FRAME) +
545 vp9_check_segref(xd, segment_id, GOLDEN_FRAME) +
546 vp9_check_segref(xd, segment_id, ALTREF_FRAME);
549 // If segment level coding of this signal is disabled...
550 // or the segment allows multiple reference frame options
551 if (!seg_ref_active || (seg_ref_count > 1)) {
552 // Values used in prediction model coding
553 unsigned char prediction_flag;
555 MV_REFERENCE_FRAME pred_rf;
557 // Get the context probability the prediction flag
558 pred_prob = vp9_get_pred_prob(cm, xd, PRED_REF);
560 // Get the predicted value.
561 pred_rf = vp9_get_pred_ref(cm, xd);
563 // Did the chosen reference frame match its predicted value.
565 (xd->mode_info_context->mbmi.ref_frame == pred_rf);
567 vp9_set_pred_flag(xd, PRED_REF, prediction_flag);
568 vp9_write(bc, prediction_flag, pred_prob);
570 // If not predicted correctly then code value explicitly
571 if (!prediction_flag) {
572 vp9_prob mod_refprobs[PREDICTION_PROBS];
574 vpx_memcpy(mod_refprobs,
575 cm->mod_refprobs[pred_rf], sizeof(mod_refprobs));
577 // If segment coding enabled blank out options that cant occur by
578 // setting the branch probability to 0.
579 if (seg_ref_active) {
580 mod_refprobs[INTRA_FRAME] *=
581 vp9_check_segref(xd, segment_id, INTRA_FRAME);
582 mod_refprobs[LAST_FRAME] *=
583 vp9_check_segref(xd, segment_id, LAST_FRAME);
584 mod_refprobs[GOLDEN_FRAME] *=
585 (vp9_check_segref(xd, segment_id, GOLDEN_FRAME) *
586 vp9_check_segref(xd, segment_id, ALTREF_FRAME));
589 if (mod_refprobs[0]) {
590 vp9_write(bc, (rf != INTRA_FRAME), mod_refprobs[0]);
594 if (rf != INTRA_FRAME) {
595 if (mod_refprobs[1]) {
596 vp9_write(bc, (rf != LAST_FRAME), mod_refprobs[1]);
599 if (rf != LAST_FRAME) {
600 if (mod_refprobs[2]) {
601 vp9_write(bc, (rf != GOLDEN_FRAME), mod_refprobs[2]);
608 // if using the prediction mdoel we have nothing further to do because
609 // the reference frame is fully coded by the segment
612 // Update the probabilities used to encode reference frame data
613 static void update_ref_probs(VP9_COMP *const cpi) {
614 VP9_COMMON *const cm = &cpi->common;
616 const int *const rfct = cpi->count_mb_ref_frame_usage;
617 const int rf_intra = rfct[INTRA_FRAME];
618 const int rf_inter = rfct[LAST_FRAME] +
619 rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
621 cm->prob_intra_coded = get_binary_prob(rf_intra, rf_inter);
622 cm->prob_last_coded = get_prob(rfct[LAST_FRAME], rf_inter);
623 cm->prob_gf_coded = get_binary_prob(rfct[GOLDEN_FRAME], rfct[ALTREF_FRAME]);
625 // Compute a modified set of probabilities to use when prediction of the
626 // reference frame fails
627 vp9_compute_mod_refprobs(cm);
630 static void pack_inter_mode_mvs(VP9_COMP *cpi, MODE_INFO *m,
631 vp9_writer *bc, int mi_row, int mi_col) {
632 VP9_COMMON *const pc = &cpi->common;
633 const nmv_context *nmvc = &pc->fc.nmvc;
634 MACROBLOCK *const x = &cpi->mb;
635 MACROBLOCKD *const xd = &x->e_mbd;
636 MB_MODE_INFO *const mi = &m->mbmi;
637 const MV_REFERENCE_FRAME rf = mi->ref_frame;
638 const MB_PREDICTION_MODE mode = mi->mode;
639 const int segment_id = mi->segment_id;
642 xd->prev_mode_info_context = pc->prev_mi + (m - pc->mi);
643 x->partition_info = x->pi + (m - pc->mi);
649 if (cpi->mb.e_mbd.update_mb_segmentation_map) {
650 // Is temporal coding of the segment map enabled
651 if (pc->temporal_update) {
652 unsigned char prediction_flag = vp9_get_pred_flag(xd, PRED_SEG_ID);
653 vp9_prob pred_prob = vp9_get_pred_prob(pc, xd, PRED_SEG_ID);
655 // Code the segment id prediction flag for this mb
656 vp9_write(bc, prediction_flag, pred_prob);
658 // If the mb segment id wasn't predicted code explicitly
659 if (!prediction_flag)
660 write_mb_segid(bc, mi, &cpi->mb.e_mbd);
662 // Normal unpredicted coding
663 write_mb_segid(bc, mi, &cpi->mb.e_mbd);
667 if (vp9_segfeature_active(xd, segment_id, SEG_LVL_SKIP)) {
670 skip_coeff = m->mbmi.mb_skip_coeff;
671 vp9_write(bc, skip_coeff,
672 vp9_get_pred_prob(pc, xd, PRED_MBSKIP));
675 // Encode the reference frame.
676 encode_ref_frame(bc, pc, xd, segment_id, rf);
678 if (mi->sb_type >= BLOCK_SIZE_SB8X8 && pc->txfm_mode == TX_MODE_SELECT &&
679 !(rf != INTRA_FRAME &&
680 (skip_coeff || vp9_segfeature_active(xd, segment_id, SEG_LVL_SKIP)))) {
681 TX_SIZE sz = mi->txfm_size;
682 // FIXME(rbultje) code ternary symbol once all experiments are merged
683 vp9_write(bc, sz != TX_4X4, pc->prob_tx[0]);
684 if (mi->sb_type >= BLOCK_SIZE_MB16X16 && sz != TX_4X4) {
685 vp9_write(bc, sz != TX_8X8, pc->prob_tx[1]);
686 if (mi->sb_type >= BLOCK_SIZE_SB32X32 && sz != TX_8X8)
687 vp9_write(bc, sz != TX_16X16, pc->prob_tx[2]);
691 if (rf == INTRA_FRAME) {
696 if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8) {
697 write_intra_mode(bc, mode, pc->fc.y_mode_prob);
700 int bw = 1 << b_width_log2(mi->sb_type);
701 int bh = 1 << b_height_log2(mi->sb_type);
702 for (idy = 0; idy < 2; idy += bh)
703 for (idx = 0; idx < 2; idx += bw)
704 write_intra_mode(bc, m->bmi[idy * 2 + idx].as_mode.first,
707 write_intra_mode(bc, mi->uv_mode,
708 pc->fc.uv_mode_prob[mode]);
710 vp9_prob mv_ref_p[VP9_MVREFS - 1];
712 vp9_mv_ref_probs(&cpi->common, mv_ref_p, mi->mb_mode_context[rf]);
718 // If segment skip is not enabled code the mode.
719 if (!vp9_segfeature_active(xd, segment_id, SEG_LVL_SKIP)) {
720 if (mi->sb_type >= BLOCK_SIZE_SB8X8) {
721 write_sb_mv_ref(bc, mode, mv_ref_p);
722 vp9_accum_mv_refs(&cpi->common, mode, mi->mb_mode_context[rf]);
726 if (cpi->common.mcomp_filter_type == SWITCHABLE) {
727 write_token(bc, vp9_switchable_interp_tree,
728 vp9_get_pred_probs(&cpi->common, xd,
729 PRED_SWITCHABLE_INTERP),
730 vp9_switchable_interp_encodings +
731 vp9_switchable_interp_map[mi->interp_filter]);
733 assert(mi->interp_filter == cpi->common.mcomp_filter_type);
736 // does the feature use compound prediction or not
737 // (if not specified at the frame/segment level)
738 if (cpi->common.comp_pred_mode == HYBRID_PREDICTION) {
739 vp9_write(bc, mi->second_ref_frame > INTRA_FRAME,
740 vp9_get_pred_prob(pc, xd, PRED_COMP));
743 if (xd->mode_info_context->mbmi.sb_type < BLOCK_SIZE_SB8X8) {
745 MB_PREDICTION_MODE blockmode;
747 int bwl = b_width_log2(mi->sb_type), bw = 1 << bwl;
748 int bhl = b_height_log2(mi->sb_type), bh = 1 << bhl;
750 for (idy = 0; idy < 2; idy += bh) {
751 for (idx = 0; idx < 2; idx += bw) {
753 blockmode = cpi->mb.partition_info->bmi[j].mode;
754 blockmv = cpi->mb.partition_info->bmi[j].mv;
755 write_sb_mv_ref(bc, blockmode, mv_ref_p);
756 vp9_accum_mv_refs(&cpi->common, blockmode, mi->mb_mode_context[rf]);
757 if (blockmode == NEWMV) {
761 vp9_encode_mv(bc, &blockmv.as_mv, &mi->best_mv.as_mv,
762 nmvc, xd->allow_high_precision_mv);
764 if (mi->second_ref_frame > 0)
766 &cpi->mb.partition_info->bmi[j].second_mv.as_mv,
767 &mi->best_second_mv.as_mv,
768 nmvc, xd->allow_high_precision_mv);
774 ++count_mb_seg[mi->partitioning];
776 } else if (mode == NEWMV) {
781 &mi->mv[0].as_mv, &mi->best_mv.as_mv,
782 nmvc, xd->allow_high_precision_mv);
784 if (mi->second_ref_frame > 0)
786 &mi->mv[1].as_mv, &mi->best_second_mv.as_mv,
787 nmvc, xd->allow_high_precision_mv);
792 static void write_mb_modes_kf(const VP9_COMP *cpi,
794 vp9_writer *bc, int mi_row, int mi_col) {
795 const VP9_COMMON *const c = &cpi->common;
796 const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
797 const int ym = m->mbmi.mode;
798 const int mis = c->mode_info_stride;
799 const int segment_id = m->mbmi.segment_id;
802 if (xd->update_mb_segmentation_map)
803 write_mb_segid(bc, &m->mbmi, xd);
805 if (vp9_segfeature_active(xd, segment_id, SEG_LVL_SKIP)) {
808 skip_coeff = m->mbmi.mb_skip_coeff;
809 vp9_write(bc, skip_coeff, vp9_get_pred_prob(c, xd, PRED_MBSKIP));
812 if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8 && c->txfm_mode == TX_MODE_SELECT) {
813 TX_SIZE sz = m->mbmi.txfm_size;
814 // FIXME(rbultje) code ternary symbol once all experiments are merged
815 vp9_write(bc, sz != TX_4X4, c->prob_tx[0]);
816 if (m->mbmi.sb_type >= BLOCK_SIZE_MB16X16 && sz != TX_4X4) {
817 vp9_write(bc, sz != TX_8X8, c->prob_tx[1]);
818 if (m->mbmi.sb_type >= BLOCK_SIZE_SB32X32 && sz != TX_8X8)
819 vp9_write(bc, sz != TX_16X16, c->prob_tx[2]);
823 if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8) {
824 const MB_PREDICTION_MODE A = above_block_mode(m, 0, mis);
825 const MB_PREDICTION_MODE L = xd->left_available ?
826 left_block_mode(m, 0) : DC_PRED;
827 write_intra_mode(bc, ym, c->kf_y_mode_prob[A][L]);
830 int bw = 1 << b_width_log2(m->mbmi.sb_type);
831 int bh = 1 << b_height_log2(m->mbmi.sb_type);
832 for (idy = 0; idy < 2; idy += bh) {
833 for (idx = 0; idx < 2; idx += bw) {
834 int i = idy * 2 + idx;
835 const MB_PREDICTION_MODE A = above_block_mode(m, i, mis);
836 const MB_PREDICTION_MODE L = (xd->left_available || idx) ?
837 left_block_mode(m, i) : DC_PRED;
838 const int bm = m->bmi[i].as_mode.first;
840 ++intra_mode_stats[A][L][bm];
842 write_intra_mode(bc, bm, c->kf_y_mode_prob[A][L]);
847 write_intra_mode(bc, m->mbmi.uv_mode, c->kf_uv_mode_prob[ym]);
850 static void write_modes_b(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
851 TOKENEXTRA **tok, TOKENEXTRA *tok_end,
852 int mi_row, int mi_col) {
853 VP9_COMMON *const cm = &cpi->common;
854 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
856 if (m->mbmi.sb_type < BLOCK_SIZE_SB8X8)
857 if (xd->ab_index > 0)
859 xd->mode_info_context = m;
860 set_mi_row_col(&cpi->common, xd, mi_row,
861 1 << mi_height_log2(m->mbmi.sb_type),
862 mi_col, 1 << mi_width_log2(m->mbmi.sb_type));
863 if (cm->frame_type == KEY_FRAME) {
864 write_mb_modes_kf(cpi, m, bc, mi_row, mi_col);
869 pack_inter_mode_mvs(cpi, m, bc, mi_row, mi_col);
875 assert(*tok < tok_end);
876 pack_mb_tokens(bc, tok, tok_end);
879 static void write_modes_sb(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
880 TOKENEXTRA **tok, TOKENEXTRA *tok_end,
881 int mi_row, int mi_col,
882 BLOCK_SIZE_TYPE bsize) {
883 VP9_COMMON *const cm = &cpi->common;
884 MACROBLOCKD *xd = &cpi->mb.e_mbd;
885 const int mis = cm->mode_info_stride;
887 int bsl = b_width_log2(bsize);
888 int bs = (1 << bsl) / 4; // mode_info step for subsize
890 PARTITION_TYPE partition;
891 BLOCK_SIZE_TYPE subsize;
893 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
896 bwl = b_width_log2(m->mbmi.sb_type);
897 bhl = b_height_log2(m->mbmi.sb_type);
899 // parse the partition type
900 if ((bwl == bsl) && (bhl == bsl))
901 partition = PARTITION_NONE;
902 else if ((bwl == bsl) && (bhl < bsl))
903 partition = PARTITION_HORZ;
904 else if ((bwl < bsl) && (bhl == bsl))
905 partition = PARTITION_VERT;
906 else if ((bwl < bsl) && (bhl < bsl))
907 partition = PARTITION_SPLIT;
911 if (bsize < BLOCK_SIZE_SB8X8)
912 if (xd->ab_index > 0)
915 if (bsize >= BLOCK_SIZE_SB8X8) {
917 xd->left_seg_context = cm->left_seg_context + (mi_row & MI_MASK);
918 xd->above_seg_context = cm->above_seg_context + mi_col;
919 pl = partition_plane_context(xd, bsize);
920 // encode the partition information
921 write_token(bc, vp9_partition_tree, cm->fc.partition_prob[pl],
922 vp9_partition_encodings + partition);
925 subsize = get_subsize(bsize, partition);
926 *(get_sb_index(xd, subsize)) = 0;
930 write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
933 write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
934 *(get_sb_index(xd, subsize)) = 1;
935 if ((mi_row + bs) < cm->mi_rows)
936 write_modes_b(cpi, m + bs * mis, bc, tok, tok_end, mi_row + bs, mi_col);
939 write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
940 *(get_sb_index(xd, subsize)) = 1;
941 if ((mi_col + bs) < cm->mi_cols)
942 write_modes_b(cpi, m + bs, bc, tok, tok_end, mi_row, mi_col + bs);
944 case PARTITION_SPLIT:
945 for (n = 0; n < 4; n++) {
946 int j = n >> 1, i = n & 0x01;
947 *(get_sb_index(xd, subsize)) = n;
948 write_modes_sb(cpi, m + j * bs * mis + i * bs, bc, tok, tok_end,
949 mi_row + j * bs, mi_col + i * bs, subsize);
956 // update partition context
957 if (bsize >= BLOCK_SIZE_SB8X8 &&
958 (bsize == BLOCK_SIZE_SB8X8 || partition != PARTITION_SPLIT)) {
959 set_partition_seg_context(cm, xd, mi_row, mi_col);
960 update_partition_context(xd, subsize, bsize);
964 static void write_modes(VP9_COMP *cpi, vp9_writer* const bc,
965 TOKENEXTRA **tok, TOKENEXTRA *tok_end) {
966 VP9_COMMON *const c = &cpi->common;
967 const int mis = c->mode_info_stride;
968 MODE_INFO *m, *m_ptr = c->mi;
971 m_ptr += c->cur_tile_mi_col_start + c->cur_tile_mi_row_start * mis;
972 vpx_memset(c->above_seg_context, 0, sizeof(PARTITION_CONTEXT) *
973 mi_cols_aligned_to_sb(c));
975 for (mi_row = c->cur_tile_mi_row_start;
976 mi_row < c->cur_tile_mi_row_end;
977 mi_row += 8, m_ptr += 8 * mis) {
979 vpx_memset(c->left_seg_context, 0, sizeof(c->left_seg_context));
980 for (mi_col = c->cur_tile_mi_col_start;
981 mi_col < c->cur_tile_mi_col_end;
982 mi_col += 64 / MI_SIZE, m += 64 / MI_SIZE)
983 write_modes_sb(cpi, m, bc, tok, tok_end, mi_row, mi_col,
988 /* This function is used for debugging probability trees. */
989 static void print_prob_tree(vp9_coeff_probs *coef_probs, int block_types) {
990 /* print coef probability tree */
992 FILE *f = fopen("enc_tree_probs.txt", "a");
994 for (i = 0; i < block_types; i++) {
996 for (j = 0; j < REF_TYPES; ++j) {
998 for (k = 0; k < COEF_BANDS; k++) {
1000 for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
1002 for (m = 0; m < ENTROPY_NODES; m++) {
1004 (unsigned int)(coef_probs[i][j][k][l][m]));
1017 static void build_tree_distribution(vp9_coeff_probs_model *coef_probs,
1018 vp9_coeff_count *coef_counts,
1019 unsigned int (*eob_branch_ct)[REF_TYPES]
1021 [PREV_COEF_CONTEXTS],
1022 #ifdef ENTROPY_STATS
1024 vp9_coeff_accum *context_counters,
1026 vp9_coeff_stats *coef_branch_ct,
1029 #ifdef ENTROPY_STATS
1032 vp9_prob full_probs[ENTROPY_NODES];
1034 for (i = 0; i < block_types; ++i) {
1035 for (j = 0; j < REF_TYPES; ++j) {
1036 for (k = 0; k < COEF_BANDS; ++k) {
1037 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
1038 if (l >= 3 && k == 0)
1040 vp9_tree_probs_from_distribution(vp9_coef_tree,
1042 coef_branch_ct[i][j][k][l],
1043 coef_counts[i][j][k][l], 0);
1044 vpx_memcpy(coef_probs[i][j][k][l], full_probs,
1045 sizeof(vp9_prob) * UNCONSTRAINED_NODES);
1046 #if CONFIG_BALANCED_COEFTREE
1047 coef_branch_ct[i][j][k][l][1][1] = eob_branch_ct[i][j][k][l] -
1048 coef_branch_ct[i][j][k][l][1][0];
1049 coef_probs[i][j][k][l][1] =
1050 get_binary_prob(coef_branch_ct[i][j][k][l][1][0],
1051 coef_branch_ct[i][j][k][l][1][1]);
1053 coef_branch_ct[i][j][k][l][0][1] = eob_branch_ct[i][j][k][l] -
1054 coef_branch_ct[i][j][k][l][0][0];
1055 coef_probs[i][j][k][l][0] =
1056 get_binary_prob(coef_branch_ct[i][j][k][l][0][0],
1057 coef_branch_ct[i][j][k][l][0][1]);
1059 #ifdef ENTROPY_STATS
1060 if (!cpi->dummy_packing) {
1061 for (t = 0; t < MAX_ENTROPY_TOKENS; ++t)
1062 context_counters[i][j][k][l][t] += coef_counts[i][j][k][l][t];
1063 context_counters[i][j][k][l][MAX_ENTROPY_TOKENS] +=
1064 eob_branch_ct[i][j][k][l];
1073 static void build_coeff_contexts(VP9_COMP *cpi) {
1074 build_tree_distribution(cpi->frame_coef_probs_4x4,
1075 cpi->coef_counts_4x4,
1076 cpi->common.fc.eob_branch_counts[TX_4X4],
1077 #ifdef ENTROPY_STATS
1078 cpi, context_counters_4x4,
1080 cpi->frame_branch_ct_4x4, BLOCK_TYPES);
1081 build_tree_distribution(cpi->frame_coef_probs_8x8,
1082 cpi->coef_counts_8x8,
1083 cpi->common.fc.eob_branch_counts[TX_8X8],
1084 #ifdef ENTROPY_STATS
1085 cpi, context_counters_8x8,
1087 cpi->frame_branch_ct_8x8, BLOCK_TYPES);
1088 build_tree_distribution(cpi->frame_coef_probs_16x16,
1089 cpi->coef_counts_16x16,
1090 cpi->common.fc.eob_branch_counts[TX_16X16],
1091 #ifdef ENTROPY_STATS
1092 cpi, context_counters_16x16,
1094 cpi->frame_branch_ct_16x16, BLOCK_TYPES);
1095 build_tree_distribution(cpi->frame_coef_probs_32x32,
1096 cpi->coef_counts_32x32,
1097 cpi->common.fc.eob_branch_counts[TX_32X32],
1098 #ifdef ENTROPY_STATS
1099 cpi, context_counters_32x32,
1101 cpi->frame_branch_ct_32x32, BLOCK_TYPES);
1104 static void update_coef_probs_common(
1105 vp9_writer* const bc,
1107 #ifdef ENTROPY_STATS
1108 vp9_coeff_stats *tree_update_hist,
1110 vp9_coeff_probs_model *new_frame_coef_probs,
1111 vp9_coeff_probs_model *old_frame_coef_probs,
1112 vp9_coeff_stats *frame_branch_ct,
1115 int update[2] = {0, 0};
1118 const int entropy_nodes_update = UNCONSTRAINED_NODES;
1120 const int tstart = 0;
1121 /* dry run to see if there is any udpate at all needed */
1123 for (i = 0; i < BLOCK_TYPES; ++i) {
1124 for (j = 0; j < REF_TYPES; ++j) {
1125 for (k = 0; k < COEF_BANDS; ++k) {
1126 // int prev_coef_savings[ENTROPY_NODES] = {0};
1127 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
1128 for (t = tstart; t < entropy_nodes_update; ++t) {
1129 vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
1130 const vp9_prob oldp = old_frame_coef_probs[i][j][k][l][t];
1131 const vp9_prob upd = vp9_coef_update_prob[t];
1135 if (l >= 3 && k == 0)
1137 if (t == PIVOT_NODE)
1138 s = prob_diff_update_savings_search_model(
1139 frame_branch_ct[i][j][k][l][0],
1140 old_frame_coef_probs[i][j][k][l], &newp, upd, i, j);
1142 s = prob_diff_update_savings_search(
1143 frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
1144 if (s > 0 && newp != oldp)
1147 savings += s - (int)(vp9_cost_zero(upd));
1149 savings -= (int)(vp9_cost_zero(upd));
1157 // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
1158 /* Is coef updated at all */
1159 if (update[1] == 0 || savings < 0) {
1160 vp9_write_bit(bc, 0);
1163 vp9_write_bit(bc, 1);
1164 for (i = 0; i < BLOCK_TYPES; ++i) {
1165 for (j = 0; j < REF_TYPES; ++j) {
1166 for (k = 0; k < COEF_BANDS; ++k) {
1167 // int prev_coef_savings[ENTROPY_NODES] = {0};
1168 for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
1169 // calc probs and branch cts for this frame only
1170 for (t = tstart; t < entropy_nodes_update; ++t) {
1171 vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
1172 vp9_prob *oldp = old_frame_coef_probs[i][j][k][l] + t;
1173 const vp9_prob upd = vp9_coef_update_prob[t];
1176 if (l >= 3 && k == 0)
1178 if (t == PIVOT_NODE)
1179 s = prob_diff_update_savings_search_model(
1180 frame_branch_ct[i][j][k][l][0],
1181 old_frame_coef_probs[i][j][k][l], &newp, upd, i, j);
1183 s = prob_diff_update_savings_search(
1184 frame_branch_ct[i][j][k][l][t],
1186 if (s > 0 && newp != *oldp)
1188 vp9_write(bc, u, upd);
1189 #ifdef ENTROPY_STATS
1190 if (!cpi->dummy_packing)
1191 ++tree_update_hist[i][j][k][l][t][u];
1194 /* send/use new probability */
1195 write_prob_diff_update(bc, newp, *oldp);
1205 static void update_coef_probs(VP9_COMP* const cpi, vp9_writer* const bc) {
1206 vp9_clear_system_state();
1208 // Build the cofficient contexts based on counts collected in encode loop
1209 build_coeff_contexts(cpi);
1211 update_coef_probs_common(bc,
1213 #ifdef ENTROPY_STATS
1214 tree_update_hist_4x4,
1216 cpi->frame_coef_probs_4x4,
1217 cpi->common.fc.coef_probs_4x4,
1218 cpi->frame_branch_ct_4x4,
1221 /* do not do this if not even allowed */
1222 if (cpi->common.txfm_mode != ONLY_4X4) {
1223 update_coef_probs_common(bc,
1225 #ifdef ENTROPY_STATS
1226 tree_update_hist_8x8,
1228 cpi->frame_coef_probs_8x8,
1229 cpi->common.fc.coef_probs_8x8,
1230 cpi->frame_branch_ct_8x8,
1234 if (cpi->common.txfm_mode > ALLOW_8X8) {
1235 update_coef_probs_common(bc,
1237 #ifdef ENTROPY_STATS
1238 tree_update_hist_16x16,
1240 cpi->frame_coef_probs_16x16,
1241 cpi->common.fc.coef_probs_16x16,
1242 cpi->frame_branch_ct_16x16,
1246 if (cpi->common.txfm_mode > ALLOW_16X16) {
1247 update_coef_probs_common(bc,
1249 #ifdef ENTROPY_STATS
1250 tree_update_hist_32x32,
1252 cpi->frame_coef_probs_32x32,
1253 cpi->common.fc.coef_probs_32x32,
1254 cpi->frame_branch_ct_32x32,
1259 static void segment_reference_frames(VP9_COMP *cpi) {
1260 VP9_COMMON *oci = &cpi->common;
1261 MODE_INFO *mi = oci->mi;
1262 int ref[MAX_MB_SEGMENTS] = {0};
1265 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1267 for (i = 0; i < oci->mb_rows; i++) {
1268 for (j = 0; j < oci->mb_cols; j++, mb_index++)
1269 ref[mi[mb_index].mbmi.segment_id] |= (1 << mi[mb_index].mbmi.ref_frame);
1272 for (i = 0; i < MAX_MB_SEGMENTS; i++) {
1273 vp9_enable_segfeature(xd, i, SEG_LVL_REF_FRAME);
1274 vp9_set_segdata(xd, i, SEG_LVL_REF_FRAME, ref[i]);
1278 static void encode_loopfilter(VP9_COMMON *pc, MACROBLOCKD *xd, vp9_writer *w) {
1281 // Encode the loop filter level and type
1282 vp9_write_literal(w, pc->filter_level, 6);
1283 vp9_write_literal(w, pc->sharpness_level, 3);
1285 // Write out loop filter deltas applied at the MB level based on mode or
1286 // ref frame (if they are enabled).
1287 vp9_write_bit(w, xd->mode_ref_lf_delta_enabled);
1289 if (xd->mode_ref_lf_delta_enabled) {
1290 // Do the deltas need to be updated
1291 vp9_write_bit(w, xd->mode_ref_lf_delta_update);
1292 if (xd->mode_ref_lf_delta_update) {
1294 for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
1295 const int delta = xd->ref_lf_deltas[i];
1298 if (delta != xd->last_ref_lf_deltas[i]) {
1299 xd->last_ref_lf_deltas[i] = delta;
1300 vp9_write_bit(w, 1);
1303 vp9_write_literal(w, delta & 0x3F, 6);
1304 vp9_write_bit(w, 0); // sign
1307 vp9_write_literal(w, (-delta) & 0x3F, 6);
1308 vp9_write_bit(w, 1); // sign
1311 vp9_write_bit(w, 0);
1316 for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
1317 const int delta = xd->mode_lf_deltas[i];
1318 if (delta != xd->last_mode_lf_deltas[i]) {
1319 xd->last_mode_lf_deltas[i] = delta;
1320 vp9_write_bit(w, 1);
1323 vp9_write_literal(w, delta & 0x3F, 6);
1324 vp9_write_bit(w, 0); // sign
1327 vp9_write_literal(w, (-delta) & 0x3F, 6);
1328 vp9_write_bit(w, 1); // sign
1331 vp9_write_bit(w, 0);
1338 static void put_delta_q(vp9_writer *bc, int delta_q) {
1340 vp9_write_bit(bc, 1);
1341 vp9_write_literal(bc, abs(delta_q), 4);
1342 vp9_write_bit(bc, delta_q < 0);
1344 vp9_write_bit(bc, 0);
1348 static void encode_quantization(VP9_COMMON *pc, vp9_writer *w) {
1349 vp9_write_literal(w, pc->base_qindex, QINDEX_BITS);
1350 put_delta_q(w, pc->y_dc_delta_q);
1351 put_delta_q(w, pc->uv_dc_delta_q);
1352 put_delta_q(w, pc->uv_ac_delta_q);
1356 static void encode_segmentation(VP9_COMP *cpi, vp9_writer *w) {
1358 VP9_COMMON *const pc = &cpi->common;
1359 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1361 vp9_write_bit(w, xd->segmentation_enabled);
1362 if (!xd->segmentation_enabled)
1366 vp9_write_bit(w, xd->update_mb_segmentation_map);
1367 if (xd->update_mb_segmentation_map) {
1368 // Select the coding strategy (temporal or spatial)
1369 vp9_choose_segmap_coding_method(cpi);
1370 // Write out probabilities used to decode unpredicted macro-block segments
1371 for (i = 0; i < MB_SEG_TREE_PROBS; i++) {
1372 const int prob = xd->mb_segment_tree_probs[i];
1373 if (prob != MAX_PROB) {
1374 vp9_write_bit(w, 1);
1375 vp9_write_prob(w, prob);
1377 vp9_write_bit(w, 0);
1381 // Write out the chosen coding method.
1382 vp9_write_bit(w, pc->temporal_update);
1383 if (pc->temporal_update) {
1384 for (i = 0; i < PREDICTION_PROBS; i++) {
1385 const int prob = pc->segment_pred_probs[i];
1386 if (prob != MAX_PROB) {
1387 vp9_write_bit(w, 1);
1388 vp9_write_prob(w, prob);
1390 vp9_write_bit(w, 0);
1396 // Segmentation data
1397 vp9_write_bit(w, xd->update_mb_segmentation_data);
1398 // segment_reference_frames(cpi);
1399 if (xd->update_mb_segmentation_data) {
1400 vp9_write_bit(w, xd->mb_segment_abs_delta);
1402 for (i = 0; i < MAX_MB_SEGMENTS; i++) {
1403 for (j = 0; j < SEG_LVL_MAX; j++) {
1404 const int data = vp9_get_segdata(xd, i, j);
1405 const int data_max = vp9_seg_feature_data_max(j);
1407 if (vp9_segfeature_active(xd, i, j)) {
1408 vp9_write_bit(w, 1);
1410 if (vp9_is_segfeature_signed(j)) {
1412 vp9_encode_unsigned_max(w, -data, data_max);
1413 vp9_write_bit(w, 1);
1415 vp9_encode_unsigned_max(w, data, data_max);
1416 vp9_write_bit(w, 0);
1419 vp9_encode_unsigned_max(w, data, data_max);
1422 vp9_write_bit(w, 0);
1429 void write_uncompressed_header(VP9_COMMON *cm,
1430 struct vp9_write_bit_buffer *wb) {
1431 const int scaling_active = cm->width != cm->display_width ||
1432 cm->height != cm->display_height;
1434 vp9_wb_write_bit(wb, cm->frame_type);
1435 vp9_wb_write_literal(wb, cm->version, 3);
1436 vp9_wb_write_bit(wb, cm->show_frame);
1437 vp9_wb_write_bit(wb, scaling_active);
1438 vp9_wb_write_bit(wb, cm->subsampling_x);
1439 vp9_wb_write_bit(wb, cm->subsampling_y);
1441 if (cm->frame_type == KEY_FRAME) {
1442 vp9_wb_write_literal(wb, SYNC_CODE_0, 8);
1443 vp9_wb_write_literal(wb, SYNC_CODE_1, 8);
1444 vp9_wb_write_literal(wb, SYNC_CODE_2, 8);
1447 if (scaling_active) {
1448 vp9_wb_write_literal(wb, cm->display_width, 16);
1449 vp9_wb_write_literal(wb, cm->display_height, 16);
1452 vp9_wb_write_literal(wb, cm->width, 16);
1453 vp9_wb_write_literal(wb, cm->height, 16);
1455 if (!cm->show_frame) {
1456 vp9_wb_write_bit(wb, cm->intra_only);
1459 vp9_wb_write_literal(wb, cm->frame_context_idx, NUM_FRAME_CONTEXTS_LG2);
1460 vp9_wb_write_bit(wb, cm->clr_type);
1462 vp9_wb_write_bit(wb, cm->error_resilient_mode);
1463 if (!cm->error_resilient_mode) {
1464 vp9_wb_write_bit(wb, cm->reset_frame_context);
1465 vp9_wb_write_bit(wb, cm->refresh_frame_context);
1466 vp9_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
1470 void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, unsigned long *size) {
1471 int i, bytes_packed;
1472 VP9_COMMON *const pc = &cpi->common;
1473 vp9_writer header_bc, residual_bc;
1474 MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1476 uint8_t *cx_data = dest;
1477 struct vp9_write_bit_buffer wb = {dest, 0};
1478 struct vp9_write_bit_buffer first_partition_size_wb;
1480 write_uncompressed_header(pc, &wb);
1481 first_partition_size_wb = wb;
1482 vp9_wb_write_literal(&wb, 0, 16); // don't know in advance first part. size
1484 bytes_packed = vp9_rb_bytes_written(&wb);
1485 cx_data += bytes_packed;
1487 compute_update_table();
1489 vp9_start_encode(&header_bc, cx_data);
1491 encode_loopfilter(pc, xd, &header_bc);
1493 encode_quantization(pc, &header_bc);
1495 // When there is a key frame all reference buffers are updated using the new key frame
1496 if (pc->frame_type != KEY_FRAME) {
1499 // Should the GF or ARF be updated using the transmitted frame or buffer
1500 #if CONFIG_MULTIPLE_ARF
1501 if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1502 !cpi->refresh_alt_ref_frame) {
1504 if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame) {
1506 /* Preserve the previously existing golden frame and update the frame in
1507 * the alt ref slot instead. This is highly specific to the use of
1508 * alt-ref as a forward reference, and this needs to be generalized as
1509 * other uses are implemented (like RTC/temporal scaling)
1511 * gld_fb_idx and alt_fb_idx need to be swapped for future frames, but
1512 * that happens in vp9_onyx_if.c:update_reference_frames() so that it can
1513 * be done outside of the recode loop.
1515 refresh_mask = (cpi->refresh_last_frame << cpi->lst_fb_idx) |
1516 (cpi->refresh_golden_frame << cpi->alt_fb_idx);
1518 int arf_idx = cpi->alt_fb_idx;
1519 #if CONFIG_MULTIPLE_ARF
1520 // Determine which ARF buffer to use to encode this ARF frame.
1521 if (cpi->multi_arf_enabled) {
1522 int sn = cpi->sequence_number;
1523 arf_idx = (cpi->frame_coding_order[sn] < 0) ?
1524 cpi->arf_buffer_idx[sn + 1] :
1525 cpi->arf_buffer_idx[sn];
1528 refresh_mask = (cpi->refresh_last_frame << cpi->lst_fb_idx) |
1529 (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
1530 (cpi->refresh_alt_ref_frame << arf_idx);
1533 vp9_write_literal(&header_bc, refresh_mask, NUM_REF_FRAMES);
1534 vp9_write_literal(&header_bc, cpi->lst_fb_idx, NUM_REF_FRAMES_LG2);
1535 vp9_write_literal(&header_bc, cpi->gld_fb_idx, NUM_REF_FRAMES_LG2);
1536 vp9_write_literal(&header_bc, cpi->alt_fb_idx, NUM_REF_FRAMES_LG2);
1538 // Indicate the sign bias for each reference frame buffer.
1539 for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
1540 vp9_write_bit(&header_bc, pc->ref_frame_sign_bias[LAST_FRAME + i]);
1543 // Signal whether to allow high MV precision
1544 vp9_write_bit(&header_bc, (xd->allow_high_precision_mv) ? 1 : 0);
1545 if (pc->mcomp_filter_type == SWITCHABLE) {
1546 /* Check to see if only one of the filters is actually used */
1547 int count[VP9_SWITCHABLE_FILTERS];
1549 for (i = 0; i < VP9_SWITCHABLE_FILTERS; ++i) {
1551 for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j)
1552 count[i] += cpi->switchable_interp_count[j][i];
1553 c += (count[i] > 0);
1556 /* Only one filter is used. So set the filter at frame level */
1557 for (i = 0; i < VP9_SWITCHABLE_FILTERS; ++i) {
1559 pc->mcomp_filter_type = vp9_switchable_interp[i];
1565 // Signal the type of subpel filter to use
1566 vp9_write_bit(&header_bc, (pc->mcomp_filter_type == SWITCHABLE));
1567 if (pc->mcomp_filter_type != SWITCHABLE)
1568 vp9_write_literal(&header_bc, (pc->mcomp_filter_type), 2);
1571 #ifdef ENTROPY_STATS
1572 if (pc->frame_type == INTER_FRAME)
1578 encode_segmentation(cpi, &header_bc);
1580 // Encode the common prediction model status flag probability updates for
1581 // the reference frame
1582 update_refpred_stats(cpi);
1583 if (pc->frame_type != KEY_FRAME) {
1584 for (i = 0; i < PREDICTION_PROBS; i++) {
1585 if (cpi->ref_pred_probs_update[i]) {
1586 vp9_write_bit(&header_bc, 1);
1587 vp9_write_prob(&header_bc, pc->ref_pred_probs[i]);
1589 vp9_write_bit(&header_bc, 0);
1594 if (cpi->mb.e_mbd.lossless) {
1595 pc->txfm_mode = ONLY_4X4;
1597 if (pc->txfm_mode == TX_MODE_SELECT) {
1598 pc->prob_tx[0] = get_prob(cpi->txfm_count_32x32p[TX_4X4] +
1599 cpi->txfm_count_16x16p[TX_4X4] +
1600 cpi->txfm_count_8x8p[TX_4X4],
1601 cpi->txfm_count_32x32p[TX_4X4] +
1602 cpi->txfm_count_32x32p[TX_8X8] +
1603 cpi->txfm_count_32x32p[TX_16X16] +
1604 cpi->txfm_count_32x32p[TX_32X32] +
1605 cpi->txfm_count_16x16p[TX_4X4] +
1606 cpi->txfm_count_16x16p[TX_8X8] +
1607 cpi->txfm_count_16x16p[TX_16X16] +
1608 cpi->txfm_count_8x8p[TX_4X4] +
1609 cpi->txfm_count_8x8p[TX_8X8]);
1610 pc->prob_tx[1] = get_prob(cpi->txfm_count_32x32p[TX_8X8] +
1611 cpi->txfm_count_16x16p[TX_8X8],
1612 cpi->txfm_count_32x32p[TX_8X8] +
1613 cpi->txfm_count_32x32p[TX_16X16] +
1614 cpi->txfm_count_32x32p[TX_32X32] +
1615 cpi->txfm_count_16x16p[TX_8X8] +
1616 cpi->txfm_count_16x16p[TX_16X16]);
1617 pc->prob_tx[2] = get_prob(cpi->txfm_count_32x32p[TX_16X16],
1618 cpi->txfm_count_32x32p[TX_16X16] +
1619 cpi->txfm_count_32x32p[TX_32X32]);
1621 pc->prob_tx[0] = 128;
1622 pc->prob_tx[1] = 128;
1623 pc->prob_tx[2] = 128;
1625 vp9_write_literal(&header_bc, pc->txfm_mode <= 3 ? pc->txfm_mode : 3, 2);
1626 if (pc->txfm_mode > ALLOW_16X16) {
1627 vp9_write_bit(&header_bc, pc->txfm_mode == TX_MODE_SELECT);
1629 if (pc->txfm_mode == TX_MODE_SELECT) {
1630 vp9_write_prob(&header_bc, pc->prob_tx[0]);
1631 vp9_write_prob(&header_bc, pc->prob_tx[1]);
1632 vp9_write_prob(&header_bc, pc->prob_tx[2]);
1636 // If appropriate update the inter mode probability context and code the
1637 // changes in the bitstream.
1638 if (pc->frame_type != KEY_FRAME) {
1640 int new_context[INTER_MODE_CONTEXTS][VP9_MVREFS - 1];
1641 if (!cpi->dummy_packing) {
1642 update_inter_mode_probs(pc, new_context);
1644 // In dummy pack assume context unchanged.
1645 vpx_memcpy(new_context, pc->fc.vp9_mode_contexts,
1646 sizeof(pc->fc.vp9_mode_contexts));
1649 for (i = 0; i < INTER_MODE_CONTEXTS; i++) {
1650 for (j = 0; j < VP9_MVREFS - 1; j++) {
1651 if (new_context[i][j] != pc->fc.vp9_mode_contexts[i][j]) {
1652 vp9_write(&header_bc, 1, 252);
1653 vp9_write_prob(&header_bc, new_context[i][j]);
1655 // Only update the persistent copy if this is the "real pack"
1656 if (!cpi->dummy_packing) {
1657 pc->fc.vp9_mode_contexts[i][j] = new_context[i][j];
1660 vp9_write(&header_bc, 0, 252);
1666 vp9_clear_system_state(); // __asm emms;
1668 vp9_copy(cpi->common.fc.pre_coef_probs_4x4,
1669 cpi->common.fc.coef_probs_4x4);
1670 vp9_copy(cpi->common.fc.pre_coef_probs_8x8,
1671 cpi->common.fc.coef_probs_8x8);
1672 vp9_copy(cpi->common.fc.pre_coef_probs_16x16,
1673 cpi->common.fc.coef_probs_16x16);
1674 vp9_copy(cpi->common.fc.pre_coef_probs_32x32,
1675 cpi->common.fc.coef_probs_32x32);
1677 vp9_copy(cpi->common.fc.pre_y_mode_prob, cpi->common.fc.y_mode_prob);
1678 vp9_copy(cpi->common.fc.pre_uv_mode_prob, cpi->common.fc.uv_mode_prob);
1679 vp9_copy(cpi->common.fc.pre_partition_prob, cpi->common.fc.partition_prob);
1680 cpi->common.fc.pre_nmvc = cpi->common.fc.nmvc;
1681 vp9_zero(cpi->common.fc.mv_ref_ct);
1683 update_coef_probs(cpi, &header_bc);
1685 #ifdef ENTROPY_STATS
1689 vp9_update_skip_probs(cpi);
1690 for (i = 0; i < MBSKIP_CONTEXTS; ++i) {
1691 vp9_write_prob(&header_bc, pc->mbskip_pred_probs[i]);
1694 if (pc->frame_type != KEY_FRAME) {
1695 // Update the probabilities used to encode reference frame data
1696 update_ref_probs(cpi);
1698 #ifdef ENTROPY_STATS
1702 if (pc->mcomp_filter_type == SWITCHABLE)
1703 update_switchable_interp_probs(cpi, &header_bc);
1705 vp9_write_prob(&header_bc, pc->prob_intra_coded);
1706 vp9_write_prob(&header_bc, pc->prob_last_coded);
1707 vp9_write_prob(&header_bc, pc->prob_gf_coded);
1710 const int comp_pred_mode = cpi->common.comp_pred_mode;
1711 const int use_compound_pred = (comp_pred_mode != SINGLE_PREDICTION_ONLY);
1712 const int use_hybrid_pred = (comp_pred_mode == HYBRID_PREDICTION);
1714 vp9_write_bit(&header_bc, use_compound_pred);
1715 if (use_compound_pred) {
1716 vp9_write_bit(&header_bc, use_hybrid_pred);
1717 if (use_hybrid_pred) {
1718 for (i = 0; i < COMP_PRED_CONTEXTS; i++) {
1719 pc->prob_comppred[i] = get_binary_prob(cpi->single_pred_count[i],
1720 cpi->comp_pred_count[i]);
1721 vp9_write_prob(&header_bc, pc->prob_comppred[i]);
1726 update_mbintra_mode_probs(cpi, &header_bc);
1728 for (i = 0; i < NUM_PARTITION_CONTEXTS; ++i) {
1729 vp9_prob Pnew[PARTITION_TYPES - 1];
1730 unsigned int bct[PARTITION_TYPES - 1][2];
1731 update_mode(&header_bc, PARTITION_TYPES, vp9_partition_encodings,
1732 vp9_partition_tree, Pnew, pc->fc.partition_prob[i], bct,
1733 (unsigned int *)cpi->partition_count[i]);
1736 vp9_write_nmv_probs(cpi, xd->allow_high_precision_mv, &header_bc);
1741 int min_log2_tiles, delta_log2_tiles, n_tile_bits, n;
1743 vp9_get_tile_n_bits(pc, &min_log2_tiles, &delta_log2_tiles);
1744 n_tile_bits = pc->log2_tile_columns - min_log2_tiles;
1745 for (n = 0; n < delta_log2_tiles; n++) {
1746 if (n_tile_bits--) {
1747 vp9_write_bit(&header_bc, 1);
1749 vp9_write_bit(&header_bc, 0);
1753 vp9_write_bit(&header_bc, pc->log2_tile_rows != 0);
1754 if (pc->log2_tile_rows != 0)
1755 vp9_write_bit(&header_bc, pc->log2_tile_rows != 1);
1758 vp9_stop_encode(&header_bc);
1761 // first partition size
1762 assert(header_bc.pos <= 0xffff);
1763 vp9_wb_write_literal(&first_partition_size_wb, header_bc.pos, 16);
1764 *size = bytes_packed + header_bc.pos;
1767 int tile_row, tile_col, total_size = 0;
1768 unsigned char *data_ptr = cx_data + header_bc.pos;
1769 TOKENEXTRA *tok[1 << 6], *tok_end;
1772 for (tile_col = 1; tile_col < pc->tile_columns; tile_col++)
1773 tok[tile_col] = tok[tile_col - 1] + cpi->tok_count[tile_col - 1];
1775 for (tile_row = 0; tile_row < pc->tile_rows; tile_row++) {
1776 vp9_get_tile_row_offsets(pc, tile_row);
1777 tok_end = cpi->tok + cpi->tok_count[0];
1778 for (tile_col = 0; tile_col < pc->tile_columns;
1779 tile_col++, tok_end += cpi->tok_count[tile_col]) {
1780 vp9_get_tile_col_offsets(pc, tile_col);
1782 if (tile_col < pc->tile_columns - 1 || tile_row < pc->tile_rows - 1)
1783 vp9_start_encode(&residual_bc, data_ptr + total_size + 4);
1785 vp9_start_encode(&residual_bc, data_ptr + total_size);
1786 write_modes(cpi, &residual_bc, &tok[tile_col], tok_end);
1787 vp9_stop_encode(&residual_bc);
1788 if (tile_col < pc->tile_columns - 1 || tile_row < pc->tile_rows - 1) {
1789 // size of this tile
1790 write_le32(data_ptr + total_size, residual_bc.pos);
1794 total_size += residual_bc.pos;
1798 assert((unsigned int)(tok[0] - cpi->tok) == cpi->tok_count[0]);
1799 for (tile_col = 1; tile_col < pc->tile_columns; tile_col++)
1800 assert((unsigned int)(tok[tile_col] - tok[tile_col - 1]) ==
1801 cpi->tok_count[tile_col]);
1803 *size += total_size;
1807 #ifdef ENTROPY_STATS
1808 static void print_tree_update_for_type(FILE *f,
1809 vp9_coeff_stats *tree_update_hist,
1810 int block_types, const char *header) {
1813 fprintf(f, "const vp9_coeff_prob %s = {\n", header);
1814 for (i = 0; i < block_types; i++) {
1815 fprintf(f, " { \n");
1816 for (j = 0; j < REF_TYPES; j++) {
1817 fprintf(f, " { \n");
1818 for (k = 0; k < COEF_BANDS; k++) {
1820 for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
1822 for (m = 0; m < ENTROPY_NODES; m++) {
1824 get_binary_prob(tree_update_hist[i][j][k][l][m][0],
1825 tree_update_hist[i][j][k][l][m][1]));
1831 fprintf(f, " },\n");
1833 fprintf(f, " },\n");
1838 void print_tree_update_probs() {
1839 FILE *f = fopen("coefupdprob.h", "w");
1840 fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1842 print_tree_update_for_type(f, tree_update_hist_4x4, BLOCK_TYPES,
1843 "vp9_coef_update_probs_4x4[BLOCK_TYPES]");
1844 print_tree_update_for_type(f, tree_update_hist_8x8, BLOCK_TYPES,
1845 "vp9_coef_update_probs_8x8[BLOCK_TYPES]");
1846 print_tree_update_for_type(f, tree_update_hist_16x16, BLOCK_TYPES,
1847 "vp9_coef_update_probs_16x16[BLOCK_TYPES]");
1848 print_tree_update_for_type(f, tree_update_hist_32x32, BLOCK_TYPES,
1849 "vp9_coef_update_probs_32x32[BLOCK_TYPES]");
1852 f = fopen("treeupdate.bin", "wb");
1853 fwrite(tree_update_hist_4x4, sizeof(tree_update_hist_4x4), 1, f);
1854 fwrite(tree_update_hist_8x8, sizeof(tree_update_hist_8x8), 1, f);
1855 fwrite(tree_update_hist_16x16, sizeof(tree_update_hist_16x16), 1, f);
1856 fwrite(tree_update_hist_32x32, sizeof(tree_update_hist_32x32), 1, f);