]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_bitstream.c
Merge "cleanups after bw bh code"
[libvpx] / vp9 / encoder / vp9_bitstream.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <assert.h>
12 #include <stdio.h>
13 #include <limits.h>
14
15 #include "vpx/vpx_encoder.h"
16 #include "vpx_mem/vpx_mem.h"
17
18 #include "vp9/common/vp9_entropymode.h"
19 #include "vp9/common/vp9_entropymv.h"
20 #include "vp9/common/vp9_findnearmv.h"
21 #include "vp9/common/vp9_tile_common.h"
22 #include "vp9/common/vp9_seg_common.h"
23 #include "vp9/common/vp9_pred_common.h"
24 #include "vp9/common/vp9_entropy.h"
25 #include "vp9/common/vp9_entropymv.h"
26 #include "vp9/common/vp9_mvref_common.h"
27 #include "vp9/common/vp9_treecoder.h"
28 #include "vp9/common/vp9_systemdependent.h"
29 #include "vp9/common/vp9_pragmas.h"
30
31 #include "vp9/encoder/vp9_mcomp.h"
32 #include "vp9/encoder/vp9_encodemv.h"
33 #include "vp9/encoder/vp9_bitstream.h"
34 #include "vp9/encoder/vp9_segmentation.h"
35 #include "vp9/encoder/vp9_subexp.h"
36 #include "vp9/encoder/vp9_write_bit_buffer.h"
37
38
39 #if defined(SECTIONBITS_OUTPUT)
40 unsigned __int64 Sectionbits[500];
41 #endif
42
43 #ifdef ENTROPY_STATS
44 int intra_mode_stats[VP9_INTRA_MODES]
45                     [VP9_INTRA_MODES]
46                     [VP9_INTRA_MODES];
47 vp9_coeff_stats tree_update_hist[TX_SIZES][BLOCK_TYPES];
48
49 extern unsigned int active_section;
50 #endif
51
52
53 #ifdef MODE_STATS
54 int64_t tx_count_32x32p_stats[TX_SIZE_CONTEXTS][TX_SIZES];
55 int64_t tx_count_16x16p_stats[TX_SIZE_CONTEXTS][TX_SIZES - 1];
56 int64_t tx_count_8x8p_stats[TX_SIZE_CONTEXTS][TX_SIZES - 2];
57 int64_t switchable_interp_stats[VP9_SWITCHABLE_FILTERS+1]
58                                [VP9_SWITCHABLE_FILTERS];
59
60 void init_tx_count_stats() {
61   vp9_zero(tx_count_32x32p_stats);
62   vp9_zero(tx_count_16x16p_stats);
63   vp9_zero(tx_count_8x8p_stats);
64 }
65
66 void init_switchable_interp_stats() {
67   vp9_zero(switchable_interp_stats);
68 }
69
70 static void update_tx_count_stats(VP9_COMMON *cm) {
71   int i, j;
72   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
73     for (j = 0; j < TX_SIZES; j++) {
74       tx_count_32x32p_stats[i][j] += cm->fc.tx_count_32x32p[i][j];
75     }
76   }
77   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
78     for (j = 0; j < TX_SIZES - 1; j++) {
79       tx_count_16x16p_stats[i][j] += cm->fc.tx_count_16x16p[i][j];
80     }
81   }
82   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
83     for (j = 0; j < TX_SIZES - 2; j++) {
84       tx_count_8x8p_stats[i][j] += cm->fc.tx_count_8x8p[i][j];
85     }
86   }
87 }
88
89 static void update_switchable_interp_stats(VP9_COMMON *cm) {
90   int i, j;
91   for (i = 0; i < VP9_SWITCHABLE_FILTERS+1; ++i)
92     for (j = 0; j < VP9_SWITCHABLE_FILTERS; ++j) {
93       switchable_interp_stats[i][j] += cm->fc.switchable_interp_count[i][j];
94     }
95 }
96
97 void write_tx_count_stats() {
98   int i, j;
99   FILE *fp = fopen("tx_count.bin", "wb");
100   fwrite(tx_count_32x32p_stats, sizeof(tx_count_32x32p_stats), 1, fp);
101   fwrite(tx_count_16x16p_stats, sizeof(tx_count_16x16p_stats), 1, fp);
102   fwrite(tx_count_8x8p_stats, sizeof(tx_count_8x8p_stats), 1, fp);
103   fclose(fp);
104
105   printf(
106       "vp9_default_tx_count_32x32p[TX_SIZE_CONTEXTS][TX_SIZES] = {\n");
107   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
108     printf("  { ");
109     for (j = 0; j < TX_SIZES; j++) {
110       printf("%"PRId64", ", tx_count_32x32p_stats[i][j]);
111     }
112     printf("},\n");
113   }
114   printf("};\n");
115   printf(
116       "vp9_default_tx_count_16x16p[TX_SIZE_CONTEXTS][TX_SIZES-1] = {\n");
117   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
118     printf("  { ");
119     for (j = 0; j < TX_SIZES - 1; j++) {
120       printf("%"PRId64", ", tx_count_16x16p_stats[i][j]);
121     }
122     printf("},\n");
123   }
124   printf("};\n");
125   printf(
126       "vp9_default_tx_count_8x8p[TX_SIZE_CONTEXTS][TX_SIZES-2] = {\n");
127   for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
128     printf("  { ");
129     for (j = 0; j < TX_SIZES - 2; j++) {
130       printf("%"PRId64", ", tx_count_8x8p_stats[i][j]);
131     }
132     printf("},\n");
133   }
134   printf("};\n");
135 }
136
137 void write_switchable_interp_stats() {
138   int i, j;
139   FILE *fp = fopen("switchable_interp.bin", "wb");
140   fwrite(switchable_interp_stats, sizeof(switchable_interp_stats), 1, fp);
141   fclose(fp);
142
143   printf(
144       "vp9_default_switchable_filter_count[VP9_SWITCHABLE_FILTERS+1]"
145       "[VP9_SWITCHABLE_FILTERS] = {\n");
146   for (i = 0; i < VP9_SWITCHABLE_FILTERS+1; i++) {
147     printf("  { ");
148     for (j = 0; j < VP9_SWITCHABLE_FILTERS; j++) {
149       printf("%"PRId64", ", switchable_interp_stats[i][j]);
150     }
151     printf("},\n");
152   }
153   printf("};\n");
154 }
155 #endif
156
157 static INLINE void write_be32(uint8_t *p, int value) {
158   p[0] = value >> 24;
159   p[1] = value >> 16;
160   p[2] = value >> 8;
161   p[3] = value;
162 }
163
164 void vp9_encode_unsigned_max(struct vp9_write_bit_buffer *wb,
165                              int data, int max) {
166   vp9_wb_write_literal(wb, data, get_unsigned_bits(max));
167 }
168
169 static void update_mode(
170   vp9_writer *w,
171   int n,
172   vp9_tree tree,
173   vp9_prob Pnew[/* n-1 */],
174   vp9_prob Pcur[/* n-1 */],
175   unsigned int bct[/* n-1 */] [2],
176   const unsigned int num_events[/* n */]
177 ) {
178   int i = 0;
179
180   vp9_tree_probs_from_distribution(tree, Pnew, bct, num_events, 0);
181   n--;
182
183   for (i = 0; i < n; ++i) {
184     vp9_cond_prob_diff_update(w, &Pcur[i], VP9_MODE_UPDATE_PROB, bct[i]);
185   }
186 }
187
188 static void update_mbintra_mode_probs(VP9_COMP* const cpi,
189                                       vp9_writer* const bc) {
190   VP9_COMMON *const cm = &cpi->common;
191   int j;
192   vp9_prob pnew[VP9_INTRA_MODES - 1];
193   unsigned int bct[VP9_INTRA_MODES - 1][2];
194
195   for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
196     update_mode(bc, VP9_INTRA_MODES, vp9_intra_mode_tree, pnew,
197                 cm->fc.y_mode_prob[j], bct,
198                 (unsigned int *)cpi->y_mode_count[j]);
199 }
200
201 static void write_selected_tx_size(const VP9_COMP *cpi, TX_SIZE tx_size,
202                                    BLOCK_SIZE_TYPE bsize, vp9_writer *w) {
203   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
204   const vp9_prob *tx_probs = get_tx_probs2(xd, &cpi->common.fc.tx_probs);
205   vp9_write(w, tx_size != TX_4X4, tx_probs[0]);
206   if (bsize >= BLOCK_16X16 && tx_size != TX_4X4) {
207     vp9_write(w, tx_size != TX_8X8, tx_probs[1]);
208     if (bsize >= BLOCK_32X32 && tx_size != TX_8X8)
209       vp9_write(w, tx_size != TX_16X16, tx_probs[2]);
210   }
211 }
212
213 static int write_skip_coeff(const VP9_COMP *cpi, int segment_id, MODE_INFO *m,
214                             vp9_writer *w) {
215   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
216   if (vp9_segfeature_active(&xd->seg, segment_id, SEG_LVL_SKIP)) {
217     return 1;
218   } else {
219     const int skip_coeff = m->mbmi.mb_skip_coeff;
220     vp9_write(w, skip_coeff, vp9_get_pred_prob_mbskip(&cpi->common, xd));
221     return skip_coeff;
222   }
223 }
224
225 void vp9_update_skip_probs(VP9_COMP *cpi, vp9_writer *w) {
226   VP9_COMMON *cm = &cpi->common;
227   int k;
228
229   for (k = 0; k < MBSKIP_CONTEXTS; ++k)
230     vp9_cond_prob_diff_update(w, &cm->fc.mbskip_probs[k],
231                               VP9_MODE_UPDATE_PROB, cm->counts.mbskip[k]);
232 }
233
234 static void write_intra_mode(vp9_writer *bc, int m, const vp9_prob *p) {
235   write_token(bc, vp9_intra_mode_tree, p, vp9_intra_mode_encodings + m);
236 }
237
238 static void update_switchable_interp_probs(VP9_COMP *const cpi,
239                                            vp9_writer* const bc) {
240   VP9_COMMON *const pc = &cpi->common;
241   unsigned int branch_ct[VP9_SWITCHABLE_FILTERS + 1]
242                         [VP9_SWITCHABLE_FILTERS - 1][2];
243   vp9_prob new_prob[VP9_SWITCHABLE_FILTERS + 1][VP9_SWITCHABLE_FILTERS - 1];
244   int i, j;
245   for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
246     vp9_tree_probs_from_distribution(
247         vp9_switchable_interp_tree,
248         new_prob[j], branch_ct[j],
249         pc->counts.switchable_interp[j], 0);
250   }
251   for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j) {
252     for (i = 0; i < VP9_SWITCHABLE_FILTERS - 1; ++i) {
253       vp9_cond_prob_diff_update(bc, &pc->fc.switchable_interp_prob[j][i],
254                                 VP9_MODE_UPDATE_PROB, branch_ct[j][i]);
255     }
256   }
257 #ifdef MODE_STATS
258   if (!cpi->dummy_packing)
259     update_switchable_interp_stats(pc);
260 #endif
261 }
262
263 static void update_inter_mode_probs(VP9_COMMON *pc, vp9_writer* const bc) {
264   int i, j;
265
266   for (i = 0; i < INTER_MODE_CONTEXTS; ++i) {
267     unsigned int branch_ct[VP9_INTER_MODES - 1][2];
268     vp9_prob new_prob[VP9_INTER_MODES - 1];
269
270     vp9_tree_probs_from_distribution(vp9_inter_mode_tree,
271                                      new_prob, branch_ct,
272                                      pc->counts.inter_mode[i], NEARESTMV);
273
274     for (j = 0; j < VP9_INTER_MODES - 1; ++j)
275       vp9_cond_prob_diff_update(bc, &pc->fc.inter_mode_probs[i][j],
276                                 VP9_MODE_UPDATE_PROB, branch_ct[j]);
277   }
278 }
279
280 static void pack_mb_tokens(vp9_writer* const bc,
281                            TOKENEXTRA **tp,
282                            const TOKENEXTRA *const stop) {
283   TOKENEXTRA *p = *tp;
284
285   while (p < stop) {
286     const int t = p->token;
287     const struct vp9_token *const a = vp9_coef_encodings + t;
288     const vp9_extra_bit *const b = vp9_extra_bits + t;
289     int i = 0;
290     const vp9_prob *pp;
291     int v = a->value;
292     int n = a->len;
293     vp9_prob probs[ENTROPY_NODES];
294
295     if (t == EOSB_TOKEN) {
296       ++p;
297       break;
298     }
299     if (t >= TWO_TOKEN) {
300       vp9_model_to_full_probs(p->context_tree, probs);
301       pp = probs;
302     } else {
303       pp = p->context_tree;
304     }
305     assert(pp != 0);
306
307     /* skip one or two nodes */
308     if (p->skip_eob_node) {
309       n -= p->skip_eob_node;
310       i = 2 * p->skip_eob_node;
311     }
312
313     do {
314       const int bb = (v >> --n) & 1;
315       vp9_write(bc, bb, pp[i >> 1]);
316       i = vp9_coef_tree[i + bb];
317     } while (n);
318
319     if (b->base_val) {
320       const int e = p->extra, l = b->len;
321
322       if (l) {
323         const unsigned char *pb = b->prob;
324         int v = e >> 1;
325         int n = l;              /* number of bits in v, assumed nonzero */
326         int i = 0;
327
328         do {
329           const int bb = (v >> --n) & 1;
330           vp9_write(bc, bb, pb[i >> 1]);
331           i = b->tree[i + bb];
332         } while (n);
333       }
334
335       vp9_write_bit(bc, e & 1);
336     }
337     ++p;
338   }
339
340   *tp = p;
341 }
342
343 static void write_sb_mv_ref(vp9_writer *w, MB_PREDICTION_MODE mode,
344                             const vp9_prob *p) {
345   assert(is_inter_mode(mode));
346   write_token(w, vp9_inter_mode_tree, p,
347               &vp9_inter_mode_encodings[mode - NEARESTMV]);
348 }
349
350
351 static void write_segment_id(vp9_writer *w, const struct segmentation *seg,
352                              int segment_id) {
353   if (seg->enabled && seg->update_map)
354     treed_write(w, vp9_segment_tree, seg->tree_probs, segment_id, 3);
355 }
356
357 // This function encodes the reference frame
358 static void encode_ref_frame(VP9_COMP *cpi, vp9_writer *bc) {
359   VP9_COMMON *const pc = &cpi->common;
360   MACROBLOCK *const x = &cpi->mb;
361   MACROBLOCKD *const xd = &x->e_mbd;
362   MB_MODE_INFO *mi = &xd->mode_info_context->mbmi;
363   const int segment_id = mi->segment_id;
364   int seg_ref_active = vp9_segfeature_active(&xd->seg, segment_id,
365                                              SEG_LVL_REF_FRAME);
366   // If segment level coding of this signal is disabled...
367   // or the segment allows multiple reference frame options
368   if (!seg_ref_active) {
369     // does the feature use compound prediction or not
370     // (if not specified at the frame/segment level)
371     if (pc->comp_pred_mode == HYBRID_PREDICTION) {
372       vp9_write(bc, mi->ref_frame[1] > INTRA_FRAME,
373                 vp9_get_pred_prob_comp_inter_inter(pc, xd));
374     } else {
375       assert((mi->ref_frame[1] <= INTRA_FRAME) ==
376                  (pc->comp_pred_mode == SINGLE_PREDICTION_ONLY));
377     }
378
379     if (mi->ref_frame[1] > INTRA_FRAME) {
380       vp9_write(bc, mi->ref_frame[0] == GOLDEN_FRAME,
381                 vp9_get_pred_prob_comp_ref_p(pc, xd));
382     } else {
383       vp9_write(bc, mi->ref_frame[0] != LAST_FRAME,
384                 vp9_get_pred_prob_single_ref_p1(pc, xd));
385       if (mi->ref_frame[0] != LAST_FRAME)
386         vp9_write(bc, mi->ref_frame[0] != GOLDEN_FRAME,
387                   vp9_get_pred_prob_single_ref_p2(pc, xd));
388     }
389   } else {
390     assert(mi->ref_frame[1] <= INTRA_FRAME);
391     assert(vp9_get_segdata(&xd->seg, segment_id, SEG_LVL_REF_FRAME) ==
392            mi->ref_frame[0]);
393   }
394
395   // if using the prediction mdoel we have nothing further to do because
396   // the reference frame is fully coded by the segment
397 }
398
399 static void pack_inter_mode_mvs(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc) {
400   VP9_COMMON *const pc = &cpi->common;
401   const nmv_context *nmvc = &pc->fc.nmvc;
402   MACROBLOCK *const x = &cpi->mb;
403   MACROBLOCKD *const xd = &x->e_mbd;
404   struct segmentation *seg = &xd->seg;
405   MB_MODE_INFO *const mi = &m->mbmi;
406   const MV_REFERENCE_FRAME rf = mi->ref_frame[0];
407   const MB_PREDICTION_MODE mode = mi->mode;
408   const int segment_id = mi->segment_id;
409   int skip_coeff;
410   const BLOCK_SIZE_TYPE bsize = mi->sb_type;
411   const int allow_hp = xd->allow_high_precision_mv;
412
413   x->partition_info = x->pi + (m - pc->mi);
414
415 #ifdef ENTROPY_STATS
416   active_section = 9;
417 #endif
418
419   if (seg->update_map) {
420     if (seg->temporal_update) {
421       const int pred_flag = mi->seg_id_predicted;
422       vp9_prob pred_prob = vp9_get_pred_prob_seg_id(xd);
423       vp9_write(bc, pred_flag, pred_prob);
424       if (!pred_flag)
425         write_segment_id(bc, seg, segment_id);
426     } else {
427       write_segment_id(bc, seg, segment_id);
428     }
429   }
430
431   skip_coeff = write_skip_coeff(cpi, segment_id, m, bc);
432
433   if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
434     vp9_write(bc, rf != INTRA_FRAME,
435               vp9_get_pred_prob_intra_inter(pc, xd));
436
437   if (bsize >= BLOCK_SIZE_SB8X8 && pc->tx_mode == TX_MODE_SELECT &&
438       !(rf != INTRA_FRAME &&
439         (skip_coeff || vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)))) {
440     write_selected_tx_size(cpi, mi->txfm_size, bsize, bc);
441   }
442
443   if (rf == INTRA_FRAME) {
444 #ifdef ENTROPY_STATS
445     active_section = 6;
446 #endif
447
448     if (bsize >= BLOCK_SIZE_SB8X8) {
449       write_intra_mode(bc, mode, pc->fc.y_mode_prob[size_group_lookup[bsize]]);
450     } else {
451       int idx, idy;
452       const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
453       const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
454       for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
455         for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
456           const MB_PREDICTION_MODE bm = m->bmi[idy * 2 + idx].as_mode;
457           write_intra_mode(bc, bm, pc->fc.y_mode_prob[0]);
458         }
459       }
460     }
461     write_intra_mode(bc, mi->uv_mode, pc->fc.uv_mode_prob[mode]);
462   } else {
463     vp9_prob *mv_ref_p;
464     encode_ref_frame(cpi, bc);
465     mv_ref_p = cpi->common.fc.inter_mode_probs[mi->mb_mode_context[rf]];
466
467 #ifdef ENTROPY_STATS
468     active_section = 3;
469 #endif
470
471     // If segment skip is not enabled code the mode.
472     if (!vp9_segfeature_active(seg, segment_id, SEG_LVL_SKIP)) {
473       if (bsize >= BLOCK_SIZE_SB8X8) {
474         write_sb_mv_ref(bc, mode, mv_ref_p);
475         ++pc->counts.inter_mode[mi->mb_mode_context[rf]]
476                                [inter_mode_offset(mode)];
477       }
478     }
479
480     if (cpi->common.mcomp_filter_type == SWITCHABLE) {
481       write_token(bc, vp9_switchable_interp_tree,
482                   vp9_get_pred_probs_switchable_interp(&cpi->common, xd),
483                   vp9_switchable_interp_encodings +
484                   vp9_switchable_interp_map[mi->interp_filter]);
485     } else {
486       assert(mi->interp_filter == cpi->common.mcomp_filter_type);
487     }
488
489     if (bsize < BLOCK_SIZE_SB8X8) {
490       int j;
491       MB_PREDICTION_MODE blockmode;
492       int_mv blockmv;
493       const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
494       const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
495       int idx, idy;
496       for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
497         for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
498           j = idy * 2 + idx;
499           blockmode = x->partition_info->bmi[j].mode;
500           blockmv = m->bmi[j].as_mv[0];
501           write_sb_mv_ref(bc, blockmode, mv_ref_p);
502           ++pc->counts.inter_mode[mi->mb_mode_context[rf]]
503                                  [inter_mode_offset(blockmode)];
504
505           if (blockmode == NEWMV) {
506 #ifdef ENTROPY_STATS
507             active_section = 11;
508 #endif
509             vp9_encode_mv(cpi, bc, &blockmv.as_mv, &mi->best_mv.as_mv,
510                           nmvc, allow_hp);
511
512             if (mi->ref_frame[1] > INTRA_FRAME)
513               vp9_encode_mv(cpi, bc,
514                             &m->bmi[j].as_mv[1].as_mv,
515                             &mi->best_second_mv.as_mv,
516                             nmvc, allow_hp);
517           }
518         }
519       }
520     } else if (mode == NEWMV) {
521 #ifdef ENTROPY_STATS
522       active_section = 5;
523 #endif
524       vp9_encode_mv(cpi, bc, &mi->mv[0].as_mv, &mi->best_mv.as_mv,
525                     nmvc, allow_hp);
526
527       if (mi->ref_frame[1] > INTRA_FRAME)
528         vp9_encode_mv(cpi, bc, &mi->mv[1].as_mv, &mi->best_second_mv.as_mv,
529                       nmvc, allow_hp);
530     }
531   }
532 }
533
534 static void write_mb_modes_kf(const VP9_COMP *cpi, MODE_INFO *m,
535                               vp9_writer *bc) {
536   const VP9_COMMON *const c = &cpi->common;
537   const MACROBLOCKD *const xd = &cpi->mb.e_mbd;
538   const int ym = m->mbmi.mode;
539   const int mis = c->mode_info_stride;
540   const int segment_id = m->mbmi.segment_id;
541
542   if (xd->seg.update_map)
543     write_segment_id(bc, &xd->seg, m->mbmi.segment_id);
544
545   write_skip_coeff(cpi, segment_id, m, bc);
546
547   if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8 && c->tx_mode == TX_MODE_SELECT)
548     write_selected_tx_size(cpi, m->mbmi.txfm_size, m->mbmi.sb_type, bc);
549
550   if (m->mbmi.sb_type >= BLOCK_SIZE_SB8X8) {
551     const MB_PREDICTION_MODE A = above_block_mode(m, 0, mis);
552     const MB_PREDICTION_MODE L = xd->left_available ?
553                                  left_block_mode(m, 0) : DC_PRED;
554     write_intra_mode(bc, ym, vp9_kf_y_mode_prob[A][L]);
555   } else {
556     int idx, idy;
557     const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[m->mbmi.sb_type];
558     const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[m->mbmi.sb_type];
559     for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
560       for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
561         const int i = idy * 2 + idx;
562         const MB_PREDICTION_MODE A = above_block_mode(m, i, mis);
563         const MB_PREDICTION_MODE L = (xd->left_available || idx) ?
564                                      left_block_mode(m, i) : DC_PRED;
565         const int bm = m->bmi[i].as_mode;
566 #ifdef ENTROPY_STATS
567         ++intra_mode_stats[A][L][bm];
568 #endif
569         write_intra_mode(bc, bm, vp9_kf_y_mode_prob[A][L]);
570       }
571     }
572   }
573
574   write_intra_mode(bc, m->mbmi.uv_mode, vp9_kf_uv_mode_prob[ym]);
575 }
576
577 static void write_modes_b(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
578                           TOKENEXTRA **tok, TOKENEXTRA *tok_end,
579                           int mi_row, int mi_col) {
580   VP9_COMMON *const cm = &cpi->common;
581   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
582
583   if (m->mbmi.sb_type < BLOCK_SIZE_SB8X8)
584     if (xd->ab_index > 0)
585       return;
586   xd->mode_info_context = m;
587   set_mi_row_col(&cpi->common, xd, mi_row,
588                  1 << mi_height_log2(m->mbmi.sb_type),
589                  mi_col, 1 << mi_width_log2(m->mbmi.sb_type));
590   if ((cm->frame_type == KEY_FRAME) || cm->intra_only) {
591     write_mb_modes_kf(cpi, m, bc);
592 #ifdef ENTROPY_STATS
593     active_section = 8;
594 #endif
595   } else {
596     pack_inter_mode_mvs(cpi, m, bc);
597 #ifdef ENTROPY_STATS
598     active_section = 1;
599 #endif
600   }
601
602   assert(*tok < tok_end);
603   pack_mb_tokens(bc, tok, tok_end);
604 }
605
606 static void write_modes_sb(VP9_COMP *cpi, MODE_INFO *m, vp9_writer *bc,
607                            TOKENEXTRA **tok, TOKENEXTRA *tok_end,
608                            int mi_row, int mi_col,
609                            BLOCK_SIZE_TYPE bsize) {
610   VP9_COMMON *const cm = &cpi->common;
611   MACROBLOCKD *xd = &cpi->mb.e_mbd;
612   const int mis = cm->mode_info_stride;
613   int bsl = b_width_log2(bsize);
614   int bs = (1 << bsl) / 4;  // mode_info step for subsize
615   int n;
616   PARTITION_TYPE partition = PARTITION_NONE;
617   BLOCK_SIZE_TYPE subsize;
618
619   if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
620     return;
621
622   partition = partition_lookup[bsl][m->mbmi.sb_type];
623
624   if (bsize < BLOCK_SIZE_SB8X8)
625     if (xd->ab_index > 0)
626       return;
627
628   if (bsize >= BLOCK_SIZE_SB8X8) {
629     int pl;
630     const int idx = check_bsize_coverage(cm, mi_row, mi_col, bsize);
631     set_partition_seg_context(cm, xd, mi_row, mi_col);
632     pl = partition_plane_context(xd, bsize);
633     // encode the partition information
634     if (idx == 0)
635       write_token(bc, vp9_partition_tree,
636                   cm->fc.partition_prob[cm->frame_type][pl],
637                   vp9_partition_encodings + partition);
638     else if (idx > 0)
639       vp9_write(bc, partition == PARTITION_SPLIT,
640                 cm->fc.partition_prob[cm->frame_type][pl][idx]);
641   }
642
643   subsize = get_subsize(bsize, partition);
644   *(get_sb_index(xd, subsize)) = 0;
645
646   switch (partition) {
647     case PARTITION_NONE:
648       write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
649       break;
650     case PARTITION_HORZ:
651       write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
652       *(get_sb_index(xd, subsize)) = 1;
653       if ((mi_row + bs) < cm->mi_rows)
654         write_modes_b(cpi, m + bs * mis, bc, tok, tok_end, mi_row + bs, mi_col);
655       break;
656     case PARTITION_VERT:
657       write_modes_b(cpi, m, bc, tok, tok_end, mi_row, mi_col);
658       *(get_sb_index(xd, subsize)) = 1;
659       if ((mi_col + bs) < cm->mi_cols)
660         write_modes_b(cpi, m + bs, bc, tok, tok_end, mi_row, mi_col + bs);
661       break;
662     case PARTITION_SPLIT:
663       for (n = 0; n < 4; n++) {
664         int j = n >> 1, i = n & 0x01;
665         *(get_sb_index(xd, subsize)) = n;
666         write_modes_sb(cpi, m + j * bs * mis + i * bs, bc, tok, tok_end,
667                        mi_row + j * bs, mi_col + i * bs, subsize);
668       }
669       break;
670     default:
671       assert(0);
672   }
673
674   // update partition context
675   if (bsize >= BLOCK_SIZE_SB8X8 &&
676       (bsize == BLOCK_SIZE_SB8X8 || partition != PARTITION_SPLIT)) {
677     set_partition_seg_context(cm, xd, mi_row, mi_col);
678     update_partition_context(xd, subsize, bsize);
679   }
680 }
681
682 static void write_modes(VP9_COMP *cpi, vp9_writer* const bc,
683                         TOKENEXTRA **tok, TOKENEXTRA *tok_end) {
684   VP9_COMMON *const c = &cpi->common;
685   const int mis = c->mode_info_stride;
686   MODE_INFO *m, *m_ptr = c->mi;
687   int mi_row, mi_col;
688
689   m_ptr += c->cur_tile_mi_col_start + c->cur_tile_mi_row_start * mis;
690
691   for (mi_row = c->cur_tile_mi_row_start; mi_row < c->cur_tile_mi_row_end;
692        mi_row += 8, m_ptr += 8 * mis) {
693     m = m_ptr;
694     vp9_zero(c->left_seg_context);
695     for (mi_col = c->cur_tile_mi_col_start; mi_col < c->cur_tile_mi_col_end;
696          mi_col += MI_BLOCK_SIZE, m += MI_BLOCK_SIZE)
697       write_modes_sb(cpi, m, bc, tok, tok_end, mi_row, mi_col, BLOCK_64X64);
698   }
699 }
700
701 /* This function is used for debugging probability trees. */
702 static void print_prob_tree(vp9_coeff_probs *coef_probs, int block_types) {
703   /* print coef probability tree */
704   int i, j, k, l, m;
705   FILE *f = fopen("enc_tree_probs.txt", "a");
706   fprintf(f, "{\n");
707   for (i = 0; i < block_types; i++) {
708     fprintf(f, "  {\n");
709     for (j = 0; j < REF_TYPES; ++j) {
710       fprintf(f, "  {\n");
711       for (k = 0; k < COEF_BANDS; k++) {
712         fprintf(f, "    {\n");
713         for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
714           fprintf(f, "      {");
715           for (m = 0; m < ENTROPY_NODES; m++) {
716             fprintf(f, "%3u, ",
717                     (unsigned int)(coef_probs[i][j][k][l][m]));
718           }
719         }
720         fprintf(f, " }\n");
721       }
722       fprintf(f, "    }\n");
723     }
724     fprintf(f, "  }\n");
725   }
726   fprintf(f, "}\n");
727   fclose(f);
728 }
729
730 static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE tx_size) {
731   vp9_coeff_probs_model *coef_probs = cpi->frame_coef_probs[tx_size];
732   vp9_coeff_count *coef_counts = cpi->coef_counts[tx_size];
733   unsigned int (*eob_branch_ct)[REF_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS] =
734       cpi->common.counts.eob_branch[tx_size];
735   vp9_coeff_stats *coef_branch_ct = cpi->frame_branch_ct[tx_size];
736   vp9_prob full_probs[ENTROPY_NODES];
737   int i, j, k, l;
738
739   for (i = 0; i < BLOCK_TYPES; ++i) {
740     for (j = 0; j < REF_TYPES; ++j) {
741       for (k = 0; k < COEF_BANDS; ++k) {
742         for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
743           if (l >= 3 && k == 0)
744             continue;
745           vp9_tree_probs_from_distribution(vp9_coef_tree,
746                                            full_probs,
747                                            coef_branch_ct[i][j][k][l],
748                                            coef_counts[i][j][k][l], 0);
749           vpx_memcpy(coef_probs[i][j][k][l], full_probs,
750                      sizeof(vp9_prob) * UNCONSTRAINED_NODES);
751           coef_branch_ct[i][j][k][l][0][1] = eob_branch_ct[i][j][k][l] -
752                                              coef_branch_ct[i][j][k][l][0][0];
753           coef_probs[i][j][k][l][0] =
754               get_binary_prob(coef_branch_ct[i][j][k][l][0][0],
755                               coef_branch_ct[i][j][k][l][0][1]);
756 #ifdef ENTROPY_STATS
757           if (!cpi->dummy_packing) {
758             int t;
759             for (t = 0; t < MAX_ENTROPY_TOKENS; ++t)
760               context_counters[tx_size][i][j][k][l][t] +=
761                   coef_counts[i][j][k][l][t];
762             context_counters[tx_size][i][j][k][l][MAX_ENTROPY_TOKENS] +=
763                 eob_branch_ct[i][j][k][l];
764           }
765 #endif
766         }
767       }
768     }
769   }
770 }
771
772 static void build_coeff_contexts(VP9_COMP *cpi) {
773   TX_SIZE t;
774   for (t = TX_4X4; t <= TX_32X32; t++)
775     build_tree_distribution(cpi, t);
776 }
777
778 static void update_coef_probs_common(vp9_writer* const bc, VP9_COMP *cpi,
779                                      TX_SIZE tx_size) {
780   vp9_coeff_probs_model *new_frame_coef_probs = cpi->frame_coef_probs[tx_size];
781   vp9_coeff_probs_model *old_frame_coef_probs =
782       cpi->common.fc.coef_probs[tx_size];
783   vp9_coeff_stats *frame_branch_ct = cpi->frame_branch_ct[tx_size];
784   int i, j, k, l, t;
785   int update[2] = {0, 0};
786   int savings;
787
788   const int entropy_nodes_update = UNCONSTRAINED_NODES;
789
790   const int tstart = 0;
791   /* dry run to see if there is any udpate at all needed */
792   savings = 0;
793   for (i = 0; i < BLOCK_TYPES; ++i) {
794     for (j = 0; j < REF_TYPES; ++j) {
795       for (k = 0; k < COEF_BANDS; ++k) {
796         // int prev_coef_savings[ENTROPY_NODES] = {0};
797         for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
798           for (t = tstart; t < entropy_nodes_update; ++t) {
799             vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
800             const vp9_prob oldp = old_frame_coef_probs[i][j][k][l][t];
801             const vp9_prob upd = VP9_COEF_UPDATE_PROB;
802             int s;
803             int u = 0;
804
805             if (l >= 3 && k == 0)
806               continue;
807             if (t == PIVOT_NODE)
808               s = vp9_prob_diff_update_savings_search_model(
809                   frame_branch_ct[i][j][k][l][0],
810                   old_frame_coef_probs[i][j][k][l], &newp, upd, i, j);
811             else
812               s = vp9_prob_diff_update_savings_search(
813                   frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
814             if (s > 0 && newp != oldp)
815               u = 1;
816             if (u)
817               savings += s - (int)(vp9_cost_zero(upd));
818             else
819               savings -= (int)(vp9_cost_zero(upd));
820             update[u]++;
821           }
822         }
823       }
824     }
825   }
826
827   // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
828   /* Is coef updated at all */
829   if (update[1] == 0 || savings < 0) {
830     vp9_write_bit(bc, 0);
831     return;
832   }
833   vp9_write_bit(bc, 1);
834   for (i = 0; i < BLOCK_TYPES; ++i) {
835     for (j = 0; j < REF_TYPES; ++j) {
836       for (k = 0; k < COEF_BANDS; ++k) {
837         // int prev_coef_savings[ENTROPY_NODES] = {0};
838         for (l = 0; l < PREV_COEF_CONTEXTS; ++l) {
839           // calc probs and branch cts for this frame only
840           for (t = tstart; t < entropy_nodes_update; ++t) {
841             vp9_prob newp = new_frame_coef_probs[i][j][k][l][t];
842             vp9_prob *oldp = old_frame_coef_probs[i][j][k][l] + t;
843             const vp9_prob upd = VP9_COEF_UPDATE_PROB;
844             int s;
845             int u = 0;
846             if (l >= 3 && k == 0)
847               continue;
848             if (t == PIVOT_NODE)
849               s = vp9_prob_diff_update_savings_search_model(
850                   frame_branch_ct[i][j][k][l][0],
851                   old_frame_coef_probs[i][j][k][l], &newp, upd, i, j);
852             else
853               s = vp9_prob_diff_update_savings_search(
854                   frame_branch_ct[i][j][k][l][t],
855                   *oldp, &newp, upd);
856             if (s > 0 && newp != *oldp)
857               u = 1;
858             vp9_write(bc, u, upd);
859 #ifdef ENTROPY_STATS
860             if (!cpi->dummy_packing)
861               ++tree_update_hist[tx_size][i][j][k][l][t][u];
862 #endif
863             if (u) {
864               /* send/use new probability */
865               vp9_write_prob_diff_update(bc, newp, *oldp);
866               *oldp = newp;
867             }
868           }
869         }
870       }
871     }
872   }
873 }
874
875 static void update_coef_probs(VP9_COMP* const cpi, vp9_writer* const bc) {
876   const TX_MODE tx_mode = cpi->common.tx_mode;
877
878   vp9_clear_system_state();
879
880   // Build the cofficient contexts based on counts collected in encode loop
881   build_coeff_contexts(cpi);
882
883   update_coef_probs_common(bc, cpi, TX_4X4);
884
885   // do not do this if not even allowed
886   if (tx_mode > ONLY_4X4)
887     update_coef_probs_common(bc, cpi, TX_8X8);
888
889   if (tx_mode > ALLOW_8X8)
890     update_coef_probs_common(bc, cpi, TX_16X16);
891
892   if (tx_mode > ALLOW_16X16)
893     update_coef_probs_common(bc, cpi, TX_32X32);
894 }
895
896 static void encode_loopfilter(struct loopfilter *lf,
897                               struct vp9_write_bit_buffer *wb) {
898   int i;
899
900   // Encode the loop filter level and type
901   vp9_wb_write_literal(wb, lf->filter_level, 6);
902   vp9_wb_write_literal(wb, lf->sharpness_level, 3);
903
904   // Write out loop filter deltas applied at the MB level based on mode or
905   // ref frame (if they are enabled).
906   vp9_wb_write_bit(wb, lf->mode_ref_delta_enabled);
907
908   if (lf->mode_ref_delta_enabled) {
909     // Do the deltas need to be updated
910     vp9_wb_write_bit(wb, lf->mode_ref_delta_update);
911     if (lf->mode_ref_delta_update) {
912       // Send update
913       for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
914         const int delta = lf->ref_deltas[i];
915
916         // Frame level data
917         if (delta != lf->last_ref_deltas[i]) {
918           lf->last_ref_deltas[i] = delta;
919           vp9_wb_write_bit(wb, 1);
920
921           assert(delta != 0);
922           vp9_wb_write_literal(wb, abs(delta) & 0x3F, 6);
923           vp9_wb_write_bit(wb, delta < 0);
924         } else {
925           vp9_wb_write_bit(wb, 0);
926         }
927       }
928
929       // Send update
930       for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
931         const int delta = lf->mode_deltas[i];
932         if (delta != lf->last_mode_deltas[i]) {
933           lf->last_mode_deltas[i] = delta;
934           vp9_wb_write_bit(wb, 1);
935
936           assert(delta != 0);
937           vp9_wb_write_literal(wb, abs(delta) & 0x3F, 6);
938           vp9_wb_write_bit(wb, delta < 0);
939         } else {
940           vp9_wb_write_bit(wb, 0);
941         }
942       }
943     }
944   }
945 }
946
947 static void write_delta_q(struct vp9_write_bit_buffer *wb, int delta_q) {
948   if (delta_q != 0) {
949     vp9_wb_write_bit(wb, 1);
950     vp9_wb_write_literal(wb, abs(delta_q), 4);
951     vp9_wb_write_bit(wb, delta_q < 0);
952   } else {
953     vp9_wb_write_bit(wb, 0);
954   }
955 }
956
957 static void encode_quantization(VP9_COMMON *cm,
958                                 struct vp9_write_bit_buffer *wb) {
959   vp9_wb_write_literal(wb, cm->base_qindex, QINDEX_BITS);
960   write_delta_q(wb, cm->y_dc_delta_q);
961   write_delta_q(wb, cm->uv_dc_delta_q);
962   write_delta_q(wb, cm->uv_ac_delta_q);
963 }
964
965
966 static void encode_segmentation(VP9_COMP *cpi,
967                                 struct vp9_write_bit_buffer *wb) {
968   int i, j;
969
970   struct segmentation *seg = &cpi->mb.e_mbd.seg;
971
972   vp9_wb_write_bit(wb, seg->enabled);
973   if (!seg->enabled)
974     return;
975
976   // Segmentation map
977   vp9_wb_write_bit(wb, seg->update_map);
978   if (seg->update_map) {
979     // Select the coding strategy (temporal or spatial)
980     vp9_choose_segmap_coding_method(cpi);
981     // Write out probabilities used to decode unpredicted  macro-block segments
982     for (i = 0; i < SEG_TREE_PROBS; i++) {
983       const int prob = seg->tree_probs[i];
984       const int update = prob != MAX_PROB;
985       vp9_wb_write_bit(wb, update);
986       if (update)
987         vp9_wb_write_literal(wb, prob, 8);
988     }
989
990     // Write out the chosen coding method.
991     vp9_wb_write_bit(wb, seg->temporal_update);
992     if (seg->temporal_update) {
993       for (i = 0; i < PREDICTION_PROBS; i++) {
994         const int prob = seg->pred_probs[i];
995         const int update = prob != MAX_PROB;
996         vp9_wb_write_bit(wb, update);
997         if (update)
998           vp9_wb_write_literal(wb, prob, 8);
999       }
1000     }
1001   }
1002
1003   // Segmentation data
1004   vp9_wb_write_bit(wb, seg->update_data);
1005   if (seg->update_data) {
1006     vp9_wb_write_bit(wb, seg->abs_delta);
1007
1008     for (i = 0; i < MAX_SEGMENTS; i++) {
1009       for (j = 0; j < SEG_LVL_MAX; j++) {
1010         const int active = vp9_segfeature_active(seg, i, j);
1011         vp9_wb_write_bit(wb, active);
1012         if (active) {
1013           const int data = vp9_get_segdata(seg, i, j);
1014           const int data_max = vp9_seg_feature_data_max(j);
1015
1016           if (vp9_is_segfeature_signed(j)) {
1017             vp9_encode_unsigned_max(wb, abs(data), data_max);
1018             vp9_wb_write_bit(wb, data < 0);
1019           } else {
1020             vp9_encode_unsigned_max(wb, data, data_max);
1021           }
1022         }
1023       }
1024     }
1025   }
1026 }
1027
1028
1029 static void encode_txfm_probs(VP9_COMP *cpi, vp9_writer *w) {
1030   VP9_COMMON *const cm = &cpi->common;
1031
1032   // Mode
1033   vp9_write_literal(w, MIN(cm->tx_mode, ALLOW_32X32), 2);
1034   if (cm->tx_mode >= ALLOW_32X32)
1035     vp9_write_bit(w, cm->tx_mode == TX_MODE_SELECT);
1036
1037   // Probabilities
1038   if (cm->tx_mode == TX_MODE_SELECT) {
1039     int i, j;
1040     unsigned int ct_8x8p[TX_SIZES - 3][2];
1041     unsigned int ct_16x16p[TX_SIZES - 2][2];
1042     unsigned int ct_32x32p[TX_SIZES - 1][2];
1043
1044
1045     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
1046       tx_counts_to_branch_counts_8x8(cm->counts.tx.p8x8[i],
1047                                      ct_8x8p);
1048       for (j = 0; j < TX_SIZES - 3; j++)
1049         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p8x8[i][j],
1050                                   VP9_MODE_UPDATE_PROB, ct_8x8p[j]);
1051     }
1052
1053     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
1054       tx_counts_to_branch_counts_16x16(cm->counts.tx.p16x16[i],
1055                                        ct_16x16p);
1056       for (j = 0; j < TX_SIZES - 2; j++)
1057         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p16x16[i][j],
1058                                   VP9_MODE_UPDATE_PROB, ct_16x16p[j]);
1059     }
1060
1061     for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
1062       tx_counts_to_branch_counts_32x32(cm->counts.tx.p32x32[i], ct_32x32p);
1063       for (j = 0; j < TX_SIZES - 1; j++)
1064         vp9_cond_prob_diff_update(w, &cm->fc.tx_probs.p32x32[i][j],
1065                                   VP9_MODE_UPDATE_PROB, ct_32x32p[j]);
1066     }
1067 #ifdef MODE_STATS
1068     if (!cpi->dummy_packing)
1069       update_tx_count_stats(cm);
1070 #endif
1071   }
1072 }
1073
1074 static void write_interp_filter_type(INTERPOLATIONFILTERTYPE type,
1075                                      struct vp9_write_bit_buffer *wb) {
1076   vp9_wb_write_bit(wb, type == SWITCHABLE);
1077   if (type != SWITCHABLE)
1078     vp9_wb_write_literal(wb, type, 2);
1079 }
1080
1081 static void fix_mcomp_filter_type(VP9_COMP *cpi) {
1082   VP9_COMMON *const cm = &cpi->common;
1083
1084   if (cm->mcomp_filter_type == SWITCHABLE) {
1085     // Check to see if only one of the filters is actually used
1086     int count[VP9_SWITCHABLE_FILTERS];
1087     int i, j, c = 0;
1088     for (i = 0; i < VP9_SWITCHABLE_FILTERS; ++i) {
1089       count[i] = 0;
1090       for (j = 0; j <= VP9_SWITCHABLE_FILTERS; ++j)
1091         count[i] += cm->counts.switchable_interp[j][i];
1092       c += (count[i] > 0);
1093     }
1094     if (c == 1) {
1095       // Only one filter is used. So set the filter at frame level
1096       for (i = 0; i < VP9_SWITCHABLE_FILTERS; ++i) {
1097         if (count[i]) {
1098           cm->mcomp_filter_type = vp9_switchable_interp[i];
1099           break;
1100         }
1101       }
1102     }
1103   }
1104 }
1105
1106 static void write_tile_info(VP9_COMMON *cm, struct vp9_write_bit_buffer *wb) {
1107   int min_log2_tile_cols, max_log2_tile_cols, ones;
1108   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
1109
1110   // columns
1111   ones = cm->log2_tile_cols - min_log2_tile_cols;
1112   while (ones--)
1113     vp9_wb_write_bit(wb, 1);
1114
1115   if (cm->log2_tile_cols < max_log2_tile_cols)
1116     vp9_wb_write_bit(wb, 0);
1117
1118   // rows
1119   vp9_wb_write_bit(wb, cm->log2_tile_rows != 0);
1120   if (cm->log2_tile_rows != 0)
1121     vp9_wb_write_bit(wb, cm->log2_tile_rows != 1);
1122 }
1123
1124 static int get_refresh_mask(VP9_COMP *cpi) {
1125     // Should the GF or ARF be updated using the transmitted frame or buffer
1126 #if CONFIG_MULTIPLE_ARF
1127     if (!cpi->multi_arf_enabled && cpi->refresh_golden_frame &&
1128         !cpi->refresh_alt_ref_frame) {
1129 #else
1130     if (cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame) {
1131 #endif
1132       // Preserve the previously existing golden frame and update the frame in
1133       // the alt ref slot instead. This is highly specific to the use of
1134       // alt-ref as a forward reference, and this needs to be generalized as
1135       // other uses are implemented (like RTC/temporal scaling)
1136       //
1137       // gld_fb_idx and alt_fb_idx need to be swapped for future frames, but
1138       // that happens in vp9_onyx_if.c:update_reference_frames() so that it can
1139       // be done outside of the recode loop.
1140       return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
1141              (cpi->refresh_golden_frame << cpi->alt_fb_idx);
1142     } else {
1143       int arf_idx = cpi->alt_fb_idx;
1144 #if CONFIG_MULTIPLE_ARF
1145       // Determine which ARF buffer to use to encode this ARF frame.
1146       if (cpi->multi_arf_enabled) {
1147         int sn = cpi->sequence_number;
1148         arf_idx = (cpi->frame_coding_order[sn] < 0) ?
1149             cpi->arf_buffer_idx[sn + 1] :
1150             cpi->arf_buffer_idx[sn];
1151       }
1152 #endif
1153       return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
1154              (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
1155              (cpi->refresh_alt_ref_frame << arf_idx);
1156     }
1157 }
1158
1159 static size_t encode_tiles(VP9_COMP *cpi, uint8_t *data_ptr) {
1160   VP9_COMMON *const cm = &cpi->common;
1161   vp9_writer residual_bc;
1162
1163   int tile_row, tile_col;
1164   TOKENEXTRA *tok[4][1 << 6], *tok_end;
1165   size_t total_size = 0;
1166   const int tile_cols = 1 << cm->log2_tile_cols;
1167   const int tile_rows = 1 << cm->log2_tile_rows;
1168
1169   vpx_memset(cm->above_seg_context, 0, sizeof(PARTITION_CONTEXT) *
1170              mi_cols_aligned_to_sb(cm->mi_cols));
1171
1172   tok[0][0] = cpi->tok;
1173   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
1174     if (tile_row)
1175       tok[tile_row][0] = tok[tile_row - 1][tile_cols - 1] +
1176                          cpi->tok_count[tile_row - 1][tile_cols - 1];
1177
1178     for (tile_col = 1; tile_col < tile_cols; tile_col++)
1179       tok[tile_row][tile_col] = tok[tile_row][tile_col - 1] +
1180                                 cpi->tok_count[tile_row][tile_col - 1];
1181   }
1182
1183   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
1184     vp9_get_tile_row_offsets(cm, tile_row);
1185     for (tile_col = 0; tile_col < tile_cols; tile_col++) {
1186       vp9_get_tile_col_offsets(cm, tile_col);
1187       tok_end = tok[tile_row][tile_col] + cpi->tok_count[tile_row][tile_col];
1188
1189       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1)
1190         vp9_start_encode(&residual_bc, data_ptr + total_size + 4);
1191       else
1192         vp9_start_encode(&residual_bc, data_ptr + total_size);
1193
1194       write_modes(cpi, &residual_bc, &tok[tile_row][tile_col], tok_end);
1195       assert(tok[tile_row][tile_col] == tok_end);
1196       vp9_stop_encode(&residual_bc);
1197       if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1) {
1198         // size of this tile
1199         write_be32(data_ptr + total_size, residual_bc.pos);
1200         total_size += 4;
1201       }
1202
1203       total_size += residual_bc.pos;
1204     }
1205   }
1206
1207   return total_size;
1208 }
1209
1210 static void write_display_size(VP9_COMP *cpi, struct vp9_write_bit_buffer *wb) {
1211   VP9_COMMON *const cm = &cpi->common;
1212
1213   const int scaling_active = cm->width != cm->display_width ||
1214                              cm->height != cm->display_height;
1215   vp9_wb_write_bit(wb, scaling_active);
1216   if (scaling_active) {
1217     vp9_wb_write_literal(wb, cm->display_width - 1, 16);
1218     vp9_wb_write_literal(wb, cm->display_height - 1, 16);
1219   }
1220 }
1221
1222 static void write_frame_size(VP9_COMP *cpi,
1223                              struct vp9_write_bit_buffer *wb) {
1224   VP9_COMMON *const cm = &cpi->common;
1225   vp9_wb_write_literal(wb, cm->width - 1, 16);
1226   vp9_wb_write_literal(wb, cm->height - 1, 16);
1227
1228   write_display_size(cpi, wb);
1229 }
1230
1231 static void write_frame_size_with_refs(VP9_COMP *cpi,
1232                                        struct vp9_write_bit_buffer *wb) {
1233   VP9_COMMON *const cm = &cpi->common;
1234   int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
1235                                       cpi->alt_fb_idx};
1236   int i, found = 0;
1237
1238   for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
1239     YV12_BUFFER_CONFIG *cfg = &cm->yv12_fb[cm->ref_frame_map[refs[i]]];
1240     found = cm->width == cfg->y_crop_width &&
1241             cm->height == cfg->y_crop_height;
1242     vp9_wb_write_bit(wb, found);
1243     if (found)
1244       break;
1245   }
1246
1247   if (!found) {
1248     vp9_wb_write_literal(wb, cm->width - 1, 16);
1249     vp9_wb_write_literal(wb, cm->height - 1, 16);
1250   }
1251
1252   write_display_size(cpi, wb);
1253 }
1254
1255 static void write_sync_code(struct vp9_write_bit_buffer *wb) {
1256   vp9_wb_write_literal(wb, SYNC_CODE_0, 8);
1257   vp9_wb_write_literal(wb, SYNC_CODE_1, 8);
1258   vp9_wb_write_literal(wb, SYNC_CODE_2, 8);
1259 }
1260
1261 static void write_uncompressed_header(VP9_COMP *cpi,
1262                                       struct vp9_write_bit_buffer *wb) {
1263   VP9_COMMON *const cm = &cpi->common;
1264   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1265
1266   // frame marker bits
1267   vp9_wb_write_literal(wb, 0x2, 2);
1268
1269   // bitstream version.
1270   // 00 - profile 0. 4:2:0 only
1271   // 10 - profile 1. adds 4:4:4, 4:2:2, alpha
1272   vp9_wb_write_bit(wb, cm->version);
1273   vp9_wb_write_bit(wb, 0);
1274
1275   vp9_wb_write_bit(wb, 0);
1276   vp9_wb_write_bit(wb, cm->frame_type);
1277   vp9_wb_write_bit(wb, cm->show_frame);
1278   vp9_wb_write_bit(wb, cm->error_resilient_mode);
1279
1280   if (cm->frame_type == KEY_FRAME) {
1281     write_sync_code(wb);
1282     // colorspaces
1283     // 000 - Unknown
1284     // 001 - BT.601
1285     // 010 - BT.709
1286     // 011 - SMPTE-170
1287     // 100 - SMPTE-240
1288     // 101 - Reserved
1289     // 110 - Reserved
1290     // 111 - sRGB (RGB)
1291     vp9_wb_write_literal(wb, 0, 3);
1292     if (1 /* colorspace != sRGB */) {
1293       vp9_wb_write_bit(wb, 0);  // 0: [16, 235] (i.e. xvYCC), 1: [0, 255]
1294       if (cm->version == 1) {
1295         vp9_wb_write_bit(wb, cm->subsampling_x);
1296         vp9_wb_write_bit(wb, cm->subsampling_y);
1297         vp9_wb_write_bit(wb, 0);  // has extra plane
1298       }
1299     } else {
1300       assert(cm->version == 1);
1301       vp9_wb_write_bit(wb, 0);  // has extra plane
1302     }
1303
1304     write_frame_size(cpi, wb);
1305   } else {
1306     const int refs[ALLOWED_REFS_PER_FRAME] = {cpi->lst_fb_idx, cpi->gld_fb_idx,
1307                                               cpi->alt_fb_idx};
1308     if (!cm->show_frame)
1309       vp9_wb_write_bit(wb, cm->intra_only);
1310
1311     if (!cm->error_resilient_mode)
1312       vp9_wb_write_literal(wb, cm->reset_frame_context, 2);
1313
1314     if (cm->intra_only) {
1315       write_sync_code(wb);
1316
1317       vp9_wb_write_literal(wb, get_refresh_mask(cpi), NUM_REF_FRAMES);
1318       write_frame_size(cpi, wb);
1319     } else {
1320       int i;
1321       vp9_wb_write_literal(wb, get_refresh_mask(cpi), NUM_REF_FRAMES);
1322       for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
1323         vp9_wb_write_literal(wb, refs[i], NUM_REF_FRAMES_LOG2);
1324         vp9_wb_write_bit(wb, cm->ref_frame_sign_bias[LAST_FRAME + i]);
1325       }
1326
1327       write_frame_size_with_refs(cpi, wb);
1328
1329       vp9_wb_write_bit(wb, xd->allow_high_precision_mv);
1330
1331       fix_mcomp_filter_type(cpi);
1332       write_interp_filter_type(cm->mcomp_filter_type, wb);
1333     }
1334   }
1335
1336   if (!cm->error_resilient_mode) {
1337     vp9_wb_write_bit(wb, cm->refresh_frame_context);
1338     vp9_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
1339   }
1340
1341   vp9_wb_write_literal(wb, cm->frame_context_idx, NUM_FRAME_CONTEXTS_LOG2);
1342
1343   encode_loopfilter(&xd->lf, wb);
1344   encode_quantization(cm, wb);
1345   encode_segmentation(cpi, wb);
1346
1347   write_tile_info(cm, wb);
1348 }
1349
1350 static size_t write_compressed_header(VP9_COMP *cpi, uint8_t *data) {
1351   VP9_COMMON *const cm = &cpi->common;
1352   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1353   FRAME_CONTEXT *const fc = &cm->fc;
1354   vp9_writer header_bc;
1355
1356   vp9_start_encode(&header_bc, data);
1357
1358   if (xd->lossless)
1359     cm->tx_mode = ONLY_4X4;
1360   else
1361     encode_txfm_probs(cpi, &header_bc);
1362
1363   update_coef_probs(cpi, &header_bc);
1364
1365 #ifdef ENTROPY_STATS
1366   active_section = 2;
1367 #endif
1368
1369   vp9_update_skip_probs(cpi, &header_bc);
1370
1371   if (cm->frame_type != KEY_FRAME) {
1372     int i;
1373 #ifdef ENTROPY_STATS
1374     active_section = 1;
1375 #endif
1376
1377     update_inter_mode_probs(cm, &header_bc);
1378     vp9_zero(cm->counts.inter_mode);
1379
1380     if (cm->mcomp_filter_type == SWITCHABLE)
1381       update_switchable_interp_probs(cpi, &header_bc);
1382
1383     for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1384       vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i],
1385                                 VP9_MODE_UPDATE_PROB,
1386                                 cpi->intra_inter_count[i]);
1387
1388     if (cm->allow_comp_inter_inter) {
1389       const int comp_pred_mode = cpi->common.comp_pred_mode;
1390       const int use_compound_pred = comp_pred_mode != SINGLE_PREDICTION_ONLY;
1391       const int use_hybrid_pred = comp_pred_mode == HYBRID_PREDICTION;
1392
1393       vp9_write_bit(&header_bc, use_compound_pred);
1394       if (use_compound_pred) {
1395         vp9_write_bit(&header_bc, use_hybrid_pred);
1396         if (use_hybrid_pred)
1397           for (i = 0; i < COMP_INTER_CONTEXTS; i++)
1398             vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i],
1399                                       VP9_MODE_UPDATE_PROB,
1400                                       cpi->comp_inter_count[i]);
1401       }
1402     }
1403
1404     if (cm->comp_pred_mode != COMP_PREDICTION_ONLY) {
1405       for (i = 0; i < REF_CONTEXTS; i++) {
1406         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0],
1407                                   VP9_MODE_UPDATE_PROB,
1408                                   cpi->single_ref_count[i][0]);
1409         vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1],
1410                                   VP9_MODE_UPDATE_PROB,
1411                                   cpi->single_ref_count[i][1]);
1412       }
1413     }
1414
1415     if (cm->comp_pred_mode != SINGLE_PREDICTION_ONLY)
1416       for (i = 0; i < REF_CONTEXTS; i++)
1417         vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i],
1418                                   VP9_MODE_UPDATE_PROB,
1419                                   cpi->comp_ref_count[i]);
1420
1421     update_mbintra_mode_probs(cpi, &header_bc);
1422
1423     for (i = 0; i < NUM_PARTITION_CONTEXTS; ++i) {
1424       vp9_prob pnew[PARTITION_TYPES - 1];
1425       unsigned int bct[PARTITION_TYPES - 1][2];
1426       update_mode(&header_bc, PARTITION_TYPES,
1427                   vp9_partition_tree, pnew,
1428                   fc->partition_prob[cm->frame_type][i], bct,
1429                   (unsigned int *)cpi->partition_count[i]);
1430     }
1431
1432     vp9_write_nmv_probs(cpi, xd->allow_high_precision_mv, &header_bc);
1433   }
1434
1435   vp9_stop_encode(&header_bc);
1436   assert(header_bc.pos <= 0xffff);
1437
1438   return header_bc.pos;
1439 }
1440
1441 void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, unsigned long *size) {
1442   uint8_t *data = dest;
1443   size_t first_part_size;
1444   struct vp9_write_bit_buffer wb = {data, 0};
1445   struct vp9_write_bit_buffer saved_wb;
1446
1447   write_uncompressed_header(cpi, &wb);
1448   saved_wb = wb;
1449   vp9_wb_write_literal(&wb, 0, 16);  // don't know in advance first part. size
1450
1451   data += vp9_rb_bytes_written(&wb);
1452
1453   vp9_compute_update_table();
1454
1455 #ifdef ENTROPY_STATS
1456   if (pc->frame_type == INTER_FRAME)
1457     active_section = 0;
1458   else
1459     active_section = 7;
1460 #endif
1461
1462   vp9_clear_system_state();  // __asm emms;
1463
1464   first_part_size = write_compressed_header(cpi, data);
1465   data += first_part_size;
1466   vp9_wb_write_literal(&saved_wb, first_part_size, 16);
1467
1468   data += encode_tiles(cpi, data);
1469
1470   *size = data - dest;
1471 }
1472
1473 #ifdef ENTROPY_STATS
1474 static void print_tree_update_for_type(FILE *f,
1475                                        vp9_coeff_stats *tree_update_hist,
1476                                        int block_types, const char *header) {
1477   int i, j, k, l, m;
1478
1479   fprintf(f, "const vp9_coeff_prob %s = {\n", header);
1480   for (i = 0; i < block_types; i++) {
1481     fprintf(f, "  { \n");
1482     for (j = 0; j < REF_TYPES; j++) {
1483       fprintf(f, "  { \n");
1484       for (k = 0; k < COEF_BANDS; k++) {
1485         fprintf(f, "    {\n");
1486         for (l = 0; l < PREV_COEF_CONTEXTS; l++) {
1487           fprintf(f, "      {");
1488           for (m = 0; m < ENTROPY_NODES; m++) {
1489             fprintf(f, "%3d, ",
1490                     get_binary_prob(tree_update_hist[i][j][k][l][m][0],
1491                                     tree_update_hist[i][j][k][l][m][1]));
1492           }
1493           fprintf(f, "},\n");
1494         }
1495         fprintf(f, "},\n");
1496       }
1497       fprintf(f, "    },\n");
1498     }
1499     fprintf(f, "  },\n");
1500   }
1501   fprintf(f, "};\n");
1502 }
1503
1504 void print_tree_update_probs() {
1505   FILE *f = fopen("coefupdprob.h", "w");
1506   fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1507
1508   print_tree_update_for_type(f, tree_update_hist[TX_4X4],   BLOCK_TYPES,
1509                              "vp9_coef_update_probs_4x4[BLOCK_TYPES]");
1510   print_tree_update_for_type(f, tree_update_hist[TX_8X8],   BLOCK_TYPES,
1511                              "vp9_coef_update_probs_8x8[BLOCK_TYPES]");
1512   print_tree_update_for_type(f, tree_update_hist[TX_16X16], BLOCK_TYPES,
1513                              "vp9_coef_update_probs_16x16[BLOCK_TYPES]");
1514   print_tree_update_for_type(f, tree_update_hist[TX_32X32], BLOCK_TYPES,
1515                              "vp9_coef_update_probs_32x32[BLOCK_TYPES]");
1516
1517   fclose(f);
1518   f = fopen("treeupdate.bin", "wb");
1519   fwrite(tree_update_hist, sizeof(tree_update_hist), 1, f);
1520   fclose(f);
1521 }
1522 #endif