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