]> granicus.if.org Git - libvpx/blob - vp8/encoder/bitstream.c
Merge changes from topic 'clang-tidy'
[libvpx] / vp8 / 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 "vp8/common/header.h"
12 #include "encodemv.h"
13 #include "vp8/common/entropymode.h"
14 #include "vp8/common/findnearmv.h"
15 #include "mcomp.h"
16 #include "vp8/common/systemdependent.h"
17 #include <assert.h>
18 #include <stdio.h>
19 #include <limits.h>
20 #include "vpx/vpx_encoder.h"
21 #include "vpx_mem/vpx_mem.h"
22 #include "bitstream.h"
23
24 #include "defaultcoefcounts.h"
25 #include "vp8/common/common.h"
26
27 const int vp8cx_base_skip_false_prob[128] = {
28   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
29   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
30   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
31   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 248, 244, 240,
32   236, 232, 229, 225, 221, 217, 213, 208, 204, 199, 194, 190, 187, 183, 179,
33   175, 172, 168, 164, 160, 157, 153, 149, 145, 142, 138, 134, 130, 127, 124,
34   120, 117, 114, 110, 107, 104, 101, 98,  95,  92,  89,  86,  83,  80,  77,
35   74,  71,  68,  65,  62,  59,  56,  53,  50,  47,  44,  41,  38,  35,  32,
36   30,  28,  26,  24,  22,  20,  18,  16,
37 };
38
39 #if defined(SECTIONBITS_OUTPUT)
40 unsigned __int64 Sectionbits[500];
41 #endif
42
43 #ifdef VP8_ENTROPY_STATS
44 int intra_mode_stats[10][10][10];
45 static unsigned int tree_update_hist[BLOCK_TYPES][COEF_BANDS]
46                                     [PREV_COEF_CONTEXTS][ENTROPY_NODES][2];
47 extern unsigned int active_section;
48 #endif
49
50 #ifdef MODE_STATS
51 int count_mb_seg[4] = { 0, 0, 0, 0 };
52 #endif
53
54 static void update_mode(vp8_writer *const w, int n, vp8_token tok[/* n */],
55                         vp8_tree tree, vp8_prob Pnew[/* n-1 */],
56                         vp8_prob Pcur[/* n-1 */],
57                         unsigned int bct[/* n-1 */][2],
58                         const unsigned int num_events[/* n */]) {
59   unsigned int new_b = 0, old_b = 0;
60   int i = 0;
61
62   vp8_tree_probs_from_distribution(n--, tok, tree, Pnew, bct, num_events, 256,
63                                    1);
64
65   do {
66     new_b += vp8_cost_branch(bct[i], Pnew[i]);
67     old_b += vp8_cost_branch(bct[i], Pcur[i]);
68   } while (++i < n);
69
70   if (new_b + (n << 8) < old_b) {
71     int j = 0;
72
73     vp8_write_bit(w, 1);
74
75     do {
76       const vp8_prob p = Pnew[j];
77
78       vp8_write_literal(w, Pcur[j] = p ? p : 1, 8);
79     } while (++j < n);
80   } else
81     vp8_write_bit(w, 0);
82 }
83
84 static void update_mbintra_mode_probs(VP8_COMP *cpi) {
85   VP8_COMMON *const x = &cpi->common;
86
87   vp8_writer *const w = cpi->bc;
88
89   {
90     vp8_prob Pnew[VP8_YMODES - 1];
91     unsigned int bct[VP8_YMODES - 1][2];
92
93     update_mode(w, VP8_YMODES, vp8_ymode_encodings, vp8_ymode_tree, Pnew,
94                 x->fc.ymode_prob, bct, (unsigned int *)cpi->mb.ymode_count);
95   }
96   {
97     vp8_prob Pnew[VP8_UV_MODES - 1];
98     unsigned int bct[VP8_UV_MODES - 1][2];
99
100     update_mode(w, VP8_UV_MODES, vp8_uv_mode_encodings, vp8_uv_mode_tree, Pnew,
101                 x->fc.uv_mode_prob, bct, (unsigned int *)cpi->mb.uv_mode_count);
102   }
103 }
104
105 static void write_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
106   vp8_write_token(bc, vp8_ymode_tree, p, vp8_ymode_encodings + m);
107 }
108
109 static void kfwrite_ymode(vp8_writer *bc, int m, const vp8_prob *p) {
110   vp8_write_token(bc, vp8_kf_ymode_tree, p, vp8_kf_ymode_encodings + m);
111 }
112
113 static void write_uv_mode(vp8_writer *bc, int m, const vp8_prob *p) {
114   vp8_write_token(bc, vp8_uv_mode_tree, p, vp8_uv_mode_encodings + m);
115 }
116
117 static void write_bmode(vp8_writer *bc, int m, const vp8_prob *p) {
118   vp8_write_token(bc, vp8_bmode_tree, p, vp8_bmode_encodings + m);
119 }
120
121 static void write_split(vp8_writer *bc, int x) {
122   vp8_write_token(bc, vp8_mbsplit_tree, vp8_mbsplit_probs,
123                   vp8_mbsplit_encodings + x);
124 }
125
126 void vp8_pack_tokens(vp8_writer *w, const TOKENEXTRA *p, int xcount) {
127   const TOKENEXTRA *stop = p + xcount;
128   unsigned int split;
129   int shift;
130   int count = w->count;
131   unsigned int range = w->range;
132   unsigned int lowvalue = w->lowvalue;
133
134   while (p < stop) {
135     const int t = p->Token;
136     vp8_token *a = vp8_coef_encodings + t;
137     const vp8_extra_bit_struct *b = vp8_extra_bits + t;
138     int i = 0;
139     const unsigned char *pp = p->context_tree;
140     int v = a->value;
141     int n = a->Len;
142
143     if (p->skip_eob_node) {
144       n--;
145       i = 2;
146     }
147
148     do {
149       const int bb = (v >> --n) & 1;
150       split = 1 + (((range - 1) * pp[i >> 1]) >> 8);
151       i = vp8_coef_tree[i + bb];
152
153       if (bb) {
154         lowvalue += split;
155         range = range - split;
156       } else {
157         range = split;
158       }
159
160       shift = vp8_norm[range];
161       range <<= shift;
162       count += shift;
163
164       if (count >= 0) {
165         int offset = shift - count;
166
167         if ((lowvalue << (offset - 1)) & 0x80000000) {
168           int x = w->pos - 1;
169
170           while (x >= 0 && w->buffer[x] == 0xff) {
171             w->buffer[x] = (unsigned char)0;
172             x--;
173           }
174
175           w->buffer[x] += 1;
176         }
177
178         validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
179
180         w->buffer[w->pos++] = (lowvalue >> (24 - offset));
181         lowvalue <<= offset;
182         shift = count;
183         lowvalue &= 0xffffff;
184         count -= 8;
185       }
186
187       lowvalue <<= shift;
188     } while (n);
189
190     if (b->base_val) {
191       const int e = p->Extra, L = b->Len;
192
193       if (L) {
194         const unsigned char *proba = b->prob;
195         const int v2 = e >> 1;
196         int n2 = L; /* number of bits in v2, assumed nonzero */
197         i = 0;
198
199         do {
200           const int bb = (v2 >> --n2) & 1;
201           split = 1 + (((range - 1) * proba[i >> 1]) >> 8);
202           i = b->tree[i + bb];
203
204           if (bb) {
205             lowvalue += split;
206             range = range - split;
207           } else {
208             range = split;
209           }
210
211           shift = vp8_norm[range];
212           range <<= shift;
213           count += shift;
214
215           if (count >= 0) {
216             int offset = shift - count;
217
218             if ((lowvalue << (offset - 1)) & 0x80000000) {
219               int x = w->pos - 1;
220
221               while (x >= 0 && w->buffer[x] == 0xff) {
222                 w->buffer[x] = (unsigned char)0;
223                 x--;
224               }
225
226               w->buffer[x] += 1;
227             }
228
229             validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
230
231             w->buffer[w->pos++] = (lowvalue >> (24 - offset));
232             lowvalue <<= offset;
233             shift = count;
234             lowvalue &= 0xffffff;
235             count -= 8;
236           }
237
238           lowvalue <<= shift;
239         } while (n2);
240       }
241
242       {
243         split = (range + 1) >> 1;
244
245         if (e & 1) {
246           lowvalue += split;
247           range = range - split;
248         } else {
249           range = split;
250         }
251
252         range <<= 1;
253
254         if ((lowvalue & 0x80000000)) {
255           int x = w->pos - 1;
256
257           while (x >= 0 && w->buffer[x] == 0xff) {
258             w->buffer[x] = (unsigned char)0;
259             x--;
260           }
261
262           w->buffer[x] += 1;
263         }
264
265         lowvalue <<= 1;
266
267         if (!++count) {
268           count = -8;
269
270           validate_buffer(w->buffer + w->pos, 1, w->buffer_end, w->error);
271
272           w->buffer[w->pos++] = (lowvalue >> 24);
273           lowvalue &= 0xffffff;
274         }
275       }
276     }
277
278     ++p;
279   }
280
281   w->count = count;
282   w->lowvalue = lowvalue;
283   w->range = range;
284 }
285
286 static void write_partition_size(unsigned char *cx_data, int size) {
287   signed char csize;
288
289   csize = size & 0xff;
290   *cx_data = csize;
291   csize = (size >> 8) & 0xff;
292   *(cx_data + 1) = csize;
293   csize = (size >> 16) & 0xff;
294   *(cx_data + 2) = csize;
295 }
296
297 static void pack_tokens_into_partitions(VP8_COMP *cpi, unsigned char *cx_data,
298                                         unsigned char *cx_data_end,
299                                         int num_part) {
300   int i;
301   unsigned char *ptr = cx_data;
302   unsigned char *ptr_end = cx_data_end;
303   vp8_writer *w;
304
305   for (i = 0; i < num_part; ++i) {
306     int mb_row;
307
308     w = cpi->bc + i + 1;
309
310     vp8_start_encode(w, ptr, ptr_end);
311
312     for (mb_row = i; mb_row < cpi->common.mb_rows; mb_row += num_part) {
313       const TOKENEXTRA *p = cpi->tplist[mb_row].start;
314       const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
315       int tokens = (int)(stop - p);
316
317       vp8_pack_tokens(w, p, tokens);
318     }
319
320     vp8_stop_encode(w);
321     ptr += w->pos;
322   }
323 }
324
325 #if CONFIG_MULTITHREAD
326 static void pack_mb_row_tokens(VP8_COMP *cpi, vp8_writer *w) {
327   int mb_row;
328
329   for (mb_row = 0; mb_row < cpi->common.mb_rows; ++mb_row) {
330     const TOKENEXTRA *p = cpi->tplist[mb_row].start;
331     const TOKENEXTRA *stop = cpi->tplist[mb_row].stop;
332     int tokens = (int)(stop - p);
333
334     vp8_pack_tokens(w, p, tokens);
335   }
336 }
337 #endif  // CONFIG_MULTITHREAD
338
339 static void write_mv_ref(vp8_writer *w, MB_PREDICTION_MODE m,
340                          const vp8_prob *p) {
341 #if CONFIG_DEBUG
342   assert(NEARESTMV <= m && m <= SPLITMV);
343 #endif
344   vp8_write_token(w, vp8_mv_ref_tree, p,
345                   vp8_mv_ref_encoding_array + (m - NEARESTMV));
346 }
347
348 static void write_sub_mv_ref(vp8_writer *w, B_PREDICTION_MODE m,
349                              const vp8_prob *p) {
350 #if CONFIG_DEBUG
351   assert(LEFT4X4 <= m && m <= NEW4X4);
352 #endif
353   vp8_write_token(w, vp8_sub_mv_ref_tree, p,
354                   vp8_sub_mv_ref_encoding_array + (m - LEFT4X4));
355 }
356
357 static void write_mv(vp8_writer *w, const MV *mv, const int_mv *ref,
358                      const MV_CONTEXT *mvc) {
359   MV e;
360   e.row = mv->row - ref->as_mv.row;
361   e.col = mv->col - ref->as_mv.col;
362
363   vp8_encode_motion_vector(w, &e, mvc);
364 }
365
366 static void write_mb_features(vp8_writer *w, const MB_MODE_INFO *mi,
367                               const MACROBLOCKD *x) {
368   /* Encode the MB segment id. */
369   if (x->segmentation_enabled && x->update_mb_segmentation_map) {
370     switch (mi->segment_id) {
371       case 0:
372         vp8_write(w, 0, x->mb_segment_tree_probs[0]);
373         vp8_write(w, 0, x->mb_segment_tree_probs[1]);
374         break;
375       case 1:
376         vp8_write(w, 0, x->mb_segment_tree_probs[0]);
377         vp8_write(w, 1, x->mb_segment_tree_probs[1]);
378         break;
379       case 2:
380         vp8_write(w, 1, x->mb_segment_tree_probs[0]);
381         vp8_write(w, 0, x->mb_segment_tree_probs[2]);
382         break;
383       case 3:
384         vp8_write(w, 1, x->mb_segment_tree_probs[0]);
385         vp8_write(w, 1, x->mb_segment_tree_probs[2]);
386         break;
387
388       /* TRAP.. This should not happen */
389       default:
390         vp8_write(w, 0, x->mb_segment_tree_probs[0]);
391         vp8_write(w, 0, x->mb_segment_tree_probs[1]);
392         break;
393     }
394   }
395 }
396 void vp8_convert_rfct_to_prob(VP8_COMP *const cpi) {
397   const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
398   const int rf_intra = rfct[INTRA_FRAME];
399   const int rf_inter =
400       rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
401
402   /* Calculate the probabilities used to code the ref frame based on usage */
403   if (!(cpi->prob_intra_coded = rf_intra * 255 / (rf_intra + rf_inter))) {
404     cpi->prob_intra_coded = 1;
405   }
406
407   cpi->prob_last_coded = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
408
409   if (!cpi->prob_last_coded) cpi->prob_last_coded = 1;
410
411   cpi->prob_gf_coded = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
412                            ? (rfct[GOLDEN_FRAME] * 255) /
413                                  (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
414                            : 128;
415
416   if (!cpi->prob_gf_coded) cpi->prob_gf_coded = 1;
417 }
418
419 static void pack_inter_mode_mvs(VP8_COMP *const cpi) {
420   VP8_COMMON *const pc = &cpi->common;
421   vp8_writer *const w = cpi->bc;
422   const MV_CONTEXT *mvc = pc->fc.mvc;
423
424   MODE_INFO *m = pc->mi;
425   const int mis = pc->mode_info_stride;
426   int mb_row = -1;
427
428   int prob_skip_false = 0;
429
430   cpi->mb.partition_info = cpi->mb.pi;
431
432   vp8_convert_rfct_to_prob(cpi);
433
434 #ifdef VP8_ENTROPY_STATS
435   active_section = 1;
436 #endif
437
438   if (pc->mb_no_coeff_skip) {
439     int total_mbs = pc->mb_rows * pc->mb_cols;
440
441     prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
442
443     if (prob_skip_false <= 1) prob_skip_false = 1;
444
445     if (prob_skip_false > 255) prob_skip_false = 255;
446
447     cpi->prob_skip_false = prob_skip_false;
448     vp8_write_literal(w, prob_skip_false, 8);
449   }
450
451   vp8_write_literal(w, cpi->prob_intra_coded, 8);
452   vp8_write_literal(w, cpi->prob_last_coded, 8);
453   vp8_write_literal(w, cpi->prob_gf_coded, 8);
454
455   update_mbintra_mode_probs(cpi);
456
457   vp8_write_mvprobs(cpi);
458
459   while (++mb_row < pc->mb_rows) {
460     int mb_col = -1;
461
462     while (++mb_col < pc->mb_cols) {
463       const MB_MODE_INFO *const mi = &m->mbmi;
464       const MV_REFERENCE_FRAME rf = mi->ref_frame;
465       const MB_PREDICTION_MODE mode = mi->mode;
466
467       MACROBLOCKD *xd = &cpi->mb.e_mbd;
468
469       /* Distance of Mb to the various image edges.
470        * These specified to 8th pel as they are always compared to MV
471        * values that are in 1/8th pel units
472        */
473       xd->mb_to_left_edge = -((mb_col * 16) << 3);
474       xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
475       xd->mb_to_top_edge = -((mb_row * 16) << 3);
476       xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
477
478 #ifdef VP8_ENTROPY_STATS
479       active_section = 9;
480 #endif
481
482       if (cpi->mb.e_mbd.update_mb_segmentation_map) {
483         write_mb_features(w, mi, &cpi->mb.e_mbd);
484       }
485
486       if (pc->mb_no_coeff_skip) {
487         vp8_encode_bool(w, m->mbmi.mb_skip_coeff, prob_skip_false);
488       }
489
490       if (rf == INTRA_FRAME) {
491         vp8_write(w, 0, cpi->prob_intra_coded);
492 #ifdef VP8_ENTROPY_STATS
493         active_section = 6;
494 #endif
495         write_ymode(w, mode, pc->fc.ymode_prob);
496
497         if (mode == B_PRED) {
498           int j = 0;
499
500           do {
501             write_bmode(w, m->bmi[j].as_mode, pc->fc.bmode_prob);
502           } while (++j < 16);
503         }
504
505         write_uv_mode(w, mi->uv_mode, pc->fc.uv_mode_prob);
506       } else /* inter coded */
507       {
508         int_mv best_mv;
509         vp8_prob mv_ref_p[VP8_MVREFS - 1];
510
511         vp8_write(w, 1, cpi->prob_intra_coded);
512
513         if (rf == LAST_FRAME)
514           vp8_write(w, 0, cpi->prob_last_coded);
515         else {
516           vp8_write(w, 1, cpi->prob_last_coded);
517           vp8_write(w, (rf == GOLDEN_FRAME) ? 0 : 1, cpi->prob_gf_coded);
518         }
519
520         {
521           int_mv n1, n2;
522           int ct[4];
523
524           vp8_find_near_mvs(xd, m, &n1, &n2, &best_mv, ct, rf,
525                             cpi->common.ref_frame_sign_bias);
526           vp8_clamp_mv2(&best_mv, xd);
527
528           vp8_mv_ref_probs(mv_ref_p, ct);
529
530 #ifdef VP8_ENTROPY_STATS
531           accum_mv_refs(mode, ct);
532 #endif
533         }
534
535 #ifdef VP8_ENTROPY_STATS
536         active_section = 3;
537 #endif
538
539         write_mv_ref(w, mode, mv_ref_p);
540
541         switch (mode) /* new, split require MVs */
542         {
543           case NEWMV:
544
545 #ifdef VP8_ENTROPY_STATS
546             active_section = 5;
547 #endif
548
549             write_mv(w, &mi->mv.as_mv, &best_mv, mvc);
550             break;
551
552           case SPLITMV: {
553             int j = 0;
554
555 #ifdef MODE_STATS
556             ++count_mb_seg[mi->partitioning];
557 #endif
558
559             write_split(w, mi->partitioning);
560
561             do {
562               B_PREDICTION_MODE blockmode;
563               int_mv blockmv;
564               const int *const L = vp8_mbsplits[mi->partitioning];
565               int k = -1; /* first block in subset j */
566               int mv_contz;
567               int_mv leftmv, abovemv;
568
569               blockmode = cpi->mb.partition_info->bmi[j].mode;
570               blockmv = cpi->mb.partition_info->bmi[j].mv;
571               while (j != L[++k]) {
572                 assert(k < 16);
573               }
574               leftmv.as_int = left_block_mv(m, k);
575               abovemv.as_int = above_block_mv(m, k, mis);
576               mv_contz = vp8_mv_cont(&leftmv, &abovemv);
577
578               write_sub_mv_ref(w, blockmode, vp8_sub_mv_ref_prob2[mv_contz]);
579
580               if (blockmode == NEW4X4) {
581 #ifdef VP8_ENTROPY_STATS
582                 active_section = 11;
583 #endif
584                 write_mv(w, &blockmv.as_mv, &best_mv, (const MV_CONTEXT *)mvc);
585               }
586             } while (++j < cpi->mb.partition_info->count);
587             break;
588           }
589           default: break;
590         }
591       }
592
593       ++m;
594       cpi->mb.partition_info++;
595     }
596
597     ++m; /* skip L prediction border */
598     cpi->mb.partition_info++;
599   }
600 }
601
602 static void write_kfmodes(VP8_COMP *cpi) {
603   vp8_writer *const bc = cpi->bc;
604   const VP8_COMMON *const c = &cpi->common;
605   /* const */
606   MODE_INFO *m = c->mi;
607
608   int mb_row = -1;
609   int prob_skip_false = 0;
610
611   if (c->mb_no_coeff_skip) {
612     int total_mbs = c->mb_rows * c->mb_cols;
613
614     prob_skip_false = (total_mbs - cpi->mb.skip_true_count) * 256 / total_mbs;
615
616     if (prob_skip_false <= 1) prob_skip_false = 1;
617
618     if (prob_skip_false >= 255) prob_skip_false = 255;
619
620     cpi->prob_skip_false = prob_skip_false;
621     vp8_write_literal(bc, prob_skip_false, 8);
622   }
623
624   while (++mb_row < c->mb_rows) {
625     int mb_col = -1;
626
627     while (++mb_col < c->mb_cols) {
628       const int ym = m->mbmi.mode;
629
630       if (cpi->mb.e_mbd.update_mb_segmentation_map) {
631         write_mb_features(bc, &m->mbmi, &cpi->mb.e_mbd);
632       }
633
634       if (c->mb_no_coeff_skip) {
635         vp8_encode_bool(bc, m->mbmi.mb_skip_coeff, prob_skip_false);
636       }
637
638       kfwrite_ymode(bc, ym, vp8_kf_ymode_prob);
639
640       if (ym == B_PRED) {
641         const int mis = c->mode_info_stride;
642         int i = 0;
643
644         do {
645           const B_PREDICTION_MODE A = above_block_mode(m, i, mis);
646           const B_PREDICTION_MODE L = left_block_mode(m, i);
647           const int bm = m->bmi[i].as_mode;
648
649 #ifdef VP8_ENTROPY_STATS
650           ++intra_mode_stats[A][L][bm];
651 #endif
652
653           write_bmode(bc, bm, vp8_kf_bmode_prob[A][L]);
654         } while (++i < 16);
655       }
656
657       write_uv_mode(bc, (m++)->mbmi.uv_mode, vp8_kf_uv_mode_prob);
658     }
659
660     m++; /* skip L prediction border */
661   }
662 }
663
664 #if 0
665 /* This function is used for debugging probability trees. */
666 static void print_prob_tree(vp8_prob
667      coef_probs[BLOCK_TYPES][COEF_BANDS][PREV_COEF_CONTEXTS][ENTROPY_NODES])
668 {
669     /* print coef probability tree */
670     int i,j,k,l;
671     FILE* f = fopen("enc_tree_probs.txt", "a");
672     fprintf(f, "{\n");
673     for (i = 0; i < BLOCK_TYPES; ++i)
674     {
675         fprintf(f, "  {\n");
676         for (j = 0; j < COEF_BANDS; ++j)
677         {
678             fprintf(f, "    {\n");
679             for (k = 0; k < PREV_COEF_CONTEXTS; ++k)
680             {
681                 fprintf(f, "      {");
682                 for (l = 0; l < ENTROPY_NODES; ++l)
683                 {
684                     fprintf(f, "%3u, ",
685                             (unsigned int)(coef_probs [i][j][k][l]));
686                 }
687                 fprintf(f, " }\n");
688             }
689             fprintf(f, "    }\n");
690         }
691         fprintf(f, "  }\n");
692     }
693     fprintf(f, "}\n");
694     fclose(f);
695 }
696 #endif
697
698 static void sum_probs_over_prev_coef_context(
699     const unsigned int probs[PREV_COEF_CONTEXTS][MAX_ENTROPY_TOKENS],
700     unsigned int *out) {
701   int i, j;
702   for (i = 0; i < MAX_ENTROPY_TOKENS; ++i) {
703     for (j = 0; j < PREV_COEF_CONTEXTS; ++j) {
704       const unsigned int tmp = out[i];
705       out[i] += probs[j][i];
706       /* check for wrap */
707       if (out[i] < tmp) out[i] = UINT_MAX;
708     }
709   }
710 }
711
712 static int prob_update_savings(const unsigned int *ct, const vp8_prob oldp,
713                                const vp8_prob newp, const vp8_prob upd) {
714   const int old_b = vp8_cost_branch(ct, oldp);
715   const int new_b = vp8_cost_branch(ct, newp);
716   const int update_b = 8 + ((vp8_cost_one(upd) - vp8_cost_zero(upd)) >> 8);
717
718   return old_b - new_b - update_b;
719 }
720
721 static int independent_coef_context_savings(VP8_COMP *cpi) {
722   MACROBLOCK *const x = &cpi->mb;
723   int savings = 0;
724   int i = 0;
725   do {
726     int j = 0;
727     do {
728       int k = 0;
729       unsigned int prev_coef_count_sum[MAX_ENTROPY_TOKENS] = { 0 };
730       int prev_coef_savings[MAX_ENTROPY_TOKENS] = { 0 };
731       const unsigned int(*probs)[MAX_ENTROPY_TOKENS];
732       /* Calculate new probabilities given the constraint that
733        * they must be equal over the prev coef contexts
734        */
735
736       probs = (const unsigned int(*)[MAX_ENTROPY_TOKENS])x->coef_counts[i][j];
737
738       /* Reset to default probabilities at key frames */
739       if (cpi->common.frame_type == KEY_FRAME) {
740         probs = default_coef_counts[i][j];
741       }
742
743       sum_probs_over_prev_coef_context(probs, prev_coef_count_sum);
744
745       do {
746         /* at every context */
747
748         /* calc probs and branch cts for this frame only */
749         int t = 0; /* token/prob index */
750
751         vp8_tree_probs_from_distribution(
752             MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
753             cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
754             prev_coef_count_sum, 256, 1);
755
756         do {
757           const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
758           const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
759           const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
760           const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
761           const int s = prob_update_savings(ct, oldp, newp, upd);
762
763           if (cpi->common.frame_type != KEY_FRAME ||
764               (cpi->common.frame_type == KEY_FRAME && newp != oldp)) {
765             prev_coef_savings[t] += s;
766           }
767         } while (++t < ENTROPY_NODES);
768       } while (++k < PREV_COEF_CONTEXTS);
769       k = 0;
770       do {
771         /* We only update probabilities if we can save bits, except
772          * for key frames where we have to update all probabilities
773          * to get the equal probabilities across the prev coef
774          * contexts.
775          */
776         if (prev_coef_savings[k] > 0 || cpi->common.frame_type == KEY_FRAME) {
777           savings += prev_coef_savings[k];
778         }
779       } while (++k < ENTROPY_NODES);
780     } while (++j < COEF_BANDS);
781   } while (++i < BLOCK_TYPES);
782   return savings;
783 }
784
785 static int default_coef_context_savings(VP8_COMP *cpi) {
786   MACROBLOCK *const x = &cpi->mb;
787   int savings = 0;
788   int i = 0;
789   do {
790     int j = 0;
791     do {
792       int k = 0;
793       do {
794         /* at every context */
795
796         /* calc probs and branch cts for this frame only */
797         int t = 0; /* token/prob index */
798
799         vp8_tree_probs_from_distribution(
800             MAX_ENTROPY_TOKENS, vp8_coef_encodings, vp8_coef_tree,
801             cpi->frame_coef_probs[i][j][k], cpi->frame_branch_ct[i][j][k],
802             x->coef_counts[i][j][k], 256, 1);
803
804         do {
805           const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
806           const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
807           const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
808           const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
809           const int s = prob_update_savings(ct, oldp, newp, upd);
810
811           if (s > 0) {
812             savings += s;
813           }
814         } while (++t < ENTROPY_NODES);
815       } while (++k < PREV_COEF_CONTEXTS);
816     } while (++j < COEF_BANDS);
817   } while (++i < BLOCK_TYPES);
818   return savings;
819 }
820
821 void vp8_calc_ref_frame_costs(int *ref_frame_cost, int prob_intra,
822                               int prob_last, int prob_garf) {
823   assert(prob_intra >= 0);
824   assert(prob_intra <= 255);
825   assert(prob_last >= 0);
826   assert(prob_last <= 255);
827   assert(prob_garf >= 0);
828   assert(prob_garf <= 255);
829   ref_frame_cost[INTRA_FRAME] = vp8_cost_zero(prob_intra);
830   ref_frame_cost[LAST_FRAME] =
831       vp8_cost_one(prob_intra) + vp8_cost_zero(prob_last);
832   ref_frame_cost[GOLDEN_FRAME] = vp8_cost_one(prob_intra) +
833                                  vp8_cost_one(prob_last) +
834                                  vp8_cost_zero(prob_garf);
835   ref_frame_cost[ALTREF_FRAME] = vp8_cost_one(prob_intra) +
836                                  vp8_cost_one(prob_last) +
837                                  vp8_cost_one(prob_garf);
838 }
839
840 int vp8_estimate_entropy_savings(VP8_COMP *cpi) {
841   int savings = 0;
842
843   const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
844   const int rf_intra = rfct[INTRA_FRAME];
845   const int rf_inter =
846       rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
847   int new_intra, new_last, new_garf, oldtotal, newtotal;
848   int ref_frame_cost[MAX_REF_FRAMES];
849
850   vp8_clear_system_state();
851
852   if (cpi->common.frame_type != KEY_FRAME) {
853     if (!(new_intra = rf_intra * 255 / (rf_intra + rf_inter))) new_intra = 1;
854
855     new_last = rf_inter ? (rfct[LAST_FRAME] * 255) / rf_inter : 128;
856
857     new_garf = (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
858                    ? (rfct[GOLDEN_FRAME] * 255) /
859                          (rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME])
860                    : 128;
861
862     vp8_calc_ref_frame_costs(ref_frame_cost, new_intra, new_last, new_garf);
863
864     newtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
865                rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
866                rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
867                rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
868
869     /* old costs */
870     vp8_calc_ref_frame_costs(ref_frame_cost, cpi->prob_intra_coded,
871                              cpi->prob_last_coded, cpi->prob_gf_coded);
872
873     oldtotal = rfct[INTRA_FRAME] * ref_frame_cost[INTRA_FRAME] +
874                rfct[LAST_FRAME] * ref_frame_cost[LAST_FRAME] +
875                rfct[GOLDEN_FRAME] * ref_frame_cost[GOLDEN_FRAME] +
876                rfct[ALTREF_FRAME] * ref_frame_cost[ALTREF_FRAME];
877
878     savings += (oldtotal - newtotal) / 256;
879   }
880
881   if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
882     savings += independent_coef_context_savings(cpi);
883   } else {
884     savings += default_coef_context_savings(cpi);
885   }
886
887   return savings;
888 }
889
890 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
891 int vp8_update_coef_context(VP8_COMP *cpi) {
892   int savings = 0;
893
894   if (cpi->common.frame_type == KEY_FRAME) {
895     /* Reset to default counts/probabilities at key frames */
896     vp8_copy(cpi->mb.coef_counts, default_coef_counts);
897   }
898
899   if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS)
900     savings += independent_coef_context_savings(cpi);
901   else
902     savings += default_coef_context_savings(cpi);
903
904   return savings;
905 }
906 #endif
907
908 void vp8_update_coef_probs(VP8_COMP *cpi) {
909   int i = 0;
910 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
911   vp8_writer *const w = cpi->bc;
912 #endif
913   int savings = 0;
914
915   vp8_clear_system_state();
916
917   do {
918     int j = 0;
919
920     do {
921       int k = 0;
922       int prev_coef_savings[ENTROPY_NODES] = { 0 };
923       if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
924         for (k = 0; k < PREV_COEF_CONTEXTS; ++k) {
925           int t; /* token/prob index */
926           for (t = 0; t < ENTROPY_NODES; ++t) {
927             const unsigned int *ct = cpi->frame_branch_ct[i][j][k][t];
928             const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
929             const vp8_prob oldp = cpi->common.fc.coef_probs[i][j][k][t];
930             const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
931
932             prev_coef_savings[t] += prob_update_savings(ct, oldp, newp, upd);
933           }
934         }
935         k = 0;
936       }
937       do {
938         /* note: use result from vp8_estimate_entropy_savings, so no
939          * need to call vp8_tree_probs_from_distribution here.
940          */
941
942         /* at every context */
943
944         /* calc probs and branch cts for this frame only */
945         int t = 0; /* token/prob index */
946
947         do {
948           const vp8_prob newp = cpi->frame_coef_probs[i][j][k][t];
949
950           vp8_prob *Pold = cpi->common.fc.coef_probs[i][j][k] + t;
951           const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
952
953           int s = prev_coef_savings[t];
954           int u = 0;
955
956           if (!(cpi->oxcf.error_resilient_mode &
957                 VPX_ERROR_RESILIENT_PARTITIONS)) {
958             s = prob_update_savings(cpi->frame_branch_ct[i][j][k][t], *Pold,
959                                     newp, upd);
960           }
961
962           if (s > 0) u = 1;
963
964           /* Force updates on key frames if the new is different,
965            * so that we can be sure we end up with equal probabilities
966            * over the prev coef contexts.
967            */
968           if ((cpi->oxcf.error_resilient_mode &
969                VPX_ERROR_RESILIENT_PARTITIONS) &&
970               cpi->common.frame_type == KEY_FRAME && newp != *Pold) {
971             u = 1;
972           }
973
974 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
975           cpi->update_probs[i][j][k][t] = u;
976 #else
977           vp8_write(w, u, upd);
978 #endif
979
980 #ifdef VP8_ENTROPY_STATS
981           ++tree_update_hist[i][j][k][t][u];
982 #endif
983
984           if (u) {
985             /* send/use new probability */
986
987             *Pold = newp;
988 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
989             vp8_write_literal(w, newp, 8);
990 #endif
991
992             savings += s;
993           }
994
995         } while (++t < ENTROPY_NODES);
996
997 /* Accum token counts for generation of default statistics */
998 #ifdef VP8_ENTROPY_STATS
999         t = 0;
1000
1001         do {
1002           context_counters[i][j][k][t] += cpi->coef_counts[i][j][k][t];
1003         } while (++t < MAX_ENTROPY_TOKENS);
1004
1005 #endif
1006
1007       } while (++k < PREV_COEF_CONTEXTS);
1008     } while (++j < COEF_BANDS);
1009   } while (++i < BLOCK_TYPES);
1010 }
1011
1012 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1013 static void pack_coef_probs(VP8_COMP *cpi) {
1014   int i = 0;
1015   vp8_writer *const w = cpi->bc;
1016
1017   do {
1018     int j = 0;
1019
1020     do {
1021       int k = 0;
1022
1023       do {
1024         int t = 0; /* token/prob index */
1025
1026         do {
1027           const vp8_prob newp = cpi->common.fc.coef_probs[i][j][k][t];
1028           const vp8_prob upd = vp8_coef_update_probs[i][j][k][t];
1029
1030           const char u = cpi->update_probs[i][j][k][t];
1031
1032           vp8_write(w, u, upd);
1033
1034           if (u) {
1035             /* send/use new probability */
1036             vp8_write_literal(w, newp, 8);
1037           }
1038         } while (++t < ENTROPY_NODES);
1039       } while (++k < PREV_COEF_CONTEXTS);
1040     } while (++j < COEF_BANDS);
1041   } while (++i < BLOCK_TYPES);
1042 }
1043 #endif
1044
1045 #ifdef PACKET_TESTING
1046 FILE *vpxlogc = 0;
1047 #endif
1048
1049 static void put_delta_q(vp8_writer *bc, int delta_q) {
1050   if (delta_q != 0) {
1051     vp8_write_bit(bc, 1);
1052     vp8_write_literal(bc, abs(delta_q), 4);
1053
1054     if (delta_q < 0)
1055       vp8_write_bit(bc, 1);
1056     else
1057       vp8_write_bit(bc, 0);
1058   } else
1059     vp8_write_bit(bc, 0);
1060 }
1061
1062 void vp8_pack_bitstream(VP8_COMP *cpi, unsigned char *dest,
1063                         unsigned char *dest_end, unsigned long *size) {
1064   int i, j;
1065   VP8_HEADER oh;
1066   VP8_COMMON *const pc = &cpi->common;
1067   vp8_writer *const bc = cpi->bc;
1068   MACROBLOCKD *const xd = &cpi->mb.e_mbd;
1069   int extra_bytes_packed = 0;
1070
1071   unsigned char *cx_data = dest;
1072   unsigned char *cx_data_end = dest_end;
1073   const int *mb_feature_data_bits;
1074
1075   oh.show_frame = (int)pc->show_frame;
1076   oh.type = (int)pc->frame_type;
1077   oh.version = pc->version;
1078   oh.first_partition_length_in_bytes = 0;
1079
1080   mb_feature_data_bits = vp8_mb_feature_data_bits;
1081
1082   bc[0].error = &pc->error;
1083
1084   validate_buffer(cx_data, 3, cx_data_end, &cpi->common.error);
1085   cx_data += 3;
1086
1087 #if defined(SECTIONBITS_OUTPUT)
1088   Sectionbits[active_section = 1] += sizeof(VP8_HEADER) * 8 * 256;
1089 #endif
1090
1091   /* every keyframe send startcode, width, height, scale factor, clamp
1092    * and color type
1093    */
1094   if (oh.type == KEY_FRAME) {
1095     int v;
1096
1097     validate_buffer(cx_data, 7, cx_data_end, &cpi->common.error);
1098
1099     /* Start / synch code */
1100     cx_data[0] = 0x9D;
1101     cx_data[1] = 0x01;
1102     cx_data[2] = 0x2a;
1103
1104     v = (pc->horiz_scale << 14) | pc->Width;
1105     cx_data[3] = v;
1106     cx_data[4] = v >> 8;
1107
1108     v = (pc->vert_scale << 14) | pc->Height;
1109     cx_data[5] = v;
1110     cx_data[6] = v >> 8;
1111
1112     extra_bytes_packed = 7;
1113     cx_data += extra_bytes_packed;
1114
1115     vp8_start_encode(bc, cx_data, cx_data_end);
1116
1117     /* signal clr type */
1118     vp8_write_bit(bc, 0);
1119     vp8_write_bit(bc, pc->clamp_type);
1120
1121   } else {
1122     vp8_start_encode(bc, cx_data, cx_data_end);
1123   }
1124
1125   /* Signal whether or not Segmentation is enabled */
1126   vp8_write_bit(bc, xd->segmentation_enabled);
1127
1128   /*  Indicate which features are enabled */
1129   if (xd->segmentation_enabled) {
1130     /* Signal whether or not the segmentation map is being updated. */
1131     vp8_write_bit(bc, xd->update_mb_segmentation_map);
1132     vp8_write_bit(bc, xd->update_mb_segmentation_data);
1133
1134     if (xd->update_mb_segmentation_data) {
1135       signed char Data;
1136
1137       vp8_write_bit(bc, xd->mb_segement_abs_delta);
1138
1139       /* For each segmentation feature (Quant and loop filter level) */
1140       for (i = 0; i < MB_LVL_MAX; ++i) {
1141         /* For each of the segments */
1142         for (j = 0; j < MAX_MB_SEGMENTS; ++j) {
1143           Data = xd->segment_feature_data[i][j];
1144
1145           /* Frame level data */
1146           if (Data) {
1147             vp8_write_bit(bc, 1);
1148
1149             if (Data < 0) {
1150               Data = -Data;
1151               vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1152               vp8_write_bit(bc, 1);
1153             } else {
1154               vp8_write_literal(bc, Data, mb_feature_data_bits[i]);
1155               vp8_write_bit(bc, 0);
1156             }
1157           } else
1158             vp8_write_bit(bc, 0);
1159         }
1160       }
1161     }
1162
1163     if (xd->update_mb_segmentation_map) {
1164       /* Write the probs used to decode the segment id for each mb */
1165       for (i = 0; i < MB_FEATURE_TREE_PROBS; ++i) {
1166         int Data = xd->mb_segment_tree_probs[i];
1167
1168         if (Data != 255) {
1169           vp8_write_bit(bc, 1);
1170           vp8_write_literal(bc, Data, 8);
1171         } else
1172           vp8_write_bit(bc, 0);
1173       }
1174     }
1175   }
1176
1177   vp8_write_bit(bc, pc->filter_type);
1178   vp8_write_literal(bc, pc->filter_level, 6);
1179   vp8_write_literal(bc, pc->sharpness_level, 3);
1180
1181   /* Write out loop filter deltas applied at the MB level based on mode
1182    * or ref frame (if they are enabled).
1183    */
1184   vp8_write_bit(bc, xd->mode_ref_lf_delta_enabled);
1185
1186   if (xd->mode_ref_lf_delta_enabled) {
1187     /* Do the deltas need to be updated */
1188     int send_update =
1189         xd->mode_ref_lf_delta_update || cpi->oxcf.error_resilient_mode;
1190
1191     vp8_write_bit(bc, send_update);
1192     if (send_update) {
1193       int Data;
1194
1195       /* Send update */
1196       for (i = 0; i < MAX_REF_LF_DELTAS; ++i) {
1197         Data = xd->ref_lf_deltas[i];
1198
1199         /* Frame level data */
1200         if (xd->ref_lf_deltas[i] != xd->last_ref_lf_deltas[i] ||
1201             cpi->oxcf.error_resilient_mode) {
1202           xd->last_ref_lf_deltas[i] = xd->ref_lf_deltas[i];
1203           vp8_write_bit(bc, 1);
1204
1205           if (Data > 0) {
1206             vp8_write_literal(bc, (Data & 0x3F), 6);
1207             vp8_write_bit(bc, 0); /* sign */
1208           } else {
1209             Data = -Data;
1210             vp8_write_literal(bc, (Data & 0x3F), 6);
1211             vp8_write_bit(bc, 1); /* sign */
1212           }
1213         } else
1214           vp8_write_bit(bc, 0);
1215       }
1216
1217       /* Send update */
1218       for (i = 0; i < MAX_MODE_LF_DELTAS; ++i) {
1219         Data = xd->mode_lf_deltas[i];
1220
1221         if (xd->mode_lf_deltas[i] != xd->last_mode_lf_deltas[i] ||
1222             cpi->oxcf.error_resilient_mode) {
1223           xd->last_mode_lf_deltas[i] = xd->mode_lf_deltas[i];
1224           vp8_write_bit(bc, 1);
1225
1226           if (Data > 0) {
1227             vp8_write_literal(bc, (Data & 0x3F), 6);
1228             vp8_write_bit(bc, 0); /* sign */
1229           } else {
1230             Data = -Data;
1231             vp8_write_literal(bc, (Data & 0x3F), 6);
1232             vp8_write_bit(bc, 1); /* sign */
1233           }
1234         } else
1235           vp8_write_bit(bc, 0);
1236       }
1237     }
1238   }
1239
1240   /* signal here is multi token partition is enabled */
1241   vp8_write_literal(bc, pc->multi_token_partition, 2);
1242
1243   /* Frame Qbaseline quantizer index */
1244   vp8_write_literal(bc, pc->base_qindex, 7);
1245
1246   /* Transmit Dc, Second order and Uv quantizer delta information */
1247   put_delta_q(bc, pc->y1dc_delta_q);
1248   put_delta_q(bc, pc->y2dc_delta_q);
1249   put_delta_q(bc, pc->y2ac_delta_q);
1250   put_delta_q(bc, pc->uvdc_delta_q);
1251   put_delta_q(bc, pc->uvac_delta_q);
1252
1253   /* When there is a key frame all reference buffers are updated using
1254    * the new key frame
1255    */
1256   if (pc->frame_type != KEY_FRAME) {
1257     /* Should the GF or ARF be updated using the transmitted frame
1258      * or buffer
1259      */
1260     vp8_write_bit(bc, pc->refresh_golden_frame);
1261     vp8_write_bit(bc, pc->refresh_alt_ref_frame);
1262
1263     /* If not being updated from current frame should either GF or ARF
1264      * be updated from another buffer
1265      */
1266     if (!pc->refresh_golden_frame)
1267       vp8_write_literal(bc, pc->copy_buffer_to_gf, 2);
1268
1269     if (!pc->refresh_alt_ref_frame)
1270       vp8_write_literal(bc, pc->copy_buffer_to_arf, 2);
1271
1272     /* Indicate reference frame sign bias for Golden and ARF frames
1273      * (always 0 for last frame buffer)
1274      */
1275     vp8_write_bit(bc, pc->ref_frame_sign_bias[GOLDEN_FRAME]);
1276     vp8_write_bit(bc, pc->ref_frame_sign_bias[ALTREF_FRAME]);
1277   }
1278
1279 #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
1280   if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
1281     if (pc->frame_type == KEY_FRAME) {
1282       pc->refresh_entropy_probs = 1;
1283     } else {
1284       pc->refresh_entropy_probs = 0;
1285     }
1286   }
1287 #endif
1288
1289   vp8_write_bit(bc, pc->refresh_entropy_probs);
1290
1291   if (pc->frame_type != KEY_FRAME) vp8_write_bit(bc, pc->refresh_last_frame);
1292
1293 #ifdef VP8_ENTROPY_STATS
1294
1295   if (pc->frame_type == INTER_FRAME)
1296     active_section = 0;
1297   else
1298     active_section = 7;
1299
1300 #endif
1301
1302   vp8_clear_system_state();
1303
1304 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1305   pack_coef_probs(cpi);
1306 #else
1307   if (pc->refresh_entropy_probs == 0) {
1308     /* save a copy for later refresh */
1309     memcpy(&cpi->common.lfc, &cpi->common.fc, sizeof(cpi->common.fc));
1310   }
1311
1312   vp8_update_coef_probs(cpi);
1313 #endif
1314
1315 #ifdef VP8_ENTROPY_STATS
1316   active_section = 2;
1317 #endif
1318
1319   /* Write out the mb_no_coeff_skip flag */
1320   vp8_write_bit(bc, pc->mb_no_coeff_skip);
1321
1322   if (pc->frame_type == KEY_FRAME) {
1323     write_kfmodes(cpi);
1324
1325 #ifdef VP8_ENTROPY_STATS
1326     active_section = 8;
1327 #endif
1328   } else {
1329     pack_inter_mode_mvs(cpi);
1330
1331 #ifdef VP8_ENTROPY_STATS
1332     active_section = 1;
1333 #endif
1334   }
1335
1336   vp8_stop_encode(bc);
1337
1338   cx_data += bc->pos;
1339
1340   oh.first_partition_length_in_bytes = cpi->bc->pos;
1341
1342   /* update frame tag */
1343   {
1344     int v = (oh.first_partition_length_in_bytes << 5) | (oh.show_frame << 4) |
1345             (oh.version << 1) | oh.type;
1346
1347     dest[0] = v;
1348     dest[1] = v >> 8;
1349     dest[2] = v >> 16;
1350   }
1351
1352   *size = VP8_HEADER_SIZE + extra_bytes_packed + cpi->bc->pos;
1353
1354   cpi->partition_sz[0] = *size;
1355
1356 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1357   {
1358     const int num_part = (1 << pc->multi_token_partition);
1359     unsigned char *dp = cpi->partition_d[0] + cpi->partition_sz[0];
1360
1361     if (num_part > 1) {
1362       /* write token part sizes (all but last) if more than 1 */
1363       validate_buffer(dp, 3 * (num_part - 1), cpi->partition_d_end[0],
1364                       &pc->error);
1365
1366       cpi->partition_sz[0] += 3 * (num_part - 1);
1367
1368       for (i = 1; i < num_part; ++i) {
1369         write_partition_size(dp, cpi->partition_sz[i]);
1370         dp += 3;
1371       }
1372     }
1373
1374     if (!cpi->output_partition) {
1375       /* concatenate partition buffers */
1376       for (i = 0; i < num_part; ++i) {
1377         memmove(dp, cpi->partition_d[i + 1], cpi->partition_sz[i + 1]);
1378         cpi->partition_d[i + 1] = dp;
1379         dp += cpi->partition_sz[i + 1];
1380       }
1381     }
1382
1383     /* update total size */
1384     *size = 0;
1385     for (i = 0; i < num_part + 1; ++i) {
1386       *size += cpi->partition_sz[i];
1387     }
1388   }
1389 #else
1390   if (pc->multi_token_partition != ONE_PARTITION) {
1391     int num_part = 1 << pc->multi_token_partition;
1392
1393     /* partition size table at the end of first partition */
1394     cpi->partition_sz[0] += 3 * (num_part - 1);
1395     *size += 3 * (num_part - 1);
1396
1397     validate_buffer(cx_data, 3 * (num_part - 1), cx_data_end, &pc->error);
1398
1399     for (i = 1; i < num_part + 1; ++i) {
1400       cpi->bc[i].error = &pc->error;
1401     }
1402
1403     pack_tokens_into_partitions(cpi, cx_data + 3 * (num_part - 1), cx_data_end,
1404                                 num_part);
1405
1406     for (i = 1; i < num_part; ++i) {
1407       cpi->partition_sz[i] = cpi->bc[i].pos;
1408       write_partition_size(cx_data, cpi->partition_sz[i]);
1409       cx_data += 3;
1410       *size += cpi->partition_sz[i]; /* add to total */
1411     }
1412
1413     /* add last partition to total size */
1414     cpi->partition_sz[i] = cpi->bc[i].pos;
1415     *size += cpi->partition_sz[i];
1416   } else {
1417     bc[1].error = &pc->error;
1418
1419     vp8_start_encode(&cpi->bc[1], cx_data, cx_data_end);
1420
1421 #if CONFIG_MULTITHREAD
1422     if (cpi->b_multi_threaded) {
1423       pack_mb_row_tokens(cpi, &cpi->bc[1]);
1424     } else
1425 #endif  // CONFIG_MULTITHREAD
1426       vp8_pack_tokens(&cpi->bc[1], cpi->tok, cpi->tok_count);
1427
1428     vp8_stop_encode(&cpi->bc[1]);
1429
1430     *size += cpi->bc[1].pos;
1431     cpi->partition_sz[1] = cpi->bc[1].pos;
1432   }
1433 #endif
1434 }
1435
1436 #ifdef VP8_ENTROPY_STATS
1437 void print_tree_update_probs() {
1438   int i, j, k, l;
1439   FILE *f = fopen("context.c", "a");
1440   int Sum;
1441   fprintf(f, "\n/* Update probabilities for token entropy tree. */\n\n");
1442   fprintf(f,
1443           "const vp8_prob tree_update_probs[BLOCK_TYPES] [COEF_BANDS] "
1444           "[PREV_COEF_CONTEXTS] [ENTROPY_NODES] = {\n");
1445
1446   for (i = 0; i < BLOCK_TYPES; ++i) {
1447     fprintf(f, "  { \n");
1448
1449     for (j = 0; j < COEF_BANDS; ++j) {
1450       fprintf(f, "    {\n");
1451
1452       for (k = 0; k < PREV_COEF_CONTEXTS; ++k) {
1453         fprintf(f, "      {");
1454
1455         for (l = 0; l < ENTROPY_NODES; ++l) {
1456           Sum =
1457               tree_update_hist[i][j][k][l][0] + tree_update_hist[i][j][k][l][1];
1458
1459           if (Sum > 0) {
1460             if (((tree_update_hist[i][j][k][l][0] * 255) / Sum) > 0)
1461               fprintf(f, "%3ld, ",
1462                       (tree_update_hist[i][j][k][l][0] * 255) / Sum);
1463             else
1464               fprintf(f, "%3ld, ", 1);
1465           } else
1466             fprintf(f, "%3ld, ", 128);
1467         }
1468
1469         fprintf(f, "},\n");
1470       }
1471
1472       fprintf(f, "    },\n");
1473     }
1474
1475     fprintf(f, "  },\n");
1476   }
1477
1478   fprintf(f, "};\n");
1479   fclose(f);
1480 }
1481 #endif