Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / third_party / libvpx / source / libvpx / vp9 / encoder / vp9_bitstream.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
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.
9  */
10
11 #include <assert.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "vpx/vpx_encoder.h"
16 #include "vpx_mem/vpx_mem.h"
17 #include "vpx_ports/mem_ops.h"
18
19 #include "vp9/common/vp9_entropy.h"
20 #include "vp9/common/vp9_entropymode.h"
21 #include "vp9/common/vp9_entropymv.h"
22 #include "vp9/common/vp9_mvref_common.h"
23 #include "vp9/common/vp9_pragmas.h"
24 #include "vp9/common/vp9_pred_common.h"
25 #include "vp9/common/vp9_seg_common.h"
26 #include "vp9/common/vp9_systemdependent.h"
27 #include "vp9/common/vp9_tile_common.h"
28
29 #include "vp9/encoder/vp9_bitstream.h"
30 #include "vp9/encoder/vp9_encodemv.h"
31 #include "vp9/encoder/vp9_mcomp.h"
32 #include "vp9/encoder/vp9_segmentation.h"
33 #include "vp9/encoder/vp9_subexp.h"
34 #include "vp9/encoder/vp9_tokenize.h"
35 #include "vp9/encoder/vp9_write_bit_buffer.h"
36
37 #ifdef ENTROPY_STATS
38 extern unsigned int active_section;
39 #endif
40
41 static struct vp9_token intra_mode_encodings[INTRA_MODES];
42 static struct vp9_token switchable_interp_encodings[SWITCHABLE_FILTERS];
43 static struct vp9_token partition_encodings[PARTITION_TYPES];
44 static struct vp9_token inter_mode_encodings[INTER_MODES];
45
46 void vp9_entropy_mode_init() {
47   vp9_tokens_from_tree(intra_mode_encodings, vp9_intra_mode_tree);
48   vp9_tokens_from_tree(switchable_interp_encodings, vp9_switchable_interp_tree);
49   vp9_tokens_from_tree(partition_encodings, vp9_partition_tree);
50   vp9_tokens_from_tree(inter_mode_encodings, vp9_inter_mode_tree);
51 }
52
53 static void write_intra_mode(vp9_writer *w, MB_PREDICTION_MODE mode,
54                              const vp9_prob *probs) {
55   vp9_write_token(w, vp9_intra_mode_tree, probs, &intra_mode_encodings[mode]);
56 }
57
58 static void write_inter_mode(vp9_writer *w, MB_PREDICTION_MODE mode,
59                              const vp9_prob *probs) {
60   assert(is_inter_mode(mode));
61   vp9_write_token(w, vp9_inter_mode_tree, probs,
62                   &inter_mode_encodings[INTER_OFFSET(mode)]);
63 }
64
65 static void encode_unsigned_max(struct vp9_write_bit_buffer *wb,
66                                 int data, int max) {
67   vp9_wb_write_literal(wb, data, get_unsigned_bits(max));
68 }
69
70 static void prob_diff_update(const vp9_tree_index *tree,
71                              vp9_prob probs[/*n - 1*/],
72                              const unsigned int counts[/*n - 1*/],
73                              int n, vp9_writer *w) {
74   int i;
75   unsigned int branch_ct[32][2];
76
77   // Assuming max number of probabilities <= 32
78   assert(n <= 32);
79
80   vp9_tree_probs_from_distribution(tree, branch_ct, counts);
81   for (i = 0; i < n - 1; ++i)
82     vp9_cond_prob_diff_update(w, &probs[i], branch_ct[i]);
83 }
84
85 static void write_selected_tx_size(const VP9_COMP *cpi,
86                                    TX_SIZE tx_size, BLOCK_SIZE bsize,
87                                    vp9_writer *w) {
88   const TX_SIZE max_tx_size = max_txsize_lookup[bsize];
89   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
90   const vp9_prob *const tx_probs = get_tx_probs2(max_tx_size, xd,
91                                                  &cpi->common.fc.tx_probs);
92   vp9_write(w, tx_size != TX_4X4, tx_probs[0]);
93   if (tx_size != TX_4X4 && max_tx_size >= TX_16X16) {
94     vp9_write(w, tx_size != TX_8X8, tx_probs[1]);
95     if (tx_size != TX_8X8 && max_tx_size >= TX_32X32)
96       vp9_write(w, tx_size != TX_16X16, tx_probs[2]);
97   }
98 }
99
100 static int write_skip(const VP9_COMP *cpi, int segment_id, MODE_INFO *m,
101                       vp9_writer *w) {
102   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
103   if (vp9_segfeature_active(&cpi->common.seg, segment_id, SEG_LVL_SKIP)) {
104     return 1;
105   } else {
106     const int skip = m->mbmi.skip;
107     vp9_write(w, skip, vp9_get_skip_prob(&cpi->common, xd));
108     return skip;
109   }
110 }
111
112 static void update_skip_probs(VP9_COMMON *cm, vp9_writer *w) {
113   int k;
114
115   for (k = 0; k < SKIP_CONTEXTS; ++k)
116     vp9_cond_prob_diff_update(w, &cm->fc.skip_probs[k], cm->counts.skip[k]);
117 }
118
119 static void update_switchable_interp_probs(VP9_COMMON *cm, vp9_writer *w) {
120   int j;
121   for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
122     prob_diff_update(vp9_switchable_interp_tree,
123                      cm->fc.switchable_interp_prob[j],
124                      cm->counts.switchable_interp[j], SWITCHABLE_FILTERS, w);
125 }
126
127 static void pack_mb_tokens(vp9_writer *w,
128                            TOKENEXTRA **tp, const TOKENEXTRA *stop) {
129   TOKENEXTRA *p = *tp;
130
131   while (p < stop && p->token != EOSB_TOKEN) {
132     const int t = p->token;
133     const struct vp9_token *const a = &vp9_coef_encodings[t];
134     const vp9_extra_bit *const b = &vp9_extra_bits[t];
135     int i = 0;
136     int v = a->value;
137     int n = a->len;
138
139     /* skip one or two nodes */
140     if (p->skip_eob_node) {
141       n -= p->skip_eob_node;
142       i = 2 * p->skip_eob_node;
143     }
144
145     // TODO(jbb): expanding this can lead to big gains.  It allows
146     // much better branch prediction and would enable us to avoid numerous
147     // lookups and compares.
148
149     // If we have a token that's in the constrained set, the coefficient tree
150     // is split into two treed writes.  The first treed write takes care of the
151     // unconstrained nodes.  The second treed write takes care of the
152     // constrained nodes.
153     if (t >= TWO_TOKEN && t < EOB_TOKEN) {
154       int len = UNCONSTRAINED_NODES - p->skip_eob_node;
155       int bits = v >> (n - len);
156       vp9_write_tree(w, vp9_coef_tree, p->context_tree, bits, len, i);
157       vp9_write_tree(w, vp9_coef_con_tree,
158                      vp9_pareto8_full[p->context_tree[PIVOT_NODE] - 1],
159                      v, n - len, 0);
160     } else {
161       vp9_write_tree(w, vp9_coef_tree, p->context_tree, v, n, i);
162     }
163
164     if (b->base_val) {
165       const int e = p->extra, l = b->len;
166
167       if (l) {
168         const unsigned char *pb = b->prob;
169         int v = e >> 1;
170         int n = l;              /* number of bits in v, assumed nonzero */
171         int i = 0;
172
173         do {
174           const int bb = (v >> --n) & 1;
175           vp9_write(w, bb, pb[i >> 1]);
176           i = b->tree[i + bb];
177         } while (n);
178       }
179
180       vp9_write_bit(w, e & 1);
181     }
182     ++p;
183   }
184
185   *tp = p + (p->token == EOSB_TOKEN);
186 }
187
188 static void write_segment_id(vp9_writer *w, const struct segmentation *seg,
189                              int segment_id) {
190   if (seg->enabled && seg->update_map)
191     vp9_write_tree(w, vp9_segment_tree, seg->tree_probs, segment_id, 3, 0);
192 }
193
194 // This function encodes the reference frame
195 static void write_ref_frames(const VP9_COMP *cpi, vp9_writer *w) {
196   const VP9_COMMON *const cm = &cpi->common;
197   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
198   const MB_MODE_INFO *const mbmi = &xd->mi_8x8[0]->mbmi;
199   const int is_compound = has_second_ref(mbmi);
200   const int segment_id = mbmi->segment_id;
201
202   // If segment level coding of this signal is disabled...
203   // or the segment allows multiple reference frame options
204   if (vp9_segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) {
205     assert(!is_compound);
206     assert(mbmi->ref_frame[0] ==
207                vp9_get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME));
208   } else {
209     // does the feature use compound prediction or not
210     // (if not specified at the frame/segment level)
211     if (cm->reference_mode == REFERENCE_MODE_SELECT) {
212       vp9_write(w, is_compound, vp9_get_reference_mode_prob(cm, xd));
213     } else {
214       assert(!is_compound == (cm->reference_mode == SINGLE_REFERENCE));
215     }
216
217     if (is_compound) {
218       vp9_write(w, mbmi->ref_frame[0] == GOLDEN_FRAME,
219                 vp9_get_pred_prob_comp_ref_p(cm, xd));
220     } else {
221       const int bit0 = mbmi->ref_frame[0] != LAST_FRAME;
222       vp9_write(w, bit0, vp9_get_pred_prob_single_ref_p1(cm, xd));
223       if (bit0) {
224         const int bit1 = mbmi->ref_frame[0] != GOLDEN_FRAME;
225         vp9_write(w, bit1, vp9_get_pred_prob_single_ref_p2(cm, xd));
226       }
227     }
228   }
229 }
230
231 static void pack_inter_mode_mvs(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc) {
232   VP9_COMMON *const cm = &cpi->common;
233   const nmv_context *nmvc = &cm->fc.nmvc;
234   MACROBLOCK *const x = &cpi->mb;
235   MACROBLOCKD *const xd = &x->e_mbd;
236   const struct segmentation *const seg = &cm->seg;
237   const MB_MODE_INFO *const mi = &m->mbmi;
238   const MV_REFERENCE_FRAME ref0 = mi->ref_frame[0];
239   const MV_REFERENCE_FRAME ref1 = mi->ref_frame[1];
240   const MB_PREDICTION_MODE mode = mi->mode;
241   const int segment_id = mi->segment_id;
242   const BLOCK_SIZE bsize = mi->sb_type;
243   const int allow_hp = cm->allow_high_precision_mv;
244   int skip;
245
246 #ifdef ENTROPY_STATS
247   active_section = 9;
248 #endif
249
250   if (seg->update_map) {
251     if (seg->temporal_update) {
252       const int pred_flag = mi->seg_id_predicted;
253       vp9_prob pred_prob = vp9_get_pred_prob_seg_id(seg, xd);
254       vp9_write(bc, pred_flag, pred_prob);
255       if (!pred_flag)
256         write_segment_id(bc, seg, segment_id);
257     } else {
258       write_segment_id(bc, seg, segment_id);
259     }
260   }
261
262   skip = write_skip(cpi, segment_id, m, bc);
263
264   if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
265     vp9_write(bc, ref0 != INTRA_FRAME, vp9_get_intra_inter_prob(cm, xd));
266
267   if (bsize >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT &&
268       !(ref0 != INTRA_FRAME &&
269         (skip || vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)))) {
270     write_selected_tx_size(cpi, mi->tx_size, bsize, bc);
271   }
272
273   if (ref0 == INTRA_FRAME) {
274 #ifdef ENTROPY_STATS
275     active_section = 6;
276 #endif
277
278     if (bsize >= BLOCK_8X8) {
279       write_intra_mode(bc, mode, cm->fc.y_mode_prob[size_group_lookup[bsize]]);
280     } else {
281       int idx, idy;
282       const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
283       const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
284       for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
285         for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
286           const MB_PREDICTION_MODE bm = m->bmi[idy * 2 + idx].as_mode;
287           write_intra_mode(bc, bm, cm->fc.y_mode_prob[0]);
288         }
289       }
290     }
291     write_intra_mode(bc, mi->uv_mode, cm->fc.uv_mode_prob[mode]);
292   } else {
293     vp9_prob *mv_ref_p;
294     write_ref_frames(cpi, bc);
295     mv_ref_p = cm->fc.inter_mode_probs[mi->mode_context[ref0]];
296
297 #ifdef ENTROPY_STATS
298     active_section = 3;
299 #endif
300
301     // If segment skip is not enabled code the mode.
302     if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)) {
303       if (bsize >= BLOCK_8X8) {
304         write_inter_mode(bc, mode, mv_ref_p);
305         ++cm->counts.inter_mode[mi->mode_context[ref0]][INTER_OFFSET(mode)];
306       }
307     }
308
309     if (cm->interp_filter == SWITCHABLE) {
310       const int ctx = vp9_get_pred_context_switchable_interp(xd);
311       vp9_write_token(bc, vp9_switchable_interp_tree,
312                       cm->fc.switchable_interp_prob[ctx],
313                       &switchable_interp_encodings[mi->interp_filter]);
314     } else {
315       assert(mi->interp_filter == cm->interp_filter);
316     }
317
318     if (bsize < BLOCK_8X8) {
319       const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
320       const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
321       int idx, idy;
322       for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
323         for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
324           const int j = idy * 2 + idx;
325           const MB_PREDICTION_MODE b_mode = m->bmi[j].as_mode;
326           write_inter_mode(bc, b_mode, mv_ref_p);
327           ++cm->counts.inter_mode[mi->mode_context[ref0]][INTER_OFFSET(b_mode)];
328           if (b_mode == NEWMV) {
329 #ifdef ENTROPY_STATS
330             active_section = 11;
331 #endif
332             vp9_encode_mv(cpi, bc, &m->bmi[j].as_mv[0].as_mv,
333                           &mi->ref_mvs[ref0][0].as_mv, nmvc, allow_hp);
334
335             if (has_second_ref(mi))
336               vp9_encode_mv(cpi, bc, &m->bmi[j].as_mv[1].as_mv,
337                             &mi->ref_mvs[ref1][0].as_mv, nmvc, allow_hp);
338           }
339         }
340       }
341     } else if (mode == NEWMV) {
342 #ifdef ENTROPY_STATS
343       active_section = 5;
344 #endif
345       vp9_encode_mv(cpi, bc, &mi->mv[0].as_mv,
346                     &mi->ref_mvs[ref0][0].as_mv, nmvc, allow_hp);
347
348       if (has_second_ref(mi))
349         vp9_encode_mv(cpi, bc, &mi->mv[1].as_mv,
350                       &mi->ref_mvs[ref1][0].as_mv, nmvc, allow_hp);
351     }
352   }
353 }
354
355 static void write_mb_modes_kf(const VP9_COMP *cpi, MODE_INFO **mi_8x8,
356                               vp9_writer *bc) {
357   const VP9_COMMON *const cm = &cpi->common;
358   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
359   const struct segmentation *const seg = &cm->seg;
360   MODE_INFO *m = mi_8x8[0];
361   const int ym = m->mbmi.mode;
362   const int segment_id = m->mbmi.segment_id;
363   MODE_INFO *above_mi = mi_8x8[-xd->mode_info_stride];
364   MODE_INFO *left_mi = xd->left_available ? mi_8x8[-1] : NULL;
365
366   if (seg->update_map)
367     write_segment_id(bc, seg, m->mbmi.segment_id);
368
369   write_skip(cpi, segment_id, m, bc);
370
371   if (m->mbmi.sb_type >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT)
372     write_selected_tx_size(cpi, m->mbmi.tx_size, m->mbmi.sb_type, bc);
373
374   if (m->mbmi.sb_type >= BLOCK_8X8) {
375     const MB_PREDICTION_MODE A = vp9_above_block_mode(m, above_mi, 0);
376     const MB_PREDICTION_MODE L = vp9_left_block_mode(m, left_mi, 0);
377     write_intra_mode(bc, ym, vp9_kf_y_mode_prob[A][L]);
378   } else {
379     int idx, idy;
380     const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[m->mbmi.sb_type];
381     const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[m->mbmi.sb_type];
382     for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
383       for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
384         int i = idy * 2 + idx;
385         const MB_PREDICTION_MODE A = vp9_above_block_mode(m, above_mi, i);
386         const MB_PREDICTION_MODE L = vp9_left_block_mode(m, left_mi, i);
387         const int bm = m->bmi[i].as_mode;
388         write_intra_mode(bc, bm, vp9_kf_y_mode_prob[A][L]);
389       }
390     }
391   }
392
393   write_intra_mode(bc, m->mbmi.uv_mode, vp9_kf_uv_mode_prob[ym]);
394 }
395
396 static void write_modes_b(VP9_COMP *cpi, const TileInfo *const tile,
397                           vp9_writer *w, TOKENEXTRA **tok, TOKENEXTRA *tok_end,
398                           int mi_row, int mi_col) {
399   VP9_COMMON *const cm = &cpi->common;
400   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
401   MODE_INFO *m;
402
403   xd->mi_8x8 = cm->mi_grid_visible + (mi_row * cm->mode_info_stride + mi_col);
404   m = xd->mi_8x8[0];
405
406   set_mi_row_col(xd, tile,
407                  mi_row, num_8x8_blocks_high_lookup[m->mbmi.sb_type],
408                  mi_col, num_8x8_blocks_wide_lookup[m->mbmi.sb_type],
409                  cm->mi_rows, cm->mi_cols);
410   if (frame_is_intra_only(cm)) {
411     write_mb_modes_kf(cpi, xd->mi_8x8, w);
412 #ifdef ENTROPY_STATS
413     active_section = 8;
414 #endif
415   } else {
416     pack_inter_mode_mvs(cpi, m, w);
417 #ifdef ENTROPY_STATS
418     active_section = 1;
419 #endif
420   }
421
422   assert(*tok < tok_end);
423   pack_mb_tokens(w, tok, tok_end);
424 }
425
426 static void write_partition(VP9_COMP *cpi, int hbs, int mi_row, int mi_col,
427                             PARTITION_TYPE p, BLOCK_SIZE bsize, vp9_writer *w) {
428   VP9_COMMON *const cm = &cpi->common;
429   const int ctx = partition_plane_context(cpi->above_seg_context,
430                                           cpi->left_seg_context,
431                                           mi_row, mi_col, bsize);
432   const vp9_prob *const probs = get_partition_probs(cm, ctx);
433   const int has_rows = (mi_row + hbs) < cm->mi_rows;
434   const int has_cols = (mi_col + hbs) < cm->mi_cols;
435
436   if (has_rows && has_cols) {
437     vp9_write_token(w, vp9_partition_tree, probs, &partition_encodings[p]);
438   } else if (!has_rows && has_cols) {
439     assert(p == PARTITION_SPLIT || p == PARTITION_HORZ);
440     vp9_write(w, p == PARTITION_SPLIT, probs[1]);
441   } else if (has_rows && !has_cols) {
442     assert(p == PARTITION_SPLIT || p == PARTITION_VERT);
443     vp9_write(w, p == PARTITION_SPLIT, probs[2]);
444   } else {
445     assert(p == PARTITION_SPLIT);
446   }
447 }
448
449 static void write_modes_sb(VP9_COMP *cpi, const TileInfo *const tile,
450                            vp9_writer *w, TOKENEXTRA **tok, TOKENEXTRA *tok_end,
451                            int mi_row, int mi_col, BLOCK_SIZE bsize) {
452   VP9_COMMON *const cm = &cpi->common;
453   const int bsl = b_width_log2(bsize);
454   const int bs = (1 << bsl) / 4;
455   PARTITION_TYPE partition;
456   BLOCK_SIZE subsize;
457   MODE_INFO *m = cm->mi_grid_visible[mi_row * cm->mode_info_stride + mi_col];
458
459   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
460     return;
461
462   partition = partition_lookup[bsl][m->mbmi.sb_type];
463   write_partition(cpi, bs, mi_row, mi_col, partition, bsize, w);
464   subsize = get_subsize(bsize, partition);
465   if (subsize < BLOCK_8X8) {
466     write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
467   } else {
468     switch (partition) {
469       case PARTITION_NONE:
470         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
471         break;
472       case PARTITION_HORZ:
473         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
474         if (mi_row + bs < cm->mi_rows)
475           write_modes_b(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col);
476         break;
477       case PARTITION_VERT:
478         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
479         if (mi_col + bs < cm->mi_cols)
480           write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col + bs);
481         break;
482       case PARTITION_SPLIT:
483         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col, subsize);
484         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col + bs,
485                        subsize);
486         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col,
487                        subsize);
488         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col + bs,
489                        subsize);
490         break;
491       default:
492         assert(0);
493     }
494   }
495
496   // update partition context
497   if (bsize >= BLOCK_8X8 &&
498       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
499     update_partition_context(cpi->above_seg_context, cpi->left_seg_context,
500                              mi_row, mi_col, subsize, bsize);
501 }
502
503 static void write_modes(VP9_COMP *cpi, const TileInfo *const tile,
504                         vp9_writer *w, TOKENEXTRA **tok, TOKENEXTRA *tok_end) {
505   int mi_row, mi_col;
506
507   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
508        mi_row += MI_BLOCK_SIZE) {
509       vp9_zero(cpi->left_seg_context);
510     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
511          mi_col += MI_BLOCK_SIZE)
512       write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col, BLOCK_64X64);
513   }
514 }
515
516 static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE tx_size) {
517   vp9_coeff_probs_model *coef_probs = cpi->frame_coef_probs[tx_size];
518   vp9_coeff_count *coef_counts = cpi->coef_counts[tx_size];
519   unsigned int (*eob_branch_ct)[REF_TYPES][COEF_BANDS][COEFF_CONTEXTS] =
520       cpi->common.counts.eob_branch[tx_size];
521   vp9_coeff_stats *coef_branch_ct = cpi->frame_branch_ct[tx_size];
522   int i, j, k, l, m;
523
524   for (i = 0; i < PLANE_TYPES; ++i) {
525     for (j = 0; j < REF_TYPES; ++j) {
526       for (k = 0; k < COEF_BANDS; ++k) {
527         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
528           vp9_tree_probs_from_distribution(vp9_coef_tree,
529                                            coef_branch_ct[i][j][k][l],
530                                            coef_counts[i][j][k][l]);
531           coef_branch_ct[i][j][k][l][0][1] = eob_branch_ct[i][j][k][l] -
532                                              coef_branch_ct[i][j][k][l][0][0];
533           for (m = 0; m < UNCONSTRAINED_NODES; ++m)
534             coef_probs[i][j][k][l][m] = get_binary_prob(
535                                             coef_branch_ct[i][j][k][l][m][0],
536                                             coef_branch_ct[i][j][k][l][m][1]);
537         }
538       }
539     }
540   }
541 }
542
543 static void update_coef_probs_common(vp9_writer* const bc, VP9_COMP *cpi,
544                                      TX_SIZE tx_size) {
545   vp9_coeff_probs_model *new_frame_coef_probs = cpi->frame_coef_probs[tx_size];
546   vp9_coeff_probs_model *old_frame_coef_probs =
547       cpi->common.fc.coef_probs[tx_size];
548   vp9_coeff_stats *frame_branch_ct = cpi->frame_branch_ct[tx_size];
549   const vp9_prob upd = DIFF_UPDATE_PROB;
550   const int entropy_nodes_update = UNCONSTRAINED_NODES;
551   int i, j, k, l, t;
552   switch (cpi->sf.use_fast_coef_updates) {
553     case 0: {
554       /* dry run to see if there is any udpate at all needed */
555       int savings = 0;
556       int update[2] = {0, 0};
557       for (i = 0; i < PLANE_TYPES; ++i) {
558         for (j = 0; j < REF_TYPES; ++j) {
559           for (k = 0; k < COEF_BANDS; ++k) {
560             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
561               for (t = 0; t < entropy_nodes_update; ++t) {
562                 vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
563                 const vp9_prob oldp = old_frame_coef_probs[i][j][k][l][t];
564                 int s;
565                 int u = 0;
566                 if (t == PIVOT_NODE)
567                   s = vp9_prob_diff_update_savings_search_model(
568                       frame_branch_ct[i][j][k][l][0],
569                       old_frame_coef_probs[i][j][k][l], &newp, upd);
570                 else
571                   s = vp9_prob_diff_update_savings_search(
572                       frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
573                 if (s > 0 && newp != oldp)
574                   u = 1;
575                 if (u)
576                   savings += s - (int)(vp9_cost_zero(upd));
577                 else
578                   savings -= (int)(vp9_cost_zero(upd));
579                 update[u]++;
580               }
581             }
582           }
583         }
584       }
585
586       // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
587       /* Is coef updated at all */
588       if (update[1] == 0 || savings < 0) {
589         vp9_write_bit(bc, 0);
590         return;
591       }
592       vp9_write_bit(bc, 1);
593       for (i = 0; i < PLANE_TYPES; ++i) {
594         for (j = 0; j < REF_TYPES; ++j) {
595           for (k = 0; k < COEF_BANDS; ++k) {
596             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
597               // calc probs and branch cts for this frame only
598               for (t = 0; t < entropy_nodes_update; ++t) {
599                 vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
600                 vp9_prob *oldp = old_frame_coef_probs[i][j][k][l] + t;
601                 const vp9_prob upd = DIFF_UPDATE_PROB;
602                 int s;
603                 int u = 0;
604                 if (t == PIVOT_NODE)
605                   s = vp9_prob_diff_update_savings_search_model(
606                       frame_branch_ct[i][j][k][l][0],
607                       old_frame_coef_probs[i][j][k][l], &newp, upd);
608                 else
609                   s = vp9_prob_diff_update_savings_search(
610                       frame_branch_ct[i][j][k][l][t],
611                       *oldp, &newp, upd);
612                 if (s > 0 && newp != *oldp)
613                   u = 1;
614                 vp9_write(bc, u, upd);
615                 if (u) {
616                   /* send/use new probability */
617                   vp9_write_prob_diff_update(bc, newp, *oldp);
618                   *oldp = newp;
619                 }
620               }
621             }
622           }
623         }
624       }
625       return;
626     }
627
628     case 1:
629     case 2: {
630       const int prev_coef_contexts_to_update =
631           cpi->sf.use_fast_coef_updates == 2 ? COEFF_CONTEXTS >> 1
632                                              : COEFF_CONTEXTS;
633       const int coef_band_to_update =
634           cpi->sf.use_fast_coef_updates == 2 ? COEF_BANDS >> 1
635                                              : COEF_BANDS;
636       int updates = 0;
637       int noupdates_before_first = 0;
638       for (i = 0; i < PLANE_TYPES; ++i) {
639         for (j = 0; j < REF_TYPES; ++j) {
640           for (k = 0; k < COEF_BANDS; ++k) {
641             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
642               // calc probs and branch cts for this frame only
643               for (t = 0; t < entropy_nodes_update; ++t) {
644                 vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
645                 vp9_prob *oldp = old_frame_coef_probs[i][j][k][l] + t;
646                 int s;
647                 int u = 0;
648                 if (l >= prev_coef_contexts_to_update ||
649                     k >= coef_band_to_update) {
650                   u = 0;
651                 } else {
652                   if (t == PIVOT_NODE)
653                     s = vp9_prob_diff_update_savings_search_model(
654                         frame_branch_ct[i][j][k][l][0],
655                         old_frame_coef_probs[i][j][k][l], &newp, upd);
656                   else
657                     s = vp9_prob_diff_update_savings_search(
658                         frame_branch_ct[i][j][k][l][t],
659                         *oldp, &newp, upd);
660                   if (s > 0 && newp != *oldp)
661                     u = 1;
662                 }
663                 updates += u;
664                 if (u == 0 && updates == 0) {
665                   noupdates_before_first++;
666                   continue;
667                 }
668                 if (u == 1 && updates == 1) {
669                   int v;
670                   // first update
671                   vp9_write_bit(bc, 1);
672                   for (v = 0; v < noupdates_before_first; ++v)
673                     vp9_write(bc, 0, upd);
674                 }
675                 vp9_write(bc, u, upd);
676                 if (u) {
677                   /* send/use new probability */
678                   vp9_write_prob_diff_update(bc, newp, *oldp);
679                   *oldp = newp;
680                 }
681               }
682             }
683           }
684         }
685       }
686       if (updates == 0) {
687         vp9_write_bit(bc, 0);  // no updates
688       }
689       return;
690     }
691
692     default:
693       assert(0);
694   }
695 }
696
697 static void update_coef_probs(VP9_COMP *cpi, vp9_writer* w) {
698   const TX_MODE tx_mode = cpi->common.tx_mode;
699   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
700   TX_SIZE tx_size;
701   vp9_clear_system_state();
702
703   for (tx_size = TX_4X4; tx_size <= TX_32X32; ++tx_size)
704     build_tree_distribution(cpi, tx_size);
705
706   for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
707     update_coef_probs_common(w, cpi, tx_size);
708 }
709
710 static void encode_loopfilter(struct loopfilter *lf,
711                               struct vp9_write_bit_buffer *wb) {
712   int i;
713
714   // Encode the loop filter level and type
715   vp9_wb_write_literal(wb, lf->filter_level, 6);
716   vp9_wb_write_literal(wb, lf->sharpness_level, 3);
717
718   // Write out loop filter deltas applied at the MB level based on mode or
719   // ref frame (if they are enabled).
720   vp9_wb_write_bit(wb, lf->mode_ref_delta_enabled);
721
722   if (lf->mode_ref_delta_enabled) {
723     vp9_wb_write_bit(wb, lf->mode_ref_delta_update);
724     if (lf->mode_ref_delta_update) {
725       for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
726         const int delta = lf->ref_deltas[i];
727         const int changed = delta != lf->last_ref_deltas[i];
728         vp9_wb_write_bit(wb, changed);
729         if (changed) {
730           lf->last_ref_deltas[i] = delta;
731           vp9_wb_write_literal(wb, abs(delta) & 0x3F, 6);
732           vp9_wb_write_bit(wb, delta < 0);
733         }
734       }
735
736       for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
737         const int delta = lf->mode_deltas[i];
738         const int changed = delta != lf->last_mode_deltas[i];
739         vp9_wb_write_bit(wb, changed);
740         if (changed) {
741           lf->last_mode_deltas[i] = delta;
742           vp9_wb_write_literal(wb, abs(delta) & 0x3F, 6);
743           vp9_wb_write_bit(wb, delta < 0);
744         }
745       }
746     }
747   }
748 }
749
750 static void write_delta_q(struct vp9_write_bit_buffer *wb, int delta_q) {
751   if (delta_q != 0) {
752     vp9_wb_write_bit(wb, 1);
753     vp9_wb_write_literal(wb, abs(delta_q), 4);
754     vp9_wb_write_bit(wb, delta_q < 0);
755   } else {
756     vp9_wb_write_bit(wb, 0);
757   }
758 }
759
760 static void encode_quantization(VP9_COMMON *cm,
761                                 struct vp9_write_bit_buffer *wb) {
762   vp9_wb_write_literal(wb, cm->base_qindex, QINDEX_BITS);
763   write_delta_q(wb, cm->y_dc_delta_q);
764   write_delta_q(wb, cm->uv_dc_delta_q);
765   write_delta_q(wb, cm->uv_ac_delta_q);
766 }
767
768
769 static void encode_segmentation(VP9_COMP *cpi,
770                                 struct vp9_write_bit_buffer *wb) {
771   int i, j;
772
773   struct segmentation *seg = &cpi->common.seg;
774
775   vp9_wb_write_bit(wb, seg->enabled);
776   if (!seg->enabled)
777     return;
778
779   // Segmentation map
780   vp9_wb_write_bit(wb, seg->update_map);
781   if (seg->update_map) {
782     // Select the coding strategy (temporal or spatial)
783     vp9_choose_segmap_coding_method(cpi);
784     // Write out probabilities used to decode unpredicted  macro-block segments
785     for (i = 0; i < SEG_TREE_PROBS; i++) {
786       const int prob = seg->tree_probs[i];
787       const int update = prob != MAX_PROB;
788       vp9_wb_write_bit(wb, update);
789       if (update)
790         vp9_wb_write_literal(wb, prob, 8);
791     }
792
793     // Write out the chosen coding method.
794     vp9_wb_write_bit(wb, seg->temporal_update);
795     if (seg->temporal_update) {
796       for (i = 0; i < PREDICTION_PROBS; i++) {
797         const int prob = seg->pred_probs[i];
798         const int update = prob != MAX_PROB;
799         vp9_wb_write_bit(wb, update);
800         if (update)
801           vp9_wb_write_literal(wb, prob, 8);
802       }
803     }
804   }
805
806   // Segmentation data
807   vp9_wb_write_bit(wb, seg->update_data);
808   if (seg->update_data) {
809     vp9_wb_write_bit(wb, seg->abs_delta);
810
811     for (i = 0; i < MAX_SEGMENTS; i++) {
812       for (j = 0; j < SEG_LVL_MAX; j++) {
813         const int active = vp9_segfeature_active(seg, i, j);
814         vp9_wb_write_bit(wb, active);
815         if (active) {
816           const int data = vp9_get_segdata(seg, i, j);
817           const int data_max = vp9_seg_feature_data_max(j);
818
819           if (vp9_is_segfeature_signed(j)) {
820             encode_unsigned_max(wb, abs(data), data_max);
821             vp9_wb_write_bit(wb, data < 0);
822           } else {
823             encode_unsigned_max(wb, data, data_max);
824           }
825         }
826       }
827     }
828   }
829 }
830
831
832 static void encode_txfm_probs(VP9_COMMON *cm, vp9_writer *w) {
833   // Mode
834   vp9_write_literal(w, MIN(cm->tx_mode, ALLOW_32X32), 2);
835   if (cm->tx_mode >= ALLOW_32X32)
836     vp9_write_bit(w, cm->tx_mode == TX_MODE_SELECT);
837
838   // Probabilities
839   if (cm->tx_mode == TX_MODE_SELECT) {
840     int i, j;
841     unsigned int ct_8x8p[TX_SIZES - 3][2];
842     unsigned int ct_16x16p[TX_SIZES - 2][2];
843     unsigned int ct_32x32p[TX_SIZES - 1][2];
844
845
846     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
847       tx_counts_to_branch_counts_8x8(cm->counts.tx.p8x8[i], ct_8x8p);
848       for (j = 0; j < TX_SIZES - 3; j++)
849         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p8x8[i][j], ct_8x8p[j]);
850     }
851
852     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
853       tx_counts_to_branch_counts_16x16(cm->counts.tx.p16x16[i], ct_16x16p);
854       for (j = 0; j < TX_SIZES - 2; j++)
855         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p16x16[i][j],
856                                   ct_16x16p[j]);
857     }
858
859     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
860       tx_counts_to_branch_counts_32x32(cm->counts.tx.p32x32[i], ct_32x32p);
861       for (j = 0; j < TX_SIZES - 1; j++)
862         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p32x32[i][j],
863                                   ct_32x32p[j]);
864     }
865   }
866 }
867
868 static void write_interp_filter(INTERP_FILTER filter,
869                                 struct vp9_write_bit_buffer *wb) {
870   const int filter_to_literal[] = { 1, 0, 2, 3 };
871
872   vp9_wb_write_bit(wb, filter == SWITCHABLE);
873   if (filter != SWITCHABLE)
874     vp9_wb_write_literal(wb, filter_to_literal[filter], 2);
875 }
876
877 static void fix_interp_filter(VP9_COMMON *cm) {
878   if (cm->interp_filter == SWITCHABLE) {
879     // Check to see if only one of the filters is actually used
880     int count[SWITCHABLE_FILTERS];
881     int i, j, c = 0;
882     for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
883       count[i] = 0;
884       for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
885         count[i] += cm->counts.switchable_interp[j][i];
886       c += (count[i] > 0);
887     }
888     if (c == 1) {
889       // Only one filter is used. So set the filter at frame level
890       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
891         if (count[i]) {
892           cm->interp_filter = i;
893           break;
894         }
895       }
896     }
897   }
898 }
899
900 static void write_tile_info(VP9_COMMON *cm, struct vp9_write_bit_buffer *wb) {
901   int min_log2_tile_cols, max_log2_tile_cols, ones;
902   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
903
904   // columns
905   ones = cm->log2_tile_cols - min_log2_tile_cols;
906   while (ones--)
907     vp9_wb_write_bit(wb, 1);
908
909   if (cm->log2_tile_cols < max_log2_tile_cols)
910     vp9_wb_write_bit(wb, 0);
911
912   // rows
913   vp9_wb_write_bit(wb, cm->log2_tile_rows != 0);
914   if (cm->log2_tile_rows != 0)
915     vp9_wb_write_bit(wb, cm->log2_tile_rows != 1);
916 }
917
918 static int get_refresh_mask(VP9_COMP *cpi) {
919     // Should the GF or ARF be updated using the transmitted frame or buffer
920 #if CONFIG_MULTIPLE_ARF
921     if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
922         !cpi->refresh_alt_ref_frame) {
923 #else
924     if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
925         !cpi->use_svc) {
926 #endif
927       // Preserve the previously existing golden frame and update the frame in
928       // the alt ref slot instead. This is highly specific to the use of
929       // alt-ref as a forward reference, and this needs to be generalized as
930       // other uses are implemented (like RTC/temporal scaling)
931       //
932       // gld_fb_idx and alt_fb_idx need to be swapped for future frames, but
933       // that happens in vp9_onyx_if.c:update_reference_frames() so that it can
934       // be done outside of the recode loop.
935       return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
936              (cpi->refresh_golden_frame << cpi->alt_fb_idx);
937     } else {
938       int arf_idx = cpi->alt_fb_idx;
939 #if CONFIG_MULTIPLE_ARF
940       // Determine which ARF buffer to use to encode this ARF frame.
941       if (cpi->multi_arf_enabled) {
942         int sn = cpi->sequence_number;
943         arf_idx = (cpi->frame_coding_order[sn] < 0) ?
944             cpi->arf_buffer_idx[sn + 1] :
945             cpi->arf_buffer_idx[sn];
946       }
947 #endif
948       return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
949              (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
950              (cpi->refresh_alt_ref_frame << arf_idx);
951     }
952 }
953
954 static size_t encode_tiles(VP9_COMP *cpi, uint8_t *data_ptr) {
955   VP9_COMMON *const cm = &cpi->common;
956   vp9_writer residual_bc;
957
958   int tile_row, tile_col;
959   TOKENEXTRA *tok[4][1 << 6], *tok_end;
960   size_t total_size = 0;
961   const int tile_cols = 1 << cm->log2_tile_cols;
962   const int tile_rows = 1 << cm->log2_tile_rows;
963
964   vpx_memset(cpi->above_seg_context, 0, sizeof(*cpi->above_seg_context) *
965              mi_cols_aligned_to_sb(cm->mi_cols));
966
967   tok[0][0] = cpi->tok;
968   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
969     if (tile_row)
970       tok[tile_row][0] = tok[tile_row - 1][tile_cols - 1] +
971                          cpi->tok_count[tile_row - 1][tile_cols - 1];
972
973     for (tile_col = 1; tile_col < tile_cols; tile_col++)
974       tok[tile_row][tile_col] = tok[tile_row][tile_col - 1] +
975                                 cpi->tok_count[tile_row][tile_col - 1];
976   }
977
978   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
979     for (tile_col = 0; tile_col < tile_cols; tile_col++) {
980       TileInfo tile;
981
982       vp9_tile_init(&tile, cm, tile_row, tile_col);
983       tok_end = tok[tile_row][tile_col] + cpi->tok_count[tile_row][tile_col];
984
985       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1)
986         vp9_start_encode(&residual_bc, data_ptr + total_size + 4);
987       else
988         vp9_start_encode(&residual_bc, data_ptr + total_size);
989
990       write_modes(cpi, &tile, &residual_bc, &tok[tile_row][tile_col], tok_end);
991       assert(tok[tile_row][tile_col] == tok_end);
992       vp9_stop_encode(&residual_bc);
993       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1) {
994         // size of this tile
995         mem_put_be32(data_ptr + total_size, residual_bc.pos);
996         total_size += 4;
997       }
998
999       total_size += residual_bc.pos;
1000     }
1001   }
1002
1003   return total_size;
1004 }
1005
1006 static void write_display_size(const VP9_COMMON *cm,
1007                                struct vp9_write_bit_buffer *wb) {
1008   const int scaling_active = cm->width != cm->display_width ||
1009                              cm->height != cm->display_height;
1010   vp9_wb_write_bit(wb, scaling_active);
1011   if (scaling_active) {
1012     vp9_wb_write_literal(wb, cm->display_width - 1, 16);
1013     vp9_wb_write_literal(wb, cm->display_height - 1, 16);
1014   }
1015 }
1016
1017 static void write_frame_size(const VP9_COMMON *cm,
1018                              struct vp9_write_bit_buffer *wb) {
1019   vp9_wb_write_literal(wb, cm->width - 1, 16);
1020   vp9_wb_write_literal(wb, cm->height - 1, 16);
1021
1022   write_display_size(cm, wb);
1023 }
1024
1025 static void write_frame_size_with_refs(VP9_COMP *cpi,
1026                                        struct vp9_write_bit_buffer *wb) {
1027   VP9_COMMON *const cm = &cpi->common;
1028   int found = 0;
1029
1030   MV_REFERENCE_FRAME ref_frame;
1031   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1032     YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, ref_frame);
1033     found = cm->width == cfg->y_crop_width &&
1034             cm->height == cfg->y_crop_height;
1035
1036     // TODO(ivan): This prevents a bug while more than 3 buffers are used. Do it
1037     // in a better way.
1038     if (cpi->use_svc) {
1039       found = 0;
1040     }
1041     vp9_wb_write_bit(wb, found);
1042     if (found) {
1043       break;
1044     }
1045   }
1046
1047   if (!found) {
1048     vp9_wb_write_literal(wb, cm->width - 1, 16);
1049     vp9_wb_write_literal(wb, cm->height - 1, 16);
1050   }
1051
1052   write_display_size(cm, wb);
1053 }
1054
1055 static void write_sync_code(struct vp9_write_bit_buffer *wb) {
1056   vp9_wb_write_literal(wb, VP9_SYNC_CODE_0, 8);
1057   vp9_wb_write_literal(wb, VP9_SYNC_CODE_1, 8);
1058   vp9_wb_write_literal(wb, VP9_SYNC_CODE_2, 8);
1059 }
1060
1061 static void write_uncompressed_header(VP9_COMP *cpi,
1062                                       struct vp9_write_bit_buffer *wb) {
1063   VP9_COMMON *const cm = &cpi->common;
1064
1065   vp9_wb_write_literal(wb, VP9_FRAME_MARKER, 2);
1066
1067   // bitstream version.
1068   // 00 - profile 0. 4:2:0 only
1069   // 10 - profile 1. adds 4:4:4, 4:2:2, alpha
1070   vp9_wb_write_bit(wb, cm->version);
1071   vp9_wb_write_bit(wb, 0);
1072
1073   vp9_wb_write_bit(wb, 0);
1074   vp9_wb_write_bit(wb, cm->frame_type);
1075   vp9_wb_write_bit(wb, cm->show_frame);
1076   vp9_wb_write_bit(wb, cm->error_resilient_mode);
1077
1078   if (cm->frame_type == KEY_FRAME) {
1079     const COLOR_SPACE cs = UNKNOWN;
1080     write_sync_code(wb);
1081     vp9_wb_write_literal(wb, cs, 3);
1082     if (cs != SRGB) {
1083       vp9_wb_write_bit(wb, 0);  // 0: [16, 235] (i.e. xvYCC), 1: [0, 255]
1084       if (cm->version == 1) {
1085         vp9_wb_write_bit(wb, cm->subsampling_x);
1086         vp9_wb_write_bit(wb, cm->subsampling_y);
1087         vp9_wb_write_bit(wb, 0);  // has extra plane
1088       }
1089     } else {
1090       assert(cm->version == 1);
1091       vp9_wb_write_bit(wb, 0);  // has extra plane
1092     }
1093
1094     write_frame_size(cm, wb);
1095   } else {
1096     if (!cm->show_frame)
1097       vp9_wb_write_bit(wb, cm->intra_only);
1098
1099     if (!cm->error_resilient_mode)
1100       vp9_wb_write_literal(wb, cm->reset_frame_context, 2);
1101
1102     if (cm->intra_only) {
1103       write_sync_code(wb);
1104
1105       vp9_wb_write_literal(wb, get_refresh_mask(cpi), REF_FRAMES);
1106       write_frame_size(cm, wb);
1107     } else {
1108       MV_REFERENCE_FRAME ref_frame;
1109       vp9_wb_write_literal(wb, get_refresh_mask(cpi), REF_FRAMES);
1110       for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1111         vp9_wb_write_literal(wb, get_ref_frame_idx(cpi, ref_frame),
1112                              REF_FRAMES_LOG2);
1113         vp9_wb_write_bit(wb, cm->ref_frame_sign_bias[ref_frame]);
1114       }
1115
1116       write_frame_size_with_refs(cpi, wb);
1117
1118       vp9_wb_write_bit(wb, cm->allow_high_precision_mv);
1119
1120       fix_interp_filter(cm);
1121       write_interp_filter(cm->interp_filter, wb);
1122     }
1123   }
1124
1125   if (!cm->error_resilient_mode) {
1126     vp9_wb_write_bit(wb, cm->refresh_frame_context);
1127     vp9_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
1128   }
1129
1130   vp9_wb_write_literal(wb, cm->frame_context_idx, FRAME_CONTEXTS_LOG2);
1131
1132   encode_loopfilter(&cm->lf, wb);
1133   encode_quantization(cm, wb);
1134   encode_segmentation(cpi, wb);
1135
1136   write_tile_info(cm, wb);
1137 }
1138
1139 static size_t write_compressed_header(VP9_COMP *cpi, uint8_t *data) {
1140   VP9_COMMON *const cm = &cpi->common;
1141   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1142   FRAME_CONTEXT *const fc = &cm->fc;
1143   vp9_writer header_bc;
1144
1145   vp9_start_encode(&header_bc, data);
1146
1147   if (xd->lossless)
1148     cm->tx_mode = ONLY_4X4;
1149   else
1150     encode_txfm_probs(cm, &header_bc);
1151
1152   update_coef_probs(cpi, &header_bc);
1153
1154 #ifdef ENTROPY_STATS
1155   active_section = 2;
1156 #endif
1157
1158   update_skip_probs(cm, &header_bc);
1159
1160   if (!frame_is_intra_only(cm)) {
1161     int i;
1162 #ifdef ENTROPY_STATS
1163     active_section = 1;
1164 #endif
1165
1166     for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
1167       prob_diff_update(vp9_inter_mode_tree, cm->fc.inter_mode_probs[i],
1168                        cm->counts.inter_mode[i], INTER_MODES, &header_bc);
1169
1170     vp9_zero(cm->counts.inter_mode);
1171
1172     if (cm->interp_filter == SWITCHABLE)
1173       update_switchable_interp_probs(cm, &header_bc);
1174
1175     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1176       vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i],
1177                                 cm->counts.intra_inter[i]);
1178
1179     if (cm->allow_comp_inter_inter) {
1180       const int use_compound_pred = cm->reference_mode != SINGLE_REFERENCE;
1181       const int use_hybrid_pred = cm->reference_mode == REFERENCE_MODE_SELECT;
1182
1183       vp9_write_bit(&header_bc, use_compound_pred);
1184       if (use_compound_pred) {
1185         vp9_write_bit(&header_bc, use_hybrid_pred);
1186         if (use_hybrid_pred)
1187           for (i = 0; i < COMP_INTER_CONTEXTS; i++)
1188             vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i],
1189                                       cm->counts.comp_inter[i]);
1190       }
1191     }
1192
1193     if (cm->reference_mode != COMPOUND_REFERENCE) {
1194       for (i = 0; i < REF_CONTEXTS; i++) {
1195         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0],
1196                                   cm->counts.single_ref[i][0]);
1197         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1],
1198                                   cm->counts.single_ref[i][1]);
1199       }
1200     }
1201
1202     if (cm->reference_mode != SINGLE_REFERENCE)
1203       for (i = 0; i < REF_CONTEXTS; i++)
1204         vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i],
1205                                   cm->counts.comp_ref[i]);
1206
1207     for (i = 0; i < BLOCK_SIZE_GROUPS; ++i)
1208       prob_diff_update(vp9_intra_mode_tree, cm->fc.y_mode_prob[i],
1209                        cm->counts.y_mode[i], INTRA_MODES, &header_bc);
1210
1211     for (i = 0; i < PARTITION_CONTEXTS; ++i)
1212       prob_diff_update(vp9_partition_tree, fc->partition_prob[i],
1213                        cm->counts.partition[i], PARTITION_TYPES, &header_bc);
1214
1215     vp9_write_nmv_probs(cm, cm->allow_high_precision_mv, &header_bc);
1216   }
1217
1218   vp9_stop_encode(&header_bc);
1219   assert(header_bc.pos <= 0xffff);
1220
1221   return header_bc.pos;
1222 }
1223
1224 void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, size_t *size) {
1225   uint8_t *data = dest;
1226   size_t first_part_size;
1227   struct vp9_write_bit_buffer wb = {data, 0};
1228   struct vp9_write_bit_buffer saved_wb;
1229
1230   write_uncompressed_header(cpi, &wb);
1231   saved_wb = wb;
1232   vp9_wb_write_literal(&wb, 0, 16);  // don't know in advance first part. size
1233
1234   data += vp9_rb_bytes_written(&wb);
1235
1236   vp9_compute_update_table();
1237
1238 #ifdef ENTROPY_STATS
1239   if (cm->frame_type == INTER_FRAME)
1240     active_section = 0;
1241   else
1242     active_section = 7;
1243 #endif
1244
1245   vp9_clear_system_state();
1246
1247   first_part_size = write_compressed_header(cpi, data);
1248   data += first_part_size;
1249   // TODO(jbb): Figure out what to do if first_part_size > 16 bits.
1250   vp9_wb_write_literal(&saved_wb, (int)first_part_size, 16);
1251
1252   data += encode_tiles(cpi, data);
1253
1254   *size = data - dest;
1255 }
1256