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