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