Merge "configure: add --extra-cxxflags option"
[platform/upstream/libvpx.git] / 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_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 "vp9/common/vp9_entropy.h"
23 #include "vp9/common/vp9_entropymode.h"
24 #include "vp9/common/vp9_entropymv.h"
25 #include "vp9/common/vp9_mvref_common.h"
26 #include "vp9/common/vp9_pred_common.h"
27 #include "vp9/common/vp9_seg_common.h"
28 #include "vp9/common/vp9_tile_common.h"
29
30 #include "vp9/encoder/vp9_cost.h"
31 #include "vp9/encoder/vp9_bitstream.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_mcomp.h"
34 #include "vp9/encoder/vp9_segmentation.h"
35 #include "vp9/encoder/vp9_subexp.h"
36 #include "vp9/encoder/vp9_tokenize.h"
37
38 static const struct vp9_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 vp9_token switchable_interp_encodings[SWITCHABLE_FILTERS] =
42   {{0, 1}, {2, 2}, {3, 2}};
43 static const struct vp9_token partition_encodings[PARTITION_TYPES] =
44   {{0, 1}, {2, 2}, {6, 3}, {7, 3}};
45 static const struct vp9_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   vp9_write_token(w, vp9_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   vp9_write_token(w, vp9_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   vp9_tree_probs_from_distribution(tree, branch_ct, counts);
76   for (i = 0; i < n - 1; ++i)
77     vp9_cond_prob_diff_update(w, &probs[i], branch_ct[i]);
78 }
79
80 static void write_selected_tx_size(const VP9_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 VP9_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, vp9_get_skip_prob(cm, xd));
102     return skip;
103   }
104 }
105
106 static void update_skip_probs(VP9_COMMON *cm, vpx_writer *w,
107                               FRAME_COUNTS *counts) {
108   int k;
109
110   for (k = 0; k < SKIP_CONTEXTS; ++k)
111     vp9_cond_prob_diff_update(w, &cm->fc->skip_probs[k], counts->skip[k]);
112 }
113
114 static void update_switchable_interp_probs(VP9_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(vp9_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 vp9_token *const a = &vp9_coef_encodings[t];
131     int i = 0;
132     int v = a->value;
133     int n = a->len;
134 #if CONFIG_VP9_HIGHBITDEPTH
135     const vp9_extra_bit *b;
136     if (bit_depth == VPX_BITS_12)
137       b = &vp9_extra_bits_high12[t];
138     else if (bit_depth == VPX_BITS_10)
139       b = &vp9_extra_bits_high10[t];
140     else
141       b = &vp9_extra_bits[t];
142 #else
143     const vp9_extra_bit *const b = &vp9_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       vp9_write_tree(w, vp9_coef_tree, p->context_tree, bits, len, i);
165       vp9_write_tree(w, vp9_coef_con_tree,
166                      vp9_pareto8_full[p->context_tree[PIVOT_NODE] - 1],
167                      v, n - len, 0);
168     } else {
169       vp9_write_tree(w, vp9_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     vp9_write_tree(w, vp9_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 VP9_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, vp9_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                 vp9_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, vp9_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, vp9_get_pred_prob_single_ref_p2(cm, xd));
233       }
234     }
235   }
236 }
237
238 static void pack_inter_mode_mvs(VP9_COMP *cpi, const MODE_INFO *mi,
239                                 vpx_writer *w) {
240   VP9_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 = vp9_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, vp9_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 = vp9_get_pred_context_switchable_interp(xd);
306       vp9_write_token(w, vp9_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               vp9_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           vp9_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 VP9_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, vp9_kf_uv_mode_prob[mbmi->mode]);
376 }
377
378 static void write_modes_b(VP9_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 VP9_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->td.mb.mbmi_ext_base +
390       (mi_row * cm->mi_cols + mi_col);
391
392   set_mi_row_col(xd, tile,
393                  mi_row, num_8x8_blocks_high_lookup[m->mbmi.sb_type],
394                  mi_col, num_8x8_blocks_wide_lookup[m->mbmi.sb_type],
395                  cm->mi_rows, cm->mi_cols);
396   if (frame_is_intra_only(cm)) {
397     write_mb_modes_kf(cm, xd, xd->mi, w);
398   } else {
399     pack_inter_mode_mvs(cpi, m, w);
400   }
401
402   assert(*tok < tok_end);
403   pack_mb_tokens(w, tok, tok_end, cm->bit_depth);
404 }
405
406 static void write_partition(const VP9_COMMON *const cm,
407                             const MACROBLOCKD *const xd,
408                             int hbs, int mi_row, int mi_col,
409                             PARTITION_TYPE p, BLOCK_SIZE bsize, vpx_writer *w) {
410   const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
411   const vpx_prob *const probs = xd->partition_probs[ctx];
412   const int has_rows = (mi_row + hbs) < cm->mi_rows;
413   const int has_cols = (mi_col + hbs) < cm->mi_cols;
414
415   if (has_rows && has_cols) {
416     vp9_write_token(w, vp9_partition_tree, probs, &partition_encodings[p]);
417   } else if (!has_rows && has_cols) {
418     assert(p == PARTITION_SPLIT || p == PARTITION_HORZ);
419     vpx_write(w, p == PARTITION_SPLIT, probs[1]);
420   } else if (has_rows && !has_cols) {
421     assert(p == PARTITION_SPLIT || p == PARTITION_VERT);
422     vpx_write(w, p == PARTITION_SPLIT, probs[2]);
423   } else {
424     assert(p == PARTITION_SPLIT);
425   }
426 }
427
428 static void write_modes_sb(VP9_COMP *cpi,
429                            const TileInfo *const tile, vpx_writer *w,
430                            TOKENEXTRA **tok, const TOKENEXTRA *const tok_end,
431                            int mi_row, int mi_col, BLOCK_SIZE bsize) {
432   const VP9_COMMON *const cm = &cpi->common;
433   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
434
435   const int bsl = b_width_log2_lookup[bsize];
436   const int bs = (1 << bsl) / 4;
437   PARTITION_TYPE partition;
438   BLOCK_SIZE subsize;
439   const MODE_INFO *m = NULL;
440
441   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
442     return;
443
444   m = cm->mi_grid_visible[mi_row * cm->mi_stride + mi_col];
445
446   partition = partition_lookup[bsl][m->mbmi.sb_type];
447   write_partition(cm, xd, bs, mi_row, mi_col, partition, bsize, w);
448   subsize = get_subsize(bsize, partition);
449   if (subsize < BLOCK_8X8) {
450     write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
451   } else {
452     switch (partition) {
453       case PARTITION_NONE:
454         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
455         break;
456       case PARTITION_HORZ:
457         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
458         if (mi_row + bs < cm->mi_rows)
459           write_modes_b(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col);
460         break;
461       case PARTITION_VERT:
462         write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col);
463         if (mi_col + bs < cm->mi_cols)
464           write_modes_b(cpi, tile, w, tok, tok_end, mi_row, mi_col + bs);
465         break;
466       case PARTITION_SPLIT:
467         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col, subsize);
468         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col + bs,
469                        subsize);
470         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col,
471                        subsize);
472         write_modes_sb(cpi, tile, w, tok, tok_end, mi_row + bs, mi_col + bs,
473                        subsize);
474         break;
475       default:
476         assert(0);
477     }
478   }
479
480   // update partition context
481   if (bsize >= BLOCK_8X8 &&
482       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
483     update_partition_context(xd, mi_row, mi_col, subsize, bsize);
484 }
485
486 static void write_modes(VP9_COMP *cpi,
487                         const TileInfo *const tile, vpx_writer *w,
488                         TOKENEXTRA **tok, const TOKENEXTRA *const tok_end) {
489   const VP9_COMMON *const cm = &cpi->common;
490   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
491   int mi_row, mi_col;
492
493   set_partition_probs(cm, xd);
494
495   for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
496        mi_row += MI_BLOCK_SIZE) {
497     vp9_zero(xd->left_seg_context);
498     for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
499          mi_col += MI_BLOCK_SIZE)
500       write_modes_sb(cpi, tile, w, tok, tok_end, mi_row, mi_col,
501                      BLOCK_64X64);
502   }
503 }
504
505 static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE tx_size,
506                                     vp9_coeff_stats *coef_branch_ct,
507                                     vp9_coeff_probs_model *coef_probs) {
508   vp9_coeff_count *coef_counts = cpi->td.rd_counts.coef_counts[tx_size];
509   unsigned int (*eob_branch_ct)[REF_TYPES][COEF_BANDS][COEFF_CONTEXTS] =
510       cpi->common.counts.eob_branch[tx_size];
511   int i, j, k, l, m;
512
513   for (i = 0; i < PLANE_TYPES; ++i) {
514     for (j = 0; j < REF_TYPES; ++j) {
515       for (k = 0; k < COEF_BANDS; ++k) {
516         for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
517           vp9_tree_probs_from_distribution(vp9_coef_tree,
518                                            coef_branch_ct[i][j][k][l],
519                                            coef_counts[i][j][k][l]);
520           coef_branch_ct[i][j][k][l][0][1] = eob_branch_ct[i][j][k][l] -
521                                              coef_branch_ct[i][j][k][l][0][0];
522           for (m = 0; m < UNCONSTRAINED_NODES; ++m)
523             coef_probs[i][j][k][l][m] = get_binary_prob(
524                                             coef_branch_ct[i][j][k][l][m][0],
525                                             coef_branch_ct[i][j][k][l][m][1]);
526         }
527       }
528     }
529   }
530 }
531
532 static void update_coef_probs_common(vpx_writer* const bc, VP9_COMP *cpi,
533                                      TX_SIZE tx_size,
534                                      vp9_coeff_stats *frame_branch_ct,
535                                      vp9_coeff_probs_model *new_coef_probs) {
536   vp9_coeff_probs_model *old_coef_probs = cpi->common.fc->coef_probs[tx_size];
537   const vpx_prob upd = DIFF_UPDATE_PROB;
538   const int entropy_nodes_update = UNCONSTRAINED_NODES;
539   int i, j, k, l, t;
540   int stepsize = cpi->sf.coeff_prob_appx_step;
541
542   switch (cpi->sf.use_fast_coef_updates) {
543     case TWO_LOOP: {
544       /* dry run to see if there is any update at all needed */
545       int savings = 0;
546       int update[2] = {0, 0};
547       for (i = 0; i < PLANE_TYPES; ++i) {
548         for (j = 0; j < REF_TYPES; ++j) {
549           for (k = 0; k < COEF_BANDS; ++k) {
550             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
551               for (t = 0; t < entropy_nodes_update; ++t) {
552                 vpx_prob newp = new_coef_probs[i][j][k][l][t];
553                 const vpx_prob oldp = old_coef_probs[i][j][k][l][t];
554                 int s;
555                 int u = 0;
556                 if (t == PIVOT_NODE)
557                   s = vp9_prob_diff_update_savings_search_model(
558                       frame_branch_ct[i][j][k][l][0],
559                       old_coef_probs[i][j][k][l], &newp, upd, stepsize);
560                 else
561                   s = vp9_prob_diff_update_savings_search(
562                       frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
563                 if (s > 0 && newp != oldp)
564                   u = 1;
565                 if (u)
566                   savings += s - (int)(vp9_cost_zero(upd));
567                 else
568                   savings -= (int)(vp9_cost_zero(upd));
569                 update[u]++;
570               }
571             }
572           }
573         }
574       }
575
576       // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
577       /* Is coef updated at all */
578       if (update[1] == 0 || savings < 0) {
579         vpx_write_bit(bc, 0);
580         return;
581       }
582       vpx_write_bit(bc, 1);
583       for (i = 0; i < PLANE_TYPES; ++i) {
584         for (j = 0; j < REF_TYPES; ++j) {
585           for (k = 0; k < COEF_BANDS; ++k) {
586             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
587               // calc probs and branch cts for this frame only
588               for (t = 0; t < entropy_nodes_update; ++t) {
589                 vpx_prob newp = new_coef_probs[i][j][k][l][t];
590                 vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
591                 const vpx_prob upd = DIFF_UPDATE_PROB;
592                 int s;
593                 int u = 0;
594                 if (t == PIVOT_NODE)
595                   s = vp9_prob_diff_update_savings_search_model(
596                       frame_branch_ct[i][j][k][l][0],
597                       old_coef_probs[i][j][k][l], &newp, upd, stepsize);
598                 else
599                   s = vp9_prob_diff_update_savings_search(
600                       frame_branch_ct[i][j][k][l][t],
601                       *oldp, &newp, upd);
602                 if (s > 0 && newp != *oldp)
603                   u = 1;
604                 vpx_write(bc, u, upd);
605                 if (u) {
606                   /* send/use new probability */
607                   vp9_write_prob_diff_update(bc, newp, *oldp);
608                   *oldp = newp;
609                 }
610               }
611             }
612           }
613         }
614       }
615       return;
616     }
617
618     case ONE_LOOP_REDUCED: {
619       int updates = 0;
620       int noupdates_before_first = 0;
621       for (i = 0; i < PLANE_TYPES; ++i) {
622         for (j = 0; j < REF_TYPES; ++j) {
623           for (k = 0; k < COEF_BANDS; ++k) {
624             for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
625               // calc probs and branch cts for this frame only
626               for (t = 0; t < entropy_nodes_update; ++t) {
627                 vpx_prob newp = new_coef_probs[i][j][k][l][t];
628                 vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
629                 int s;
630                 int u = 0;
631
632                 if (t == PIVOT_NODE) {
633                   s = vp9_prob_diff_update_savings_search_model(
634                       frame_branch_ct[i][j][k][l][0],
635                       old_coef_probs[i][j][k][l], &newp, upd, stepsize);
636                 } else {
637                   s = vp9_prob_diff_update_savings_search(
638                       frame_branch_ct[i][j][k][l][t],
639                       *oldp, &newp, upd);
640                 }
641
642                 if (s > 0 && newp != *oldp)
643                   u = 1;
644                 updates += u;
645                 if (u == 0 && updates == 0) {
646                   noupdates_before_first++;
647                   continue;
648                 }
649                 if (u == 1 && updates == 1) {
650                   int v;
651                   // first update
652                   vpx_write_bit(bc, 1);
653                   for (v = 0; v < noupdates_before_first; ++v)
654                     vpx_write(bc, 0, upd);
655                 }
656                 vpx_write(bc, u, upd);
657                 if (u) {
658                   /* send/use new probability */
659                   vp9_write_prob_diff_update(bc, newp, *oldp);
660                   *oldp = newp;
661                 }
662               }
663             }
664           }
665         }
666       }
667       if (updates == 0) {
668         vpx_write_bit(bc, 0);  // no updates
669       }
670       return;
671     }
672     default:
673       assert(0);
674   }
675 }
676
677 static void update_coef_probs(VP9_COMP *cpi, vpx_writer* w) {
678   const TX_MODE tx_mode = cpi->common.tx_mode;
679   const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
680   TX_SIZE tx_size;
681   for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size) {
682     vp9_coeff_stats frame_branch_ct[PLANE_TYPES];
683     vp9_coeff_probs_model frame_coef_probs[PLANE_TYPES];
684     if (cpi->td.counts->tx.tx_totals[tx_size] <= 20 ||
685         (tx_size >= TX_16X16 && cpi->sf.tx_size_search_method == USE_TX_8X8)) {
686       vpx_write_bit(w, 0);
687     } else {
688       build_tree_distribution(cpi, tx_size, frame_branch_ct,
689                               frame_coef_probs);
690       update_coef_probs_common(w, cpi, tx_size, frame_branch_ct,
691                                frame_coef_probs);
692     }
693   }
694 }
695
696 static void encode_loopfilter(struct loopfilter *lf,
697                               struct vpx_write_bit_buffer *wb) {
698   int i;
699
700   // Encode the loop filter level and type
701   vpx_wb_write_literal(wb, lf->filter_level, 6);
702   vpx_wb_write_literal(wb, lf->sharpness_level, 3);
703
704   // Write out loop filter deltas applied at the MB level based on mode or
705   // ref frame (if they are enabled).
706   vpx_wb_write_bit(wb, lf->mode_ref_delta_enabled);
707
708   if (lf->mode_ref_delta_enabled) {
709     vpx_wb_write_bit(wb, lf->mode_ref_delta_update);
710     if (lf->mode_ref_delta_update) {
711       for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
712         const int delta = lf->ref_deltas[i];
713         const int changed = delta != lf->last_ref_deltas[i];
714         vpx_wb_write_bit(wb, changed);
715         if (changed) {
716           lf->last_ref_deltas[i] = delta;
717           vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
718           vpx_wb_write_bit(wb, delta < 0);
719         }
720       }
721
722       for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
723         const int delta = lf->mode_deltas[i];
724         const int changed = delta != lf->last_mode_deltas[i];
725         vpx_wb_write_bit(wb, changed);
726         if (changed) {
727           lf->last_mode_deltas[i] = delta;
728           vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
729           vpx_wb_write_bit(wb, delta < 0);
730         }
731       }
732     }
733   }
734 }
735
736 static void write_delta_q(struct vpx_write_bit_buffer *wb, int delta_q) {
737   if (delta_q != 0) {
738     vpx_wb_write_bit(wb, 1);
739     vpx_wb_write_literal(wb, abs(delta_q), 4);
740     vpx_wb_write_bit(wb, delta_q < 0);
741   } else {
742     vpx_wb_write_bit(wb, 0);
743   }
744 }
745
746 static void encode_quantization(const VP9_COMMON *const cm,
747                                 struct vpx_write_bit_buffer *wb) {
748   vpx_wb_write_literal(wb, cm->base_qindex, QINDEX_BITS);
749   write_delta_q(wb, cm->y_dc_delta_q);
750   write_delta_q(wb, cm->uv_dc_delta_q);
751   write_delta_q(wb, cm->uv_ac_delta_q);
752 }
753
754 static void encode_segmentation(VP9_COMMON *cm, MACROBLOCKD *xd,
755                                 struct vpx_write_bit_buffer *wb) {
756   int i, j;
757
758   const struct segmentation *seg = &cm->seg;
759
760   vpx_wb_write_bit(wb, seg->enabled);
761   if (!seg->enabled)
762     return;
763
764   // Segmentation map
765   vpx_wb_write_bit(wb, seg->update_map);
766   if (seg->update_map) {
767     // Select the coding strategy (temporal or spatial)
768     vp9_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     vpx_wb_write_bit(wb, seg->temporal_update);
780     if (seg->temporal_update) {
781       for (i = 0; i < PREDICTION_PROBS; i++) {
782         const int prob = seg->pred_probs[i];
783         const int update = prob != MAX_PROB;
784         vpx_wb_write_bit(wb, update);
785         if (update)
786           vpx_wb_write_literal(wb, prob, 8);
787       }
788     }
789   }
790
791   // Segmentation data
792   vpx_wb_write_bit(wb, seg->update_data);
793   if (seg->update_data) {
794     vpx_wb_write_bit(wb, seg->abs_delta);
795
796     for (i = 0; i < MAX_SEGMENTS; i++) {
797       for (j = 0; j < SEG_LVL_MAX; j++) {
798         const int active = segfeature_active(seg, i, j);
799         vpx_wb_write_bit(wb, active);
800         if (active) {
801           const int data = get_segdata(seg, i, j);
802           const int data_max = vp9_seg_feature_data_max(j);
803
804           if (vp9_is_segfeature_signed(j)) {
805             encode_unsigned_max(wb, abs(data), data_max);
806             vpx_wb_write_bit(wb, data < 0);
807           } else {
808             encode_unsigned_max(wb, data, data_max);
809           }
810         }
811       }
812     }
813   }
814 }
815
816 static void encode_txfm_probs(VP9_COMMON *cm, vpx_writer *w,
817                               FRAME_COUNTS *counts) {
818   // Mode
819   vpx_write_literal(w, VPXMIN(cm->tx_mode, ALLOW_32X32), 2);
820   if (cm->tx_mode >= ALLOW_32X32)
821     vpx_write_bit(w, cm->tx_mode == TX_MODE_SELECT);
822
823   // Probabilities
824   if (cm->tx_mode == TX_MODE_SELECT) {
825     int i, j;
826     unsigned int ct_8x8p[TX_SIZES - 3][2];
827     unsigned int ct_16x16p[TX_SIZES - 2][2];
828     unsigned int ct_32x32p[TX_SIZES - 1][2];
829
830
831     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
832       tx_counts_to_branch_counts_8x8(counts->tx.p8x8[i], ct_8x8p);
833       for (j = 0; j < TX_SIZES - 3; j++)
834         vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p8x8[i][j], ct_8x8p[j]);
835     }
836
837     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
838       tx_counts_to_branch_counts_16x16(counts->tx.p16x16[i], ct_16x16p);
839       for (j = 0; j < TX_SIZES - 2; j++)
840         vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p16x16[i][j],
841                                   ct_16x16p[j]);
842     }
843
844     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
845       tx_counts_to_branch_counts_32x32(counts->tx.p32x32[i], ct_32x32p);
846       for (j = 0; j < TX_SIZES - 1; j++)
847         vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p32x32[i][j],
848                                   ct_32x32p[j]);
849     }
850   }
851 }
852
853 static void write_interp_filter(INTERP_FILTER filter,
854                                 struct vpx_write_bit_buffer *wb) {
855   const int filter_to_literal[] = { 1, 0, 2, 3 };
856
857   vpx_wb_write_bit(wb, filter == SWITCHABLE);
858   if (filter != SWITCHABLE)
859     vpx_wb_write_literal(wb, filter_to_literal[filter], 2);
860 }
861
862 static void fix_interp_filter(VP9_COMMON *cm, FRAME_COUNTS *counts) {
863   if (cm->interp_filter == SWITCHABLE) {
864     // Check to see if only one of the filters is actually used
865     int count[SWITCHABLE_FILTERS];
866     int i, j, c = 0;
867     for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
868       count[i] = 0;
869       for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
870         count[i] += counts->switchable_interp[j][i];
871       c += (count[i] > 0);
872     }
873     if (c == 1) {
874       // Only one filter is used. So set the filter at frame level
875       for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
876         if (count[i]) {
877           cm->interp_filter = i;
878           break;
879         }
880       }
881     }
882   }
883 }
884
885 static void write_tile_info(const VP9_COMMON *const cm,
886                             struct vpx_write_bit_buffer *wb) {
887   int min_log2_tile_cols, max_log2_tile_cols, ones;
888   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
889
890   // columns
891   ones = cm->log2_tile_cols - min_log2_tile_cols;
892   while (ones--)
893     vpx_wb_write_bit(wb, 1);
894
895   if (cm->log2_tile_cols < max_log2_tile_cols)
896     vpx_wb_write_bit(wb, 0);
897
898   // rows
899   vpx_wb_write_bit(wb, cm->log2_tile_rows != 0);
900   if (cm->log2_tile_rows != 0)
901     vpx_wb_write_bit(wb, cm->log2_tile_rows != 1);
902 }
903
904 static int get_refresh_mask(VP9_COMP *cpi) {
905   if (vp9_preserve_existing_gf(cpi)) {
906     // We have decided to preserve the previously existing golden frame as our
907     // new ARF frame. However, in the short term we leave it in the GF slot and,
908     // if we're updating the GF with the current decoded frame, we save it
909     // instead to the ARF slot.
910     // Later, in the function vp9_encoder.c:vp9_update_reference_frames() we
911     // will swap gld_fb_idx and alt_fb_idx to achieve our objective. We do it
912     // there so that it can be done outside of the recode loop.
913     // Note: This is highly specific to the use of ARF as a forward reference,
914     // and this needs to be generalized as other uses are implemented
915     // (like RTC/temporal scalability).
916     return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
917            (cpi->refresh_golden_frame << cpi->alt_fb_idx);
918   } else {
919     int arf_idx = cpi->alt_fb_idx;
920     if ((cpi->oxcf.pass == 2) && cpi->multi_arf_allowed) {
921       const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
922       arf_idx = gf_group->arf_update_idx[gf_group->index];
923     }
924     return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
925            (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
926            (cpi->refresh_alt_ref_frame << arf_idx);
927   }
928 }
929
930 static size_t encode_tiles(VP9_COMP *cpi, uint8_t *data_ptr) {
931   VP9_COMMON *const cm = &cpi->common;
932   vpx_writer residual_bc;
933   int tile_row, tile_col;
934   TOKENEXTRA *tok_end;
935   size_t total_size = 0;
936   const int tile_cols = 1 << cm->log2_tile_cols;
937   const int tile_rows = 1 << cm->log2_tile_rows;
938
939   memset(cm->above_seg_context, 0,
940          sizeof(*cm->above_seg_context) * mi_cols_aligned_to_sb(cm->mi_cols));
941
942   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
943     for (tile_col = 0; tile_col < tile_cols; tile_col++) {
944       int tile_idx = tile_row * tile_cols + tile_col;
945       TOKENEXTRA *tok = cpi->tile_tok[tile_row][tile_col];
946
947       tok_end = cpi->tile_tok[tile_row][tile_col] +
948           cpi->tok_count[tile_row][tile_col];
949
950       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1)
951         vpx_start_encode(&residual_bc, data_ptr + total_size + 4);
952       else
953         vpx_start_encode(&residual_bc, data_ptr + total_size);
954
955       write_modes(cpi, &cpi->tile_data[tile_idx].tile_info,
956                   &residual_bc, &tok, tok_end);
957       assert(tok == tok_end);
958       vpx_stop_encode(&residual_bc);
959       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1) {
960         // size of this tile
961         mem_put_be32(data_ptr + total_size, residual_bc.pos);
962         total_size += 4;
963       }
964
965       total_size += residual_bc.pos;
966     }
967   }
968
969   return total_size;
970 }
971
972 static void write_display_size(const VP9_COMMON *cm,
973                                struct vpx_write_bit_buffer *wb) {
974   const int scaling_active = cm->width != cm->display_width ||
975                              cm->height != cm->display_height;
976   vpx_wb_write_bit(wb, scaling_active);
977   if (scaling_active) {
978     vpx_wb_write_literal(wb, cm->display_width - 1, 16);
979     vpx_wb_write_literal(wb, cm->display_height - 1, 16);
980   }
981 }
982
983 static void write_frame_size(const VP9_COMMON *cm,
984                              struct vpx_write_bit_buffer *wb) {
985   vpx_wb_write_literal(wb, cm->width - 1, 16);
986   vpx_wb_write_literal(wb, cm->height - 1, 16);
987
988   write_display_size(cm, wb);
989 }
990
991 static void write_frame_size_with_refs(VP9_COMP *cpi,
992                                        struct vpx_write_bit_buffer *wb) {
993   VP9_COMMON *const cm = &cpi->common;
994   int found = 0;
995
996   MV_REFERENCE_FRAME ref_frame;
997   for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
998     YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, ref_frame);
999
1000     // Set "found" to 0 for temporal svc and for spatial svc key frame
1001     if (cpi->use_svc &&
1002         ((cpi->svc.number_temporal_layers > 1 &&
1003          cpi->oxcf.rc_mode == VPX_CBR) ||
1004         (cpi->svc.number_spatial_layers > 1 &&
1005          cpi->svc.layer_context[cpi->svc.spatial_layer_id].is_key_frame) ||
1006         (is_two_pass_svc(cpi) &&
1007          cpi->svc.encode_empty_frame_state == ENCODING &&
1008          cpi->svc.layer_context[0].frames_from_key_frame <
1009          cpi->svc.number_temporal_layers + 1))) {
1010       found = 0;
1011     } else if (cfg != NULL) {
1012       found = cm->width == cfg->y_crop_width &&
1013               cm->height == cfg->y_crop_height;
1014     }
1015     vpx_wb_write_bit(wb, found);
1016     if (found) {
1017       break;
1018     }
1019   }
1020
1021   if (!found) {
1022     vpx_wb_write_literal(wb, cm->width - 1, 16);
1023     vpx_wb_write_literal(wb, cm->height - 1, 16);
1024   }
1025
1026   write_display_size(cm, wb);
1027 }
1028
1029 static void write_sync_code(struct vpx_write_bit_buffer *wb) {
1030   vpx_wb_write_literal(wb, VP9_SYNC_CODE_0, 8);
1031   vpx_wb_write_literal(wb, VP9_SYNC_CODE_1, 8);
1032   vpx_wb_write_literal(wb, VP9_SYNC_CODE_2, 8);
1033 }
1034
1035 static void write_profile(BITSTREAM_PROFILE profile,
1036                           struct vpx_write_bit_buffer *wb) {
1037   switch (profile) {
1038     case PROFILE_0:
1039       vpx_wb_write_literal(wb, 0, 2);
1040       break;
1041     case PROFILE_1:
1042       vpx_wb_write_literal(wb, 2, 2);
1043       break;
1044     case PROFILE_2:
1045       vpx_wb_write_literal(wb, 1, 2);
1046       break;
1047     case PROFILE_3:
1048       vpx_wb_write_literal(wb, 6, 3);
1049       break;
1050     default:
1051       assert(0);
1052   }
1053 }
1054
1055 static void write_bitdepth_colorspace_sampling(
1056     VP9_COMMON *const cm, struct vpx_write_bit_buffer *wb) {
1057   if (cm->profile >= PROFILE_2) {
1058     assert(cm->bit_depth > VPX_BITS_8);
1059     vpx_wb_write_bit(wb, cm->bit_depth == VPX_BITS_10 ? 0 : 1);
1060   }
1061   vpx_wb_write_literal(wb, cm->color_space, 3);
1062   if (cm->color_space != VPX_CS_SRGB) {
1063     // 0: [16, 235] (i.e. xvYCC), 1: [0, 255]
1064     vpx_wb_write_bit(wb, cm->color_range);
1065     if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1066       assert(cm->subsampling_x != 1 || cm->subsampling_y != 1);
1067       vpx_wb_write_bit(wb, cm->subsampling_x);
1068       vpx_wb_write_bit(wb, cm->subsampling_y);
1069       vpx_wb_write_bit(wb, 0);  // unused
1070     } else {
1071       assert(cm->subsampling_x == 1 && cm->subsampling_y == 1);
1072     }
1073   } else {
1074     assert(cm->profile == PROFILE_1 || cm->profile == PROFILE_3);
1075     vpx_wb_write_bit(wb, 0);  // unused
1076   }
1077 }
1078
1079 static void write_uncompressed_header(VP9_COMP *cpi,
1080                                       struct vpx_write_bit_buffer *wb) {
1081   VP9_COMMON *const cm = &cpi->common;
1082   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1083
1084   vpx_wb_write_literal(wb, VP9_FRAME_MARKER, 2);
1085
1086   write_profile(cm->profile, wb);
1087
1088   vpx_wb_write_bit(wb, 0);  // show_existing_frame
1089   vpx_wb_write_bit(wb, cm->frame_type);
1090   vpx_wb_write_bit(wb, cm->show_frame);
1091   vpx_wb_write_bit(wb, cm->error_resilient_mode);
1092
1093   if (cm->frame_type == KEY_FRAME) {
1094     write_sync_code(wb);
1095     write_bitdepth_colorspace_sampling(cm, wb);
1096     write_frame_size(cm, wb);
1097   } else {
1098     // In spatial svc if it's not error_resilient_mode then we need to code all
1099     // visible frames as invisible. But we need to keep the show_frame flag so
1100     // that the publisher could know whether it is supposed to be visible.
1101     // So we will code the show_frame flag as it is. Then code the intra_only
1102     // bit here. This will make the bitstream incompatible. In the player we
1103     // will change to show_frame flag to 0, then add an one byte frame with
1104     // show_existing_frame flag which tells the decoder which frame we want to
1105     // show.
1106     if (!cm->show_frame)
1107       vpx_wb_write_bit(wb, cm->intra_only);
1108
1109     if (!cm->error_resilient_mode)
1110       vpx_wb_write_literal(wb, cm->reset_frame_context, 2);
1111
1112     if (cm->intra_only) {
1113       write_sync_code(wb);
1114
1115       // Note for profile 0, 420 8bpp is assumed.
1116       if (cm->profile > PROFILE_0) {
1117         write_bitdepth_colorspace_sampling(cm, wb);
1118       }
1119
1120       vpx_wb_write_literal(wb, get_refresh_mask(cpi), REF_FRAMES);
1121       write_frame_size(cm, wb);
1122     } else {
1123       MV_REFERENCE_FRAME ref_frame;
1124       vpx_wb_write_literal(wb, get_refresh_mask(cpi), REF_FRAMES);
1125       for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
1126         assert(get_ref_frame_map_idx(cpi, ref_frame) != INVALID_IDX);
1127         vpx_wb_write_literal(wb, get_ref_frame_map_idx(cpi, ref_frame),
1128                              REF_FRAMES_LOG2);
1129         vpx_wb_write_bit(wb, cm->ref_frame_sign_bias[ref_frame]);
1130       }
1131
1132       write_frame_size_with_refs(cpi, wb);
1133
1134       vpx_wb_write_bit(wb, cm->allow_high_precision_mv);
1135
1136       fix_interp_filter(cm, cpi->td.counts);
1137       write_interp_filter(cm->interp_filter, wb);
1138     }
1139   }
1140
1141   if (!cm->error_resilient_mode) {
1142     vpx_wb_write_bit(wb, cm->refresh_frame_context);
1143     vpx_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
1144   }
1145
1146   vpx_wb_write_literal(wb, cm->frame_context_idx, FRAME_CONTEXTS_LOG2);
1147
1148   encode_loopfilter(&cm->lf, wb);
1149   encode_quantization(cm, wb);
1150   encode_segmentation(cm, xd, wb);
1151
1152   write_tile_info(cm, wb);
1153 }
1154
1155 static size_t write_compressed_header(VP9_COMP *cpi, uint8_t *data) {
1156   VP9_COMMON *const cm = &cpi->common;
1157   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
1158   FRAME_CONTEXT *const fc = cm->fc;
1159   FRAME_COUNTS *counts = cpi->td.counts;
1160   vpx_writer header_bc;
1161
1162   vpx_start_encode(&header_bc, data);
1163
1164   if (xd->lossless)
1165     cm->tx_mode = ONLY_4X4;
1166   else
1167     encode_txfm_probs(cm, &header_bc, counts);
1168
1169   update_coef_probs(cpi, &header_bc);
1170   update_skip_probs(cm, &header_bc, counts);
1171
1172   if (!frame_is_intra_only(cm)) {
1173     int i;
1174
1175     for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
1176       prob_diff_update(vp9_inter_mode_tree, cm->fc->inter_mode_probs[i],
1177                        counts->inter_mode[i], INTER_MODES, &header_bc);
1178
1179     if (cm->interp_filter == SWITCHABLE)
1180       update_switchable_interp_probs(cm, &header_bc, counts);
1181
1182     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1183       vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i],
1184                                 counts->intra_inter[i]);
1185
1186     if (cpi->allow_comp_inter_inter) {
1187       const int use_compound_pred = cm->reference_mode != SINGLE_REFERENCE;
1188       const int use_hybrid_pred = cm->reference_mode == REFERENCE_MODE_SELECT;
1189
1190       vpx_write_bit(&header_bc, use_compound_pred);
1191       if (use_compound_pred) {
1192         vpx_write_bit(&header_bc, use_hybrid_pred);
1193         if (use_hybrid_pred)
1194           for (i = 0; i < COMP_INTER_CONTEXTS; i++)
1195             vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i],
1196                                       counts->comp_inter[i]);
1197       }
1198     }
1199
1200     if (cm->reference_mode != COMPOUND_REFERENCE) {
1201       for (i = 0; i < REF_CONTEXTS; i++) {
1202         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0],
1203                                   counts->single_ref[i][0]);
1204         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1],
1205                                   counts->single_ref[i][1]);
1206       }
1207     }
1208
1209     if (cm->reference_mode != SINGLE_REFERENCE)
1210       for (i = 0; i < REF_CONTEXTS; i++)
1211         vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i],
1212                                   counts->comp_ref[i]);
1213
1214     for (i = 0; i < BLOCK_SIZE_GROUPS; ++i)
1215       prob_diff_update(vp9_intra_mode_tree, cm->fc->y_mode_prob[i],
1216                        counts->y_mode[i], INTRA_MODES, &header_bc);
1217
1218     for (i = 0; i < PARTITION_CONTEXTS; ++i)
1219       prob_diff_update(vp9_partition_tree, fc->partition_prob[i],
1220                        counts->partition[i], PARTITION_TYPES, &header_bc);
1221
1222     vp9_write_nmv_probs(cm, cm->allow_high_precision_mv, &header_bc,
1223                         &counts->mv);
1224   }
1225
1226   vpx_stop_encode(&header_bc);
1227   assert(header_bc.pos <= 0xffff);
1228
1229   return header_bc.pos;
1230 }
1231
1232 void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, size_t *size) {
1233   uint8_t *data = dest;
1234   size_t first_part_size, uncompressed_hdr_size;
1235   struct vpx_write_bit_buffer wb = {data, 0};
1236   struct vpx_write_bit_buffer saved_wb;
1237
1238   write_uncompressed_header(cpi, &wb);
1239   saved_wb = wb;
1240   vpx_wb_write_literal(&wb, 0, 16);  // don't know in advance first part. size
1241
1242   uncompressed_hdr_size = vpx_wb_bytes_written(&wb);
1243   data += uncompressed_hdr_size;
1244
1245   vpx_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   vpx_wb_write_literal(&saved_wb, (int)first_part_size, 16);
1251
1252   data += encode_tiles(cpi, data);
1253
1254   *size = data - dest;
1255 }